HTML and CSS Reference
In-Depth Information
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 colli-
sion 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 com-
plicated 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 object types the game has and add some constants to keep from
having to use magic numbers in the code.
Add the code from Listing 2-8 to the top of game.js to define five different types of objects.
Listing 2-8: Object Types
var OBJECT_PLAYER = 1,
OBJECT_PLAYER_PROJECTILE = 2,
OBJECT_ENEMY = 4,
OBJECT_ENEMY_PROJECTILE = 8,
OBJECT_POWERUP = 16;
NOTE Each of these types shown in Listing 2-8 is a power of two, which is an efficiency optimization to
enable the use of bitwise logic as discussed earlier.
Next, add three lines to game.js setting the type of each Sprite at an appropriate spot after each
Sprite 's prototype assignment code:
PlayerShip.prototype = new Sprite();
PlayerShip.prototype.type = OBJECT_PLAYER;
...
PlayerMissile.prototype = new Sprite();
PlayerMissile.prototype.type = OBJECT_PLAYER_PROJECTILE;
...
 
 
 
Search WWH ::




Custom Search