Spritesheet per pixel collision XNA
- by Jixi
So basically i'm using this:
public bool IntersectPixels(Rectangle rectangleA, Color[] dataA,Rectangle rectangleB, Color[] dataB)
{
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);
for (int y = top; y < bottom; y++)
{
for (int x = left; x < right; x++)
{
Color colorA = dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width];
Color colorB = dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width];
if (colorA.A != 0 && colorB.A != 0)
{
return true;
}
}
}
return false;
}
In order to detect collision, but i'm unable to figure out how to use it with animated sprites.
This is my animation update method:
public void AnimUpdate(GameTime gameTime)
{
if (!animPaused)
{
animTimer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (animTimer > animInterval)
{
currentFrame++;
animTimer = 0f;
}
if (currentFrame > endFrame || endFrame <= currentFrame || currentFrame < startFrame)
{
currentFrame = startFrame;
}
objRect = new Rectangle(currentFrame * TextureWidth, frameRow * TextureHeight, TextureWidth, TextureHeight);
origin = new Vector2(objRect.Width / 2, objRect.Height / 2);
}
}
Which works with multiple rows and columns.
and how i call the intersect:
public bool IntersectPixels(Obj me, Vector2 pos, Obj o)
{
Rectangle collisionRect = new Rectangle(me.objRect.X, me.objRect.Y, me.objRect.Width, me.objRect.Height);
collisionRect.X += (int)pos.X;
collisionRect.Y += (int)pos.Y;
if (IntersectPixels(collisionRect, me.TextureData, o.objRect, o.TextureData))
{
return true;
}
return false;
}
Now my guess is that i have to update the textureData everytime the frame changes, no?
If so then i already tried it and miserably failed doing so :P
Any hints, advices?
If you need to see any more of my code just let me know and i'll update the question.
Updated almost functional collisionRect:
collisionRect = new Rectangle((int)me.Position.X, (int)me.Position.Y, me.Texture.Width / (int)((me.frameCount - 1) * me.TextureWidth), me.Texture.Height);
What it does now is "move" the block up 50%, shouldn't be too hard to figure out.
Update:
Alright, so here's a functional collision rectangle(besides the height issue)
collisionRect = new Rectangle((int)me.Position.X, (int)me.Position.Y, me.TextureWidth / (int)me.frameCount - 1, me.TextureHeight);
Now the problem is that using breakpoints i found out that it's still not getting the correct color values of the animated sprite.
So it detects properly but the color values are always:
R:0 G:0 B:0 A:0
??? disregard that, it's not true afterall =P
For some reason now the collision area height is only 1 pixel..