Colliding sprites in XNAExtras

The latest release of XNAExtras added support for sprite collisions, and allows the collision detection to be either bounding box (bbox) or pixel based. This is settable per sprite - some sprites can use bboxes and others can use pixels. The sprites will collide appropriately with each other even if they can't agree on how to do it.

Here's a simple tutorial for how to use the collision detection built into XNAExtras:

(1) Create an XSpriteManager.

  m_mgrSprites = new XSpriteManager();

(2) Create an XSprite.

  m_mgrSprites.AddTexture("tex", "texture.png", 64, 64);
XSprite s1 = m_mgrSprites.AddSprite("ball1", "tex");

(3) Create another XSprite so that you have something to collide with.

  XSprite s2 = m_mgrSprites.AddSprite("ball2", "tex");

(4) Enable collisions for these two sprites. For bounding box collisions, use:

  s1.SetCollideable(true);
s2.SetCollideable(true);

If you want pixel based collisions, use:

  s1.SetCollideable(true, XSpriteManager.CollisionFlags.Pixel, 0x40);
s2.SetCollideable(true, XSpriteManager.CollisionFlags.Pixel, 0x40);

where 0x40 is the alpha value of the sprite that defines the collideable part of the sprite - any alpha value >= this value will be added to the sprite's collision mask.

(5) In your Update method, after you've moved your sprites around a bit, you can check for collisions using CheckSpriteCollisions:

  List<XSpriteManager.SpriteCollision> aColl = m_mgrSprites.CheckSpriteCollisions();

This method returns a list of collisions that were detected. It returns null if there are no collisions.

(6) To handle collisions, simply walk the list of collisions and do whatever you feel is appropriate.

  if (aColl != null)
{
// handle the collisions
foreach (XSpriteManager.SpriteCollision c in aColl)
{
// if colliding with another sprite...
if (c.Type == XSpriteManager.CollisionType.Sprite)
{
// handle collision between c.Sprite and c.Sprite2
}
}
}

A working demo of collision detection is given in the CollisionDemo project included with the XNAExtras download.