C# XNA – Per Pixel Collision Detection on Rotated Objects

I’ve been working on a new project this week which requires per pixel collision detection, however all the game objects that I need to detect the collisions on need to be rotated dynamically which introduced a lot of trouble when trying to detect collisions.

To save anyone else from having to jump through hoops trying to figure this out I’ve put together a class called CollidableObject which will store a texture, position in world space and rotation factor and allow you to detect collisions between them by calling the IsColliding method.

In order for this class to work properly, you will also have to draw your textures using the rotation values (even if you aren’t rotating your sprite) like so:

// If the player is coliding with the enemy turn the screen red
if (this.player.IsColliding(this.enemy))
{
	GraphicsDevice.Clear(Color.Red);
}

// Draw the player to the screen
spriteBatch.Draw(this.player.Texture,
			this.player.Position,
			null, Color.White,
			this.player.Rotation,
			this.player.Origin,
			1.0f,
			SpriteEffects.None,
			0.0f);

It doesn’t support the use of sprite sheets or animation, however you should be able to modify it easily to suit your needs.

Click Here to View the Code on Pastebin

Posted in Programming, Tutorials at December 19th, 2011. No Comments.