O'Reilly logo

Professional HTML5 Mobile Game Development by Pascal Rettig

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Handling Collisions

Alien Invasion is slowly coming together. It now has a player, missiles, and enemies flying around the screen. Unfortunately, none of these pieces are interacting by blowing each other up as is expected in a save-the-planet-from-destruction shooter game.

The good news is that the majority of the hard work for handling collisions has already been done. The GameBoard object already knows how to take two objects and figure out if they are overlapping as well as determine if one object is colliding with any others of a specific type. All that’s necessary now is to add the appropriate calls to those collision functions.

For collisions, Alien Invasion can use two mechanisms. The first is to do proactive checks in every object’s step function against any objects it has an interaction with. The second would be to have a general collision phase where objects trigger collision events when they hit each other. The former is simpler to implement, whereas the latter offers better overall performance and can be better optimized. Alien Invasion is going to go the simpler route, but the platformer game built in Chapter 18, “Creating a 2-D Platformer,” uses the more complicated mechanism.

Adding Object Types

To ensure that objects collide only with objects that it makes sense for them to collide with, objects need to be assigned types. This was discussed at the beginning of the chapter but has not yet been implemented in the game. The first step is to determine the different ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required