Game Development Reference
In-Depth Information
enemy = this.enemies[this.currentEnemyAttackIndex];
enemy.on(events.ENEMY_ATTACK_ANIMATION_COMPLETE,
this.onEnemyAttackAnimationComplete, this, true);
enemy.playAttackAnimation();
}
p.onEnemyAttackAnimationComplete = function (e) {
var enemy = e.target;
this.hero.takeDamage(enemy.data.power);
this.battlePanel.updateStats();
this.heroAttackedEffects();
}
The
beginEnemyAttack
method will be called to kick off an enemy streak and again for each time the streak
advances in attacks. The first thing it does is disable the battle panel so the player cannot attack during this streak. The
currentEnemyAttackIndex
, which is increased at the end of each attack, is evaluated to make sure it has not exceeded
the amount of available enemies. This is needed because the amount of enemies is constantly changing, and this
index could be off if the enemy in that slot was killed since the last enemy streak. The next enemy in line is found by
using this index value on the
enemies
array.
An enemy has a bounce effect for when it attacks and will dispatch the event
ENEMY_ATTACK_ANIMATION_COMPLETE
when it is finished. Notice that the
once
parameter is set to true in the
on
method. This is a handy way of removing the
listener as soon as it handled. Finally, the enemy plays its attacking animation by calling its
playAttackAnimation
method.
After this enemy animation, the actual attack should take place. Like the
Enemy
class, the
Hero
class also has a
takeDamage
method, which will take the
power
value of the enemy attacking. If you recall, this method will update the
hit points on the
hero
instance. Next, the
updateStats
method is called on the
battlePanel
object. Since the panel
does not update during an enemy attack, this should be called manually after the hero has been attacked so that the
HP message can be updated. Lastly, a flashy effect happens on the screen to resemble an attack from the enemy.
Listing 14-38 shows how this effect is executed.
Listing 14-38.
Game.js - Creating the Effect for Hero Damage
p.heroAttackedEffects = function () {
var flash = new createjs.Shape();
flash.graphics.beginFill('#900').drawRect(0, 0, screen_width,
screen_height);
flash.alpha = 0;
this.addChild(flash);
createjs.Tween.get(flash)
.to({alpha:.6}, 500, createjs.Ease.bounceInOut)
.to({alpha:0}, 500, createjs.Ease.bounceInOut)
.call(function (flash) {
this.removeChild(flash);
this.evaluateEnemyStreak();
}, [flash], this);
}
A red shape is created and added to the game. A few chained tween commands are applied to give it a flashing
effect (see Figure
14-16
).