Creating Games

Creating games involves all the subjects covered in this document up to this point: drawing shapes, images, and text; animation; adding touch and mouse controls; and triggering sounds. In addition, for many games you need to detect collisions, which may involve reading the canvas pixels.

Collision Detection

There are several ways to detect collisions between objects in a game.

You can compare the x and y coordinates of the various elements—this is best for detecting collisions with walls or between rectangular objects.

If at least one of the objects is a shape, you can use the isPointInPath(x,y) method to see if a given point is inside the path—this is best for detecting collisions between missiles and shapes.

You can examine the canvas bitmap, to see if a target color is anywhere inside a given area—this is best when the target is a unique color.

Space Arcade Game

The example in Listing 16-1 is the skeleton of an arcade game, as illustrated in Figure 16-1. It has a scrolling background, a ship that responds to touch or mouse control, missiles that fire when the mouse is clicked or the screen is tapped, and targets that follow a path. The game detects collisions between missiles and targets, and maintains a score that advances when a target is hit.

All the elements of a side-scrolling arcade game are present. With a little work, you can modify the skeleton to support any number of arcade shoot-em-ups.

Figure 16-1  Space arcade game

Listing 16-1  Space arcade game

    Space Arcade Game
    
    
    
            style="position:absolute;top:0;left:0">
    
    

Loony Lander Game

The example in Listing 16-2 is a complete game, including sound effects, simulating a Lunar Excursion Module (LEM) landing on the moon. This game uses PNG images—scaled and rotated—as sprites over a fixed background. The game has two custom controls, a button and a slider, created using CSS-styled div elements, to control thrust and rotation. The controls respond to touch or mouse input. A very simple physics model adds gravity to the LEM at regular intervals. The game is illustrated in Figure 16-2.

Figure 16-2  Lander game

Listing 16-2  Lander game

    lander
    
    
    
    
    
    
    
 
    
 
    
    
 
    
         onmousedown="thrustDown()" onmouseup="thrustUp()"
         ontouchstart="thrustDown()" ontouchend="thrustUp()">
        Thrust
    
 
    
         onmousedown="mouseDown()" onmousemove="mouseXY()"
         ontouchstart="touchXY()" ontouchmove="touchXY()">
        
        
            
            Spin
        
    
 
    
    

        To win, land with velocity X < 1, Y < 1, Rot < 0.1