Player.js
First up we add the ability to jump. The players jump will follow an arc in the air, jumping up quickly to begin with, slowing until the apex of the jump, and then falling back down again. This arc is nicely defined by a sine wave with the formula y = jumpHeight * sin(jumpSinWavePos). In this case y is the height of the player as he jumps, jumpHeight is a constant that defines the maximum height of the jump, and jumpSineWavePos is a variable that will be incremented over time as the player moves through the jump.
The benefit of using a sine wave to define the height of the jump is that the player will follow a smooth arc regardless of the frame rate.
First we need to define the variables that were mentioned in the formula above. You notice that we also define the grounded Boolean property, which is true when the player is on the ground, and false when he is in the air (either jumping or falling). [code]
Next we need to watch for the space bar being pressed, at which point we start the players jump. Notice that we first check to see if the player is on the ground, because the player can only jump if he is currently grounded. We set grounded to false (to indicate that the player is no longer on the ground), and set the jumpSinWavePos variable to 0. [code]
The jumpSinWavePos is the value that will increase over time to push the player along the sine wave. Because the Math.sin function works on radians we want jumpSinWavePos to start at 0 (sin(0) = 0), move to PI / 2 at the top of the jump (sin(PI / 2) = 1), and then through to PI at the bottom of the jump (sin(PI) = 0). This range takes us through the top half of the sine wave, and therefor the arc that we want to follow for the jump. The jumpHangTime variable defines how quickly jumpSinWavePos moves through the range of 0 to PI, which has the effect of defining how long the player spends in the air.