Unity有效地查找列表中A和B之间的差异

问题描述 投票:1回答:1

我试图计算2点之间的数字差异,从大约90点的列表。我到目前为止的代码:

int positiveCounter = 0;
        int positiveResetCounter = currentWayPointID;
        int negativeCounter = 0;
        int negativeResetCounter = currentWayPointID;
        while ((currentWayPointID + positiveResetCounter) != pos)
        {
            positiveCounter++;
            positiveResetCounter++;
            if(positiveResetCounter > navigationTrack.AllWayPoints.Count)
            {
                positiveResetCounter = 0;
            }
        }
        while((currentWayPointID+negativeResetCounter) != pos)
        {
            negativeCounter++;
            negativeResetCounter--;
            if(negativeResetCounter < 0)
            {
                negativeResetCounter = navigationTrack.AllWayPoints.Count;
            }
        }
        if(positiveCounter <= negativeCounter)
        {
            MoveForward();
        }
        else if(negativeCounter < positiveCounter)
        {
          //  MoveBack();
        }

这可以按预期工作,但对于更新来处理它太多了。我怎么能以较少的税收方式做到这一点?为了给出更多的背景信息,我列出了每个车辆移动到最接近我的鼠标位置的路点和车辆。路径是圆形的,因此最后一个航路点首先连接(索引0)。我试图确定每个航路点的最短路径,以便前进或后退,上面的代码是我尝试计算的方法。我不是在寻找一种让它移动的方法,因为它已经有效了。

c# unity3d waypoint
1个回答
1
投票

我假设pos是您想要到达的航点的目标指数。

而不是while循环和索引转换,你可以直接比较索引:

假设你有像这样的航点列表

[WP0, WP1, WP2, WP3, WP4, ... WPn]

所以可用的索引是0n,列表长度n+1

让我们说currentWayPointID = npos = 2

你想知道的是,倒退或前进是否更快。所以你想比较哪个差异较小:

倒退

n - 2 // simply go steps backwards until reaching 2

或使用虚拟扩展列表前进

(n+1) + 2 - n; // add the length of the list to the target index

或者想象它

                 [WP0,   WP1,   WP2,   WP3,   WP4, ... WPn]

index:              0,     1,     2,     3,     4, ...     n
extended index: n+1+0, n+1+1, n+1+2, n+1+3, n+1+4, ... n+n+1

所以为了概括你首先要检查currentwaypointID是在pos之前还是之后

bool isForwards = true;
if(currentwaypointID >= pos)
{
    if(currentwaypointID  - pos < navigationTrack.AllWayPoints.Count + pos - currentwaypointID)
    {
        isForwards = false;
    }
}
else
{
    if(pos - currentwaypointID > navigationTrack.AllWayPoints.Count + currentwaypointID - pos)
    {
        isForwards = false;
    }
}

if(isForwards)
{
    MoveForward();
}
else
{
    MoveBack();
}
© www.soinside.com 2019 - 2024. All rights reserved.