Skip to content Skip to sidebar Skip to footer

How To Make My Character Not Fly When Holding Jump

I'm making a game with javascript. Right now, when holding jump, my character keeps jumping. I would like him to not keep jumping and flying around. How do I make him stop jumping

Solution 1:

Set a timeout when the user starts jumping, and automatically call comeDown if the user haven't released the key yet:

//On key down
case 38 && 87: // up arrow
  // console.log("w")

  if (this.player.jumping === false) {
    this.player.jump();
    this._timeout = setTimeout(()=>{
      if(this.player.jumping === true)
        this.player.comeDown()
    },2000)
  }
  break;
//On key up
case 38 && 87: // up arrow
  // console.log("w")
  if (this.player.jumping){
    clearTimeout(this._timeout)
    this.player.comeDown()
  }
  break;

Also, (unrelated to this problem), case 38 && 87: won't work as you expect:

As the expression 38 && 87 equals to 87 (due to &&), it won't work for 38.

To write 38 OR 87, you have to write two folded cases:

case 38:
case 87:
  //code here

Post a Comment for "How To Make My Character Not Fly When Holding Jump"