1

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

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)。我正在尝试确定到每个航路点的最短路径以便前进或后退,上面的代码是我尝试计算要走的路。我不是在寻找一种让它移动的方法,因为它已经奏效了。

4

1 回答 1

1

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

while您可以直接比较索引,而不是循环和索引移位:

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

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

所以可用的索引是0to n,列表长度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();
}
于 2019-02-25T06:01:02.060 回答