Game Development Reference
In-Depth Information
The
Asteroid
class has a few properties for speed and to store the bounds of the sprite. There is also a string that
will be used for the event that will be dispatched when destroyed. The asteroid has four possible frames to randomly
pick from, which are shown in the sprite sheet image in Figure
9-1
.
Figure 9-1.
Exploding Asteroids sprite sheet - gameSprites.png
The sprite sheet also includes an explosion animation that will play when the asteroid is clicked and destroyed.
The registration point is centered so the rock can spin as it moves down the screen in the
move
method, which runs on
the
tick
. If the asteroid makes it past the bottom of the stage without being destroyed, it is recycled by resetting
its
y
position back at the top.
Next are the methods that handle its explosion. The
explode
method will be called from the game when the
asteroid is clicked. The speed is slowed down for effect, and an event listener is set for when the explosion animation
has ended. Next, the animation is played, and the explosion sound is referenced from the
AssetsManager
instance
that will be created in the game code. Using
SoundJS
, the sound is played.
When the animation is complete, the
explosionComplete
handler is called, which stops the animation and
dispatches the
explosion complete
event, which is set to the property
EXPLOSION_COMPLETE
.
With the
AssetManager
and
Asteroid
classes complete, it's time to create the game.
Creating the Exploding Asteroids Game
The game code will be written in the
explodingAsteroids.js
file. Open the file and start by declaring the game
variables and writing the
init
function, shown in Listing 9-16.
Listing 9-16.
Game Variables and init Function
window.game = window.game || {};
var canvas, stage, assets, preloader, spritesheet;
var spawnDelay = 40;
var count = 0;
function init() {
canvas = document.getElementById('canvas');
stage = new createjs.Stage(canvas);
createjs.Ticker.setFPS(30);
game.assets = new game.AssetManager();
preloadAssets();
}
The
spawnDelay
value will be the count at which another asteroid will be spawned, which is determined by the
incrementing
count
variable. The
init
function, which is called when the body loads, sets up the
stage
and
Ticker
.
An instance of
AssetManager
is created and set to the
game
namespace, which will be accessible throughout the game.
Next, the assets are loaded using the functions shown in Listing 9-17.