Collision detection 2d

How would I go about adding collisions to a 2d game

That can be either an easy question, or a complicated question depending on what your game requires.

The easy solution is just a simple box overlap, You define a Rectangle that represents the “Collision Box” for your objects. Each object has it’s own Collision Rectangle. You then loop through your objects and check to see if any of the Rectangles overlap.

Something like this, I have a method on my object:

    		public bool CollidesWithObject(BaseGameObject p_gameObject)
			if ((State != ObjectStates.Alive) || (p_gameObject.State != ObjectStates.Alive))
				return false;

			return CollisionRect.Intersects(p_gameObject.CollisionRect);


I can then do a simple if (a.CollidesWith(b)) do something…

This works fine for your objects if they never rotate or you don’t need an accurate collision detection.

If you need more advanced collision detection then you get into things like Circle Collision Detection, Pixel Perfect collision detection and Polygon Collision Detection.

Circle Collision detection is similar to the Box but requires a bit more work to determine if the circles overlap. A little more precise but not much better.

Pixel Perfect basically looks for any pixels that overlap between 2 images. This method is the most accurate, but also the slowest.

Polygon Collision Detection is you define a shape that roughly represents the shape of the image and then you see if the two Polygons intersect. A bit more complicated math if you take things like rotation and scale into account.

All these methods can be further optimized based on what your game requires. You don’t need (or want) to compare every object to every other object. That’s a lot of CPU time. You optimize by only comparing what you need to compare. If you’re looking to see if your shot hit something then you only need to check the objects that are closest to you. If an object is 100 pixels away from your projectile and the object is 32 x 32 and your projectile is 16 x 16, there is no way they would collide so you can skip the check. (this example is overly simplified).

What do you think is the best way to compare things only close to the object. Should i make a different bigger rectangle on the object and add every item it intersects with to the list and then loop trough them and check collision or do something else?

Check out a QuadTree. You can use this to query all objects within some given rectangle, so you can use that to see if anything intersects with the object you want to check collision for, or you can use a bigger rectangle to see if anything is nearby and do more refined collision detection.