Make a player jump (with gravity) in WoofJS

This tutorial shows you how to create a basic platformer game in WoofJS where you can make a player jump. It also shows how to add gravity to a game so the player falls back to the ground, as shown in the example below.

image24

Create a new project at woofjs.com and use the following code to implement this feature. Make sure you pay attention to the comments in the code that explain how it works.

setBackdropURL("http://www.codemahal.com/sprites/blue_background.png")
var jump = 8

var platform = new Image({
  url: "http://www.codemahal.com/sprites/platform_thick.gif",
  width: 100,
  height: 30,
  x: -50,
  y: 0
})

var player = new Image({
  url: "http://www.codemahal.com/sprites/player.gif",
  width: 20,
  height: 30,
  x: -80,
  y: 40
})

// Check if user presses UP and player is touching platform
onKeyDown(key => {
  if (key == 'UP' && player.touching(platform)) {
    jump = -5
    after(0.2, "seconds", () => {
      jump = 5
    })
  }
})

forever(() => {
  // Player movement
  if (keysDown.includes('RIGHT')) {
    player.move(2)
  }
  if (keysDown.includes('LEFT')) {
    player.move(-2)
  }
  
  // Bring player back to ground
  if ((jump < 0) || (!(player.touching(platform)))) {
    player.y -= jump;
  }
})