XNA 4.0中的碰撞检测不准确

时间:2013-02-26 09:01:28

标签: c# xna 2d collision-detection

我在小行星游戏中遇到2D碰撞检测的麻烦,我试图在旋转精灵时使用XNA。在子弹击中小行星(从它看来的每一侧)之前,碰撞一直发生,当船撞向小行星时也是不准确的。我使用矩阵来旋转由船发射的子弹,然后是小行星的矩阵,并在Xbox独立游戏论坛上使用每像素碰撞检测样本。

public static bool IntersectPixels(Matrix transformA, int widthA, int heightA, Color[] dataA, Matrix transformB, 
        int widthB, int heightB, Color[] dataB, float rotationA)
    {
        Matrix transformAToB = transformA * Matrix.Invert(transformB);

        Vector2 stepX = Vector2.TransformNormal(Vector2.UnitX, transformAToB);
        Vector2 stepY = Vector2.TransformNormal(Vector2.UnitY, transformAToB);

        Vector2 yPosInB = Vector2.Transform(Vector2.Zero, transformAToB);

        // For each row of pixels in A
        for (int yA = 0; yA < heightA; yA++)
        {
            // Start at the beginning of the row
            Vector2 posInB = yPosInB;

            // For each pixel in this row
            for (int xA = 0; xA < widthA; xA++)
            {
                // Round to the nearest pixel
                int xB = (int)Math.Round(posInB.X);
                int yB = (int)Math.Round(posInB.Y);

                // If the pixel lies within the bounds of B
                if (0 <= xB && xB < widthB &&
                    0 <= yB && yB < heightB)
                {
                    // Get the colors of the overlapping pixels
                    Color colorA = dataA[xA + yA * widthA];
                    Color colorB = dataB[xB + yB * widthB]

                    if (colorA.A != 0 && colorB.A != 0)
                    {
                        return true;
                    }
                }
                // Move to the next pixel in the row
                posInB += stepX;
            }
            // Move to the next row
            yPosInB += stepY;
        }
        // No intersection found
        return false;
    }

这里是我子弹的矩阵......原点和位置是子弹的Vector2属性

        private void UpdateTransform()
    {
        Transform =
                Matrix.CreateTranslation(new Vector3(-Origin, 0.0f)) *
                Matrix.CreateRotationZ((float)(Rotation)) *
                Matrix.CreateTranslation(new Vector3(Position, 0.0f));
    }

和小行星......

        private void UpdateTransform()
    {
        Transform =
                Matrix.CreateTranslation(new Vector3(-Origin, 0.0f)) *
                Matrix.CreateTranslation(new Vector3(Position, 0.0f));
    }

我是编程新手,我花了最近几天试图找出碰撞检测不准确的原因。我认为矩阵和可能的每像素碰撞检测方法可能导致问题,但我不确定是什么问题。非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

像素检测似乎不考虑碰撞中任一对象的旋转。您应该再研究一下Axis Aligned Bounding Boxes(AABB)。一个定向的边界框会使其碰撞相交以与对象旋转相同的旋转度旋转,并且在您的情况下效果更好。

看一下GameDev上的这篇文章,它有一些示例代码可以带你进一步:

https://gamedev.stackexchange.com/questions/15191/is-there-a-good-way-to-get-pixel-perfect-collision-detection-in-xna

相关问题