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

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 ...

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