【问题标题】:Unity Finding difference between A and B in a list efficientlyUnity 有效地在列表中查找 A 和 B 之间的差异
【发布时间】:2019-02-24 21:14:54
【问题描述】:

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

【问题讨论】:

  • 您的代码似乎有些不对劲。为什么要将positiveResetCounternegativeResetCounter 初始化为currentWayPointID?据我所知,它们表示相对于 currentWayPointID 的偏移/相对位置。他们不应该因此用 0 来初始化吗?
  • 顺便说一下,列表中的 90 个点应该不会导致性能问题。在最坏的情况下,两个 while 循环一起只能累计循环 90 次(应该快如闪电);如果它需要更多的时间,你的逻辑在某个地方被打破了,不知何故
  • 它们只是当列表上的数字达到0或list.count数量时重置的手段。它们只是与向量无关的整数
  • 如果是这样,您能解释一下您使用的while 循环中的表达式吗?我的意思不是你应该向我解释你相信他们在做什么,而是看看并尝试理解他们实际上在做什么。我建议您使用调试器(尤其是它的单步功能)并逐步执行您的代码逻辑,同时在每一步观察所有涉及的变量/字段/等的内容和变化。如果你玩这个几次,它应该会更清楚逻辑可能被破坏的地方以及为什么它显然会消耗这么多时间

标签: c# unity3d waypoint


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多