C# XNA中的BoundingBox有些奇怪
我有一个奇怪的问题,边界框和东西,在使。 For循环无法正常工作,并导致变量不变的问题C# XNA中的BoundingBox有些奇怪,c#,visual-studio-2010,xna,C#,Visual Studio 2010,Xna,我有一个奇怪的问题,边界框和东西,在使。 For循环无法正常工作,并导致变量不变的问题 for (int i = 0; i < thing.Length; i++) { for (int j = 0; j < thing.Length; j++) { if (thing[i].bb.Intersects(thing[j].bb) && i != j)
for (int i = 0; i < thing.Length; i++)
{
for (int j = 0; j < thing.Length; j++)
{
if (thing[i].bb.Intersects(thing[j].bb) && i != j)
{
thing[i].spriteSpeed *= -1;
thing[j].spriteSpeed *= -1;
soundEffect.Play(0.2f, -1f, 0f);
}
}
}
问题是您两次都在更新这两个对象 考虑这样一种情况,列表中有两个项,它们的边界框重叠。通过你的循环,你会得到:
i == 0, j == 0: Skip because (i == j)
i == 0, j == 1: Reverse direction of [0] and [1]
i == 1, j == 0: Reverse direction of [1] and [0]
i == 1, j == 1: Skip because (i == j)
按照顺序操作,您已将项目颠倒了两次,将其返回到原始标题
为防止出现这种情况,并顺便减少处理完整对象列表所需的测试次数,
j
变量的起始值应始终高于i
,因为i Tnx Corey的所有比较都是如此。这对我来说很好。
struct Thing
{
public Texture2D myTexture;
public Vector2 spritePosition;
public Vector2 spriteSpeed;
public BoundingBox bb;
public Vector3 start, end;
}
i == 0, j == 0: Skip because (i == j)
i == 0, j == 1: Reverse direction of [0] and [1]
i == 1, j == 0: Reverse direction of [1] and [0]
i == 1, j == 1: Skip because (i == j)
for (int i = 0; i < thing.Length; i++)
{
for (int j = i + 1; j < thing.Length; j++)
{
if (thing[i].bb.Intersects(thing[j].bb))
{
thing[i].spriteSpeed *= -1;
thing[j].spriteSpeed *= -1;
soundEffect.Play(0.2f, -1f, 0f);
}
}
}