I am writing a SharpDx.Toolkit(XNA) Game. I searched in the internet how to program a collision detection, and I've found this:
static bool perPixel(Rectangle rectangleA, Color[] dataA, Rectangle rectangleB, 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++)
{
if (dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width] != new Color(0, 0, 0, 0) && dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width] != new Color(0, 0, 0, 0))
{
// 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;
}
This code works fine, but only on non-rotating sprites. So I tried to add a Matrix Transformation, but it doesn't work.
Does anyone has an idea, how to do this?
Thank you, Christian
EDIT:The game is an 2D Game.
Per-pixel collision is overkill in most cases and i would not recommend it for anything else than programming practice.
You can almost always apply other methods to find collissions which introduces less bugs and require less performance.
You can either use a physics-engine or find another method.
Some methods i believe would work well in your case:
With these methods you just check if the bounds intersect instead of checking every single pixel against each-other.