我正在建立2D物理模拟,目前正在研究旋转方块之间的碰撞。
我的碰撞检测算法是这样的:
问题在于,当出现广谱相冲突时,第一个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("/-------------------------------------------------------------------------------");
}
为什么这不起作用?
答案 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()