Game Development Reference
In-Depth Information
After setting the intial values of a few instance variables, the
setListeners
method is called. This method sets up
the event listeners for the level, which pertain to the events from each enemy that will bubble up from the enemy grid
container. These events will be dispatched after the animations are complete when an enemy is attacked or destroyed.
Much more on these events will be covered in the “Attacking the Enemies” section.
The
hero
instance is created in the
createHero
method. The class was covered already, so you know that
everything that needs to be done with it is handled within its initialization. A background graphic is next added to the
container within
addBG
.
Next, it's time to add the enemies. There are two types of levels. One is
field
and the other is called
boss.
Most of
the time it will be a normal field battle, which will call the
populateGrid
method. If the level should bring a single boss
enemy,
addBoss
is called instead. Both of these methods will add enemy objects to the
enemyHolder
container, which
is added to the game at the end of the
addEnemies
method. These enemy-creating functions will be covered next.
Populating the Enemies
The enemies are created on a grid. The points on this grid were hard-coded inside of the
grid
property. The
populateGrid
will use these points when creating the enemies (see Listing 14-23).
Listing 14-23.
Game.js - Adding the Enemies to the Level
p.populateGrid = function () {
var i, startPoint, enemy, point, enemyType;
var enemies = this.levelData.enemies;
var len = enemies.length;
this.enemyHolder = new createjs.Container();
this.enemyHolder.x = this.gridPos.x;
this.enemyHolder.y = this.gridPos.y;
this.enemies = [];
for (i = 0; i < len; i++) {
point = this.grid[i];
enemyType = enemies[i];
enemy = new game.Enemy(enemyType);
enemy.x = point.x;
enemy.y = point.y;
enemy.on('click', this.attackEnemy, this);
this.enemyHolder.addChild(enemy);
this.enemies[i] = enemy;
}
}
The loop runs through the number of enemies assigned to the current level. This array is retrieved from the level
data's
enemies
property. The enemy type, which is the string value from the current array index in the loop, is passed
into the enemy object. In the loop, the location point for each enemy is determined by the
grid
array. A
click
event
listener is then assigned to each enemy, which will fire the
attackEnemy
event handler. Finally, each
enemy
instance
is added to the
enemyHolder
container and pushed to the
enemies
array in the class. Figure
14-11
shows the enemy
grid in level 5.