【问题标题】:Something strange with BoundingBox in XNAXNA 中的 BoundingBox 有点奇怪
【发布时间】:2013-12-11 15:33:02
【问题描述】:

我对 BoundingBox 和制作中的东西有奇怪的问题。 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)
                {
                    thing[i].spriteSpeed *= -1;
                    thing[j].spriteSpeed *= -1;
                    soundEffect.Play(0.2f, -1f, 0f);
                }
            }
        }

但是如果我将 j 变量更改为静态数字,比如零,代码就可以正常工作。

for (int i = 0; i < thing.Length; i++)
        {
            for (int j = 0; j < thing.Length; j++)
            {
                if (thing[i].bb.Intersects(thing[0].bb) && i != 0)
                {
                    thing[i].spriteSpeed *= -1;
                    thing[0].spriteSpeed *= -1;
                    soundEffect.Play(0.2f, -1f, 0f);
                }
            }
        }

附: Thing 是一个看起来像这样的结构:

struct Thing
    {
        public Texture2D myTexture;
        public Vector2 spritePosition;
        public Vector2 spriteSpeed;
        public BoundingBox bb;
        public Vector3 start, end;
    }

【问题讨论】:

  • Tnx 科里。它对我来说很好。

标签: c# visual-studio-2010 xna


【解决方案1】:

问题是您两次都更新了这两个对象。

考虑列表中有两个项目并且它们的边界框重叠的情况。通过你的循环你得到:

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 高 1,因为对 i &lt;= 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);
        }
    }
}

这具有将比较次数减少大约一半的效果(实际上是(n^2-n)/2,如果我们准确的话)以及消除所有双重反转。列表中每个可能的项目组合只测试一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多