如何遍历对象数组C#的列表?

时间:2018-06-29 16:27:57

标签: c# arrays list loops collision-detection

我正在建立2D物理模拟,目前正在研究旋转方块之间的碰撞。

我的碰撞检测算法是这样的:

  • 宽相
    • 检查框的轴对齐边界框是否重叠
    • 如果这样,请将重叠的2个框放入2元素数组中,然后将此数组放入列表(broadPhaseCollisionList)
  • 窄相
    • 遍历broadPhaseCollisionList并检查碰撞(由Box []表示)以判断它们是否真的在碰撞

问题在于,当出现广谱相冲突时,第一个Console.WriteLine()打印出正确的Box索引,但是第二个Console.WriteLine()始终打印出“ ObserverBox:2 ObservedBox:3”。 / p>

这是我的代码:

        //set all boxes to "not colliding"
        foreach (Box box in boxList)
        {
            box.colliding = false;
        }

        List<Box[]> broadPhaseCollisionList = new List<Box[]>();
        Box[] collisionPair = new Box[2];

        for (int i = 0; i < boxList.Count; i++)
        {
            Box observerBox = boxList[i];

            for (int j = i + 1; j < boxList.Count; j++)
            {
                Box observedBox = boxList[j];

                if (observerBox != observedBox)
                {
                    collisionPair[0] = observerBox;
                    collisionPair[1] = observedBox;

                    if (TestAABBOverlap(observerBox.aabb, observedBox.aabb))
                    {
                        observerBox.colliding = true;
                        observedBox.colliding = true;

                        broadPhaseCollisionList.Add(collisionPair);
                        //timer.Stop();
                        Box[] box = broadPhaseCollisionList[0];
                        Console.WriteLine("ObserverBox: " + box[0].index + " ObservedBox: " + box[1].index);
                    }
                }
            }
        }

        for (int i = 0; i < broadPhaseCollisionList.Count; i++)
        {
            Box[] collision = broadPhaseCollisionList[i];
            Box observerBox = collision[0];
            Box observedBox = collision[1];

            Console.WriteLine("ObserverBox: " + observerBox.index + " ObservedBox: " + observedBox.index);
            Console.WriteLine("/-------------------------------------------------------------------------------");
        }

为什么这不起作用?

3 个答案:

答案 0 :(得分:3)

我相信这里的问题是,您每次迭代仅在collisionPair上添加对broadPhaseCollisionList数组的引用(您一遍又一遍地添加相同的引用)。同时,collisionPair项会随着每次迭代的最新冲突而更新。

在循环结束时,collisionPair包含最后一个冲突对,broadPhaseCollisionList包含[collisionCount]个都指向同一数组的项。

要解决此问题,应在每次将collisionPair设置为 new 数组之前,将其添加到列表中:

if (observerBox != observedBox && TestAABBOverlap(observerBox.aabb, observedBox.aabb))
{
    observerBox.colliding = true;
    observedBox.colliding = true;

    broadPhaseCollisionList.Add(new[] {observedBox, observerBox});

答案 1 :(得分:0)

您总是在写box [0]和box [1]的值。
您的行可能应该是:

Console.WriteLine("ObserverBox: " + observerBox.index + " ObservedBox: " + observedBox.index);

答案 2 :(得分:-1)

您必须向下钻取。

broadPhaseCollisionList[i].observerBox[0].ToString()