与纹理旋转的像素完美碰撞



我有像素完美的碰撞,但它仅适用于以 0 弧度旋转的纹理。 这是我确定像素完美碰撞的代码-

public static bool IntersectPixels(Texture2D sprite, Rectangle rectangleA, Color[] dataA, Texture2D sprite2, Rectangle rectangleB, Color[] dataB)
{
    sprite.GetData<Color>(dataA);
    sprite2.GetData<Color>(dataB);
    // Find the bounds of the rectangle intersection
    int top = Math.Max(rectangleA.Top, rectangleB.Top);
    int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
    int left = Math.Max(rectangleA.Left, rectangleB.Left);
    int right = Math.Min(rectangleA.Right, rectangleB.Right);
    // Check every point within the intersection bounds
    for (int y = top; y < bottom; y++)
    {
        for (int x = left; x < right; x++)
        {
            // Get the color of both pixels at this point
            Color colorA = dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width];
            Color colorB = dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width];
            // If both pixels are not completely transparent,
            if (colorA.A != 0 && colorB.A != 0)
            {
                // then an intersection has been found
                return true;
            }
        }
    }
    // No intersection found
    return false;
}

旋转时我的碰撞有问题。 如何检查与旋转精灵的像素冲突? 谢谢,任何帮助不胜感激。

理想情况下,您可以使用矩阵执行所有转换。这应该不是帮助程序方法的问题。如果您使用矩阵,则可以轻松扩展程序,而无需更改碰撞代码。到目前为止,您可以使用矩形的位置表示翻译。

假设对象 A 具有转换transA对象 B 具有transB 。然后,您将遍历对象 A 的所有像素。如果像素不透明,请检查对象 B 的哪个像素位于此位置,并检查该像素是否透明。

棘手的部分是确定对象 B 的哪个像素位于给定位置。这可以通过一些矩阵数学来实现。

您知道对象 A 空间中的位置,首先,我们希望将此局部位置转换为屏幕上的全局位置。这正是transA所做的。之后,我们要将全局位置转换为对象 B 空间中的局部位置。这是transB的反面。因此,我们必须使用以下矩阵转换 A 中的局部位置:

var fromAToB = transA * Matrix.Invert(transB);
//now iterate over each pixel of A
for(int x = 0; x < ...; ++x)
    for(int y = 0; y < ...; ++y)
    {
        //if the pixel is not transparent, then
        //calculate the position in B
        var posInA = new Vector2(x, y);
        var posInB = Vector2.Transform(posInA, fromAToB);
        //round posInB.X and posInB.Y to integer values
        //check if the position is within the range of texture B
        //check if the pixel is transparent
    }

最新更新