Spacefight – Things are moving, but do they collide? – Part 7

Now the game is as far in the development phase and things are moving around on the screen! In order to put some logic into the game I’ll need some kind of a collision detection. I will use a very simple way of collision detection. I’ll start by adding a rectangle to each gameobject, and update this rectangle each iteration in the game loop. This will update the x and y coordinates of the rectangle and it’s width and height. Below is an image (the first image of the game!) when the rectangles are marked red.

Spacefight with rects

Each iteration the game loop will send the entire list of game objects into my collision detection function. This will loop through each game object. For each every game object it will iterate through the list again and compare object1 rectangle against object2 rectangle and see whether they intersect.

So let say that the current game object in the iteration is an enemy object, while doing the sub-iteration it finds that an object of the type rocket intersects the enemy object and adds into a vector. When it’s done with the sub-iteration it sends the list of intersecting gameobjects to the enemy object.

The code in the enemy object checks what type it hits. If it’s a rocket that has been launched by another enemy it won’t do anything. Since it should not collide with it’s own rockets it fires. However if the rocket is of a player type it will get the damage, by asking the rocket how much damage it delivers and lose the appropriate amount of health. And mark the rocket for destruction.

The same thing happens to the rocket object when it collides with a enemy or a player. Depending on the type of rocket it will create an explosion game object, and the rocket will seem to turn into a explosion.

This code might have plenty of rooms for optimization, since it does a lot of iterations. If anyone has any ideas, please let me know.

Posted in Game programming Tagged with: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *