HTML and CSS Reference
In-Depth Information
2.
The next stage is to determine whether or not the user has pressed either the Space
bar key, the W key, or the up arrow key. This is done in the same way as we detected
the user input in previous recipes. We also need to check whether or not the player is
on the ground and if they are only then can we allow them to jump.
if((key.keyCode == 32 || key.keyCode == 38 || key.keyCode == 87)
&& this.isOnGround) {
this.isOnGround = false
this.position = 0;
}
3.
Next, we need to implement a check to see if the player is jumping and if so their
position and speed needs to be updated until they have collided with the ground.
if(!this.isOnGround) {
var prevPosition = this.position;
this.position += this.jumpVelocity * deltaTime;
if(this.position >= Math.PI) {
this.y += this.maxJump / this.jumpTime * this.terminalVelocity *
deltaTime;
}
else {
this.y -= (Math.sin(this.position) - Math.sin(prevPosition)) *
this.maxJump;
}
}
4.
We then need to check if and when the player has collided with the levels terrain, if
so then we change the player's ground state to true . If the player has not collided
with the terrain we update the player's jump height and speed.
var checkCollisionLeft = this.level.CurrentTile(this.x);
var checkCollisionRight = this.level.CurrentTile(this.x + this.
frameWidth);
var heightLeft = this.level.TerrainHeight(checkCollisionLeft);
var heightRight = this.level.TerrainHeight(checkCollisionRight);
var maxHeight;
if(heightLeft > heightRight)
maxHeight = heightLeft
else
maxHeight = heightRight;
var playerHeight = context.canvas.height - (this.y + this.texture.
height);
if(maxHeight >= playerHeight) {
 
Search WWH ::




Custom Search