Sign in to follow this  

[XNA] Problem with 2D Pixel Collisions

Recommended Posts

Andy474    694
Hey guys, quick overview of what im attempting. I have a Player sprite draw on the screen, this is rotated to follow the mouse.

I also have a collision map, which is constructed by passing an int[,] to genreate a texture using a render target. So I end up with a collision Texture.

I am trying to detect a collion with this Collision texture and seem to be going wrong. I have followed the tutorial here App hub

public bool CanMove(Player player, Camera camera, Vector2 moveDir)
/* Todo:
* Calulate the Rectangle of the Player
* Move this rectangle by MoveDirection to get the Rectangle on the Collision Map we want to get
* Check these two Rectangles for pixel Collisions

// Calulate the Rectangle of the Player
Matrix rotationmatrix = Matrix.CreateRotationZ(player.Rotation);
Rectangle boundingPlayer = player.GetCollisonRect();

// Move this rectangle by MoveDirection to get the Rectangle on the Collision Map we want to get
Rectangle collisionRect = new Rectangle(
boundingPlayer.X + (int)moveDir.X,
boundingPlayer.Y + (int)moveDir.Y,

//Get the Color Data for each of these Rectangles
Color[] playerData = new Color[player._tPlayerTexture.Width * player._tPlayerTexture.Height];
Color[] CollisionData = new Color[_collisionTexture.Width * _collisionTexture.Height];
CollisionData = GetPixelData(collisionRect);

//Rotate both these Rectangles
//boundingPlayer = CalculateBoundingRectangle(boundingPlayer, rotationmatrix);
//collisionRect = CalculateBoundingRectangle(collisionRect, rotationmatrix);

// Check these two Rectangles for pixel Collisions
//Check them to see if they intersect to avoid useless calcs
if (boundingPlayer.Intersects(collisionRect))
if (IntersectPixels(boundingPlayer, playerData, collisionRect, CollisionData))
return false;

//We say we always can move, unless we already broke out
return true;

The full Code File

This function supposed to decide if the Player can mvoe, however there are a few problem I am stuggling to get my head around.

1/ When I DONT rotate the Collision Rectangle

//boundingPlayer = CalculateBoundingRectangle(boundingPlayer, rotationmatrix);
//collisionRect = CalculateBoundingRectangle(collisionRect, rotationmatrix);

My player can move, but not close to the Collision wall at all and then he gets stuck and cant move

2/ If I uncomment the lines and move the rectangle (i get an array out of bounds excecption in the Intersect Pixels function

I am pretty sure i am just not approching it properly or doing simthing stupid, can anyone help me out? its been buggin me for hrs now hehe

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this