Adding Enemies

A space shooter isn’t any fun without enemies, so next you will add some enemies into the game by creating an Enemy sprite class. Although there will be multiple types of enemies, they are all represented by the same class and differentiated only by different templates for their image and movement.

Calculating Enemy Movement

You define the movement for enemies with an equation that contains a few pluggable parameters that enable enemies to exhibit relatively complex behavior without a lot of code. The equation sets the velocity of an enemy at a given time since it was added to the board:

vx = A + B * sin(C * t + D)
vy = E + F * sin(G * t + H)

All the letters A through H represent constant numbers. Don’t let these equations intimidate you. All they say is that the velocity of an enemy is based on a constant value plus a value that repeats cyclically. (Using a sine enables the cyclical value.) Using an equation such as this allows the game to add enemies that twirl around the screen in interesting patterns and adds some dynamism to the game that a bunch of enemies flying in a straight line wouldn’t. Sines and cosines are used often in game development for animation because they provide a mechanism for smooth movement transitions. See Table 2-1 for a description of the effect each parameter A–H has on the movement of an enemy.

NOTE Parabolas created with quadratic equations ( a + bx + cx*x ) are also useful for this but don't provide periodic behavior, so they ...

Get Professional HTML5 Mobile Game Development now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.