For first, I want to say, that I'm using this code for per pixel collision detection:
public bool CollidesWith(Sprite other)
{
// Default behavior uses per-pixel collision detection
return CollidesWith(other, true);
}
public bool CollidesWith(Sprite other, bool calcPerPixel)
{
// Get dimensions of texture
int widthOther = other.Texture.Width;
int heightOther = other.Texture.Height;
int widthMe = Texture.Width;
int heightMe = Texture.Height;
if (calcPerPixel && // if we need per pixel
((Math.Min(widthOther, heightOther) > 10) || // at least avoid doing it
(Math.Min(widthMe, heightMe) > 10))) // for small sizes (nobody will notice :P)
{
return Rectangle.Intersects(other.Rectangle) // If simple intersection fails, don't even bother with per-pixel
&& PerPixelCollision(this, other);
}
return Rectangle.Intersects(other.Rectangle);
}
public bool PerPixelCollision(Sprite a, Sprite b)
{
// Get Color data of each Texture
Color[] bitsA = new Color[a.Texture.Width * a.Texture.Height];
a.Texture.GetData(bitsA);
Color[] bitsB = new Color[b.Texture.Width * b.Texture.Height];
b.Texture.GetData(bitsB);
// Calculate the intersecting rectangle
int x1 = Math.Max(a.Rectangle.X, b.Rectangle.X);
int x2 = Math.Min(a.Rectangle.X + a.Rectangle.Width, b.Rectangle.X + b.Rectangle.Width);
int y1 = Math.Max(a.Rectangle.Y, b.Rectangle.Y);
int y2 = Math.Min(a.Rectangle.Y + a.Rectangle.Height, b.Rectangle.Y + b.Rectangle.Height);
// For each single pixel in the intersecting rectangle
for (int y = y1; y < y2; ++y)
{
for (int x = x1; x < x2; ++x)
{
// Get the color from each texture
Color a1 = bitsA[(x - a.Rectangle.X) + (y - a.Rectangle.Y) * a.Texture.Width];
Color b1 = bitsB[(x - b.Rectangle.X) + (y - b.Rectangle.Y) * b.Texture.Width];
if (a1.A != 0 && b1.A != 0) // If both colors are not transparent (the alpha channel is not 0), then there is a collision
{
return true;
}
}
}
// If no collision occurred by now, we're clear.
return false;
}
this code is in my "Sprite" struct. It works fine on Windows, OpenGL (MonoGame Cross Platform Desktop Project), Android and on Windows UWP.
But on iOS when I call the Sprite.CollidesWith(...);
my program stops rendering screen. Anything works but it can't render new frames (it renders static image). (I added click sound to test if program crashed. (after freeze when I click screen, then i can hear the sound))
Problem is on this line:
a.Texture.GetData(bitsA);
I searched the web and i found that Texture2D.GetData<> is not implemented on iOS... soo, is there any possibility to make pixel-perfect collision detection on iOS? (without calling GetData<>)
Sorry for any mistakes, I'm new to this forum. And thanks for any help.