خرید بک لینک

Vote count: 0

I'm trying to make a canvas jump. By jumping I mean moving up for a kinda sort time and then going down to the floor again. Something is obviously wrong because nothing happen when I press space. Can't think of what's wrong with my code, any ideas?

var spaceKey = false;
var player = {
  side: 20,
  x: 0,
  y: HEIGHT - 20,
  color: "red"

};

context.fillStyle = player.color;
context.fillRect(player.x, player.y, player.side, player.side);

setInterval(update, 1000/60);

function update(){
  clearCanvas();

  if (spaceKey){
    jump();
  } 

  draw();
}

function jump(){
  // Moving the player 5 px up 60 times every 10ms.
  for (var i = 0; i < 60; i++){
    function jumpUp(){
      player.y -= 5;
    }
    setTimeout(10, jumpUp);

  }
  // Moving the player 5 px down 60 times every 10ms.
  for (var i = 0; i < 60; i++){
    function jumpDown(){
      player.y += 5;
    }
    setTimeout(10, jumpDown);
  }

}


function onKeyDown(evt) {
        //Making spaceKey true onclick and calling the jump function.
        if (evt.keyCode == 32) spaceKey = true;

    }

function onKeyUp(evt) {

      if (evt.keyCode == 32) spaceKey = false;

}

window.addEventListener("keydown", onKeyDown, false);

window.addEventListener("keyup", onKeyUp, false);

(This is not all of my code, and if you want me to add any more code please let me know.)Thanks

asked 11 mins ago

1 Answer

Vote count: 0

Timeouts are not chained nor summed. The browser does not want for the previous Timeout to have run before executing the next. It tries to run a timeout timeoutArg ms after the moment it is registered. All your callbacks will be executed more or less at the same time here: 10 ms after being registered.

This should work:

function jump(){
  // Moving the player 5 px up 60 times every 10ms.
  for (var i = 0; i < 60; i++){
    function jumpUp(){
      player.y -= 5;
    }
    setTimeout(i * 10, jumpUp);
  }
  // Moving the player 5 px down 60 times every 10ms.
  for (var i = 0; i < 60; i++){
    function jumpDown(){
      player.y += 5;
    }
    setTimeout(i * 10 + 600, jumpDown);
  }
}

However, be aware that using timeouts for animation is bad practice. One should use requestAnimationFrame instead and base the animation progress on time, not on frames.

answered 6 mins ago

برچسب: نویسنده: استخدام کار تاريخ: چهارشنبه 5 خرداد 1395 ساعت: 22:38

صفحه بندی