How to make jumping only possible when touching ground

I was making a game where you’re a lantern in a cave and you need to escape before the time runs out. And I was wondering how can I make it so that whenever you press the space bar (jump) it only works if you’re touching ground?
Here’s the jump code:

function jump() {
if (gameOver) return;
var force = new THREE.Vector3(
0, 150, 0);
lantern.setLinearVelocity(force);
}

(“lantern” here is your avatar)
Thanks! :smiley::smiley:

Moldy-Mango

In your current function the if statement is what we call a “guard clause” – it guards the rest of the function from running when certain conditions are present. In this case, it guards against running the code in jump() if the game is over:

function jump() {
   if (gameOver) return;

   var force = new THREE.Vector3(0, 150, 0);
   lantern.setLinearVelocity(force);
}

What you need is another “guard clause” that prevents the code in jump() from running when the player is on the ground. Something like this might work:

function jump() {
  if (gameOver) return;
  if (lantern.position.y < 10) return;

  var force = new THREE.Vector3(0, 150, 0);
  lantern.setLinearVelocity(force);

}

The value in the guard clause probably needs to be changed from 10 depending on the starting value. But something like that should work.

-Chris

Would it be very simple if I was making a game in which you can also go on platforms high up? What then?
Moldy-Mango