首页 > 解决方案 > Unity3D:检查大量点的最快方法

问题描述

这是我的问题。我有一个 Vector3 数组(大小 > 10,000)。我的对象应该在最短的时间内遍历每个点。例如,在下面的代码中,对象每帧从一个点移动到另一个点。但是当点的数组很大时,遍历每个点需要超过 2 分钟。

public class PlayerMovement : MonoBehaviour{

        Vector3[] points = new Vector3[10000];
        int i = 0;
        private void Update()
        {
                transform.position = points[i];
                 i++;
        }
}

有没有更快的方法来做到这一点?如果有人可以建议我一种更快的方法来执行此操作,我将不胜感激。

标签: c#unity3d

解决方案


定义一个速度,通过将它乘以计算出你在当前帧上行驶了多少Time.deltaTime

用于Vector3.MoveTowards向下一点移动。重复,直到您用完该帧的距离或用完点。

您需要能够在每帧中留下多条痕迹,因此将添加痕迹的过程放入void LeaveTrace(Vector3 position)方法中,以便我们可以在必要时调用它。

您可以设置目标索引来确定如何遍历点数组,但如果在遍历中间更改遍历方向,请确保更新源索引。

共:

public class PlayerMovement : MonoBehaviour{

    Vector3[] points = new Vector3[10000];
    public float speed = 1f;
    private int curSourceIndex = 0;

    private int goalIndex = 0; // no goal

    private void Update()
    {
        if (goalIndex != curSourceIndex)
        {
            MoveBus();
        }
    }

    private void MoveBus()
    {
        int step = goalIndex > curSourceIndex ? 1 : -1;

        float distLeft = speed * Time.deltaTime;

        while (distLeft > 0 && curSourceIndex != goalIndex)
        {
            Vector3 curTarget = points[curSourceIndex + step];

            Vector3 curPos = transform.position;

            Vector3 newPos = Vector3.MoveTowards(curPos, curTarget, distLeft);

            distLeft -= (newPos-curPos).magnitude;

            if (newPos == curTarget) 
            {
                // Leave trace at each point reached
                LeaveTrace(newPos)

                curSourceIndex += step;
            }

            transform.position = newPos;
        }

    }

    public void SetGoalIndex(int index)
    {
        if (index < 0 || index >= points.length) return; // or throw/log etc here

        // Do any appropriate modification to curSourceIndex
        if (points[curSourceIndex] != curPos) 
        {
            // If we were going up but we're going down (or back to where we were), 
            // increase source index
            if (goalIndex > curSourceIndex && index <= curSourceIndex) 
            { 
                curSourceIndex +=1;
            }
            // if vice versa, decrease source index
            else if (goalIndex < curSourceIndex && index >= curSourceIndex)  
            {
                curSourceIndex -=1;
            }   
        }

        goalIndex = index;
    }

    void LeaveTrace(Vector3 pos)
    {
        // leave a trace at the pos location
    }
}

推荐阅读