O'Reilly logo

Building HTML5 Games with ImpactJS by Jesse Freeman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Firing the Weapon

Since inner classes are just like any other class we would create in Impact, we can simply use the ig.game built-in spawnEntity() method to create a new instance of the bullet when the player presses the fire key. Our player and monster are created during the level parsing process, so we have not had to manually instantiate an entity yet. The spawnEntity() function helps ensure that when we create a new entity, it gets added to Impact’s render list. Open up your player.js class and put the following code under the jump logic in the update method:

// shoot
if( ig.input.pressed('shoot') ) {
    ig.game.spawnEntity( EntityBullet, this.pos.x, this.pos.y, {flip:this.flip} );
}

As you can see, we are going to look for the shoot event, which we bound to the C key in our main class. This should be very straightforward—we tell ig.game that we are going to spawn a new entity. The spawnEntity() method needs a reference to the class we want to create and its starting x,y position, along with any additional settings we want to pass to the new entity. Notice here that we create a generic object with a property called flip with the player’s flip value. This is what tells the bullet which direction it should be fired.

At this point, we can test that our gun works by refreshing the game in the browser and hitting C. So, now you should be able to fire your weapon and kill the monsters.

You should see bullets being fired when you press the C key.

Figure 4-21. You should see bullets being fired when you press the C key.

At this point, the monsters will die after a few shots. If you change the monsters’ life property to something lower, it will take less shots to kill them. This is because on every collision the bullet detects with an enemy, it calls receivedDamage() and passes in 3 as the value. Likewise, you can make the bullets stronger by changing the amount of damage they apply.

Right now, our gun is kind of boring. Let’s add another weapon to the mix and see what happens.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required