HTML and CSS Reference
In-Depth Information
Connecting Missiles to the Player
To actually get a missile onto the screen, the PlayerShip needs to be updated to respond to the fire key and
add a pair of missiles onto the screen for each of its two turrets. You also need to add in a reloading period to
limit the speed at which missiles are fired.
To put in this limit, you must add a new property called reload , which represents the remaining time before
the next pair of missiles can be fired. You also must add another property called reloadTime , which repres-
ents the full reloading time. Add the following two initialization lines to the top of the PlayerShip construct-
or method:
var PlayerShip = function() {
this.w = SpriteSheet.map['ship'].w;
this.h = SpriteSheet.map['ship'].h;
this.x = Game.width / 2 - this.w / 2;
this.y = Game.height - 10 - this.h;
this.vx = 0;
this.reloadTime = 0.25; // Quarter second reload
this.reload = this.reloadTime;
reload is set to reloadTime to prevent the player from immediately firing a missile when they press fire
to start the game.
Next, modify the step method to read as follows:
this.step = function(dt) {
if(Game.keys['left']) { this.vx = -this.maxVel; }
else if(Game.keys['right']) { this.vx = this.maxVel; }
else { this.vx = 0; }
this.x += this.vx * dt;
if(this.x < 0) { this.x = 0; }
else if(this.x > Game.width - this.w) {
this.x = Game.width - this.w
}
this.reload-=dt;
if(Game.keys['fire'] && this.reload < 0) {
Game.keys['fire'] = false;
this.reload = this.reloadTime;
this.board.add(new PlayerMissile(this.x,this.y+this.h/2));
this.board.add(new PlayerMissile(this.x+this.w,this.y+this.h/2));
}
}
This code adds two new player missiles on the left and right sides of the ship if the player presses the fire
key and is not in the process of reloading. Firing a missile simply consists of adding it to the board at the right
location. The reload property is also reset to reloadTime to add in a delay between missiles being fired.
To ensure the player needs to press and release the spacebar to fire and can't just hold it down, the key is set to
false . (This doesn't quite have the intended effect because keydown events are fired on repeat.)
 
Search WWH ::




Custom Search