Game Development Reference
In-Depth Information
Listing 9-19. Starting the Game with Some Sounds and a Simple Game Loop
function startGame() {
var assets = game.assets;
stage.removeAllChildren();
createjs.Sound.play(assets.EXPLOSION)
createjs.Sound.play(assets.SOUNDTRACK,0,0,0,10,.5);
createjs.Ticker.on('tick', onTick);
}
function onTick(e) {
count++;
checkForSpawn();
stage.update();
}
An explosion is first played as an effect for the button click. Then some background music is started, which will
loop 10 times and play at a volume of .5. Finally, the ticker is set to fire the onTick function. This function increments
the count variable, checks if a new asteroid should be created, and finally updates the stage . The asteroid functions
are written next (see Listing 9-20).
Listing 9-20. The Game Functions That Create and Destory Asteroids
function checkForSpawn() {
if (count == spawnDelay) {
spawnAsteroid();
count = 0;
}
}
function spawnAsteroid() {
var a = new game.Asteroid(spritesheet);
a.x = Math.random() * canvas.width;
a.on('click', onAsteroidClick);
a.on(a.EXPLOSION_COMPLETE, destroyAsteroid);
stage.addChild(a);
}
function onAsteroidClick(e) {
var asteroid = e.target;
asteroid.explode();
}
function destroyAsteroid(e) {
var asteroid = e.target;
stage.removeChild(asteroid);
asteroid = null;
}
An asteroid is created when the count has reached the predetermined value by calling the spawnAsteroid
function, which will then reset the counter back to 0. Each asteroid is an instance of the Asteroid class and given a
random x value. Two listeners are then set on the sprite, one for a click and another for the event you created inside of
the sprite that dispatches after its explosion animation.
Search WWH ::




Custom Search