我有像素完美的碰撞,但它只适用于以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;
}
旋转时我的碰撞有问题。如何检查旋转精灵的像素碰撞?谢谢,任何帮助表示赞赏。
答案 0 :(得分:0)
理想情况下,您可以使用矩阵排出所有变换。这不应该是辅助方法的问题。如果使用矩阵,则无需更改冲突代码即可轻松扩展程序。到目前为止,您可以使用矩形的位置表示平移。
假设对象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
}