暂停后如何进行Javascript函数调用

时间:2018-06-29 03:13:11

标签: javascript html5-canvas

我正在使用HTML5 Canvas / Javascript构建一个简单的游戏。但是,游戏将通过Javascript函数(将js注入浏览器)。传递的代码将是移动字符,即。 “ moveRight(); moveRight(); moveUp();”。 当前,我正在移动角色,但是对于“ moveRight(); moveRight();”,角色会将自身传送到新位置。我希望角色先向右移动,然后暂停一下,然后再向右移动。

The game screen

function right(){
   window.setTimeout(function() {
      character.x += 30;
   }, 2000); 
}

我该如何完成类似的任务。我尝试使用超时,但并没有太大帮助。

谢谢

2 个答案:

答案 0 :(得分:2)

解决此问题的最佳方法是使用requestAnimationFrame,并在玩家能够移动时使用计数器。

setInterval在这种情况下不起作用,因为您需要确认玩家反方向移动或玩家取消移动的情况。

没有更多代码很难理解您当前的逻辑,但是下面您将找到一种基于网格的移动方法。

const c = document.getElementById('canvas');
c.width = window.innerWidth;
c.height = window.innerHeight;
const ctx = c.getContext('2d');

// player delay for movement
const playerMovementDelay = 2;
const tileSize = 32;
// player starting position
const myPlayer = {x: 1, y: 1, h: 1, w: 1};
let pkl = 0, pkr = 0, pku = 0, pkd = 0;
let pvelx = 0, pvely = 0;
let movementCountdown = 0;

function render() {

  // player logic
  movementCountdown -= 0.16;
  const deltax = pkr + pkl;
  const deltay = pkd + pku;
  if (movementCountdown <= 0 && (deltax != 0 || deltay != 0)) {
    movementCountdown = playerMovementDelay;
    pvelx = deltax;
    pvely = deltay;
  }
  const speed = 1;
  myPlayer.x += pvelx * speed;
  myPlayer.y -= pvely * speed;
  pvelx = pvely = 0;
  
  ctx.clearRect(0, 0, c.width, c.height);

  // player render
  ctx.fillStyle = '#FFD9B3';
  ctx.fillRect(myPlayer.x * tileSize, myPlayer.y * tileSize, myPlayer.w * tileSize, myPlayer.h * tileSize);

  window.requestAnimationFrame(render);
}

window.addEventListener('keydown', e => {
  if (e.key == 'ArrowRight') {
    pkr = 1;
    e.preventDefault();
  } else if (e.key == 'ArrowLeft') {
    pkl = -1;
    e.preventDefault();
  }
  
  if (e.key == 'ArrowUp') {
    pku = 1;
    e.preventDefault();
  } else if (e.key == 'ArrowDown') {
    pkd = -1;
    e.preventDefault();
  }

});

window.addEventListener('keyup', e => {
  if (e.key == 'ArrowRight') {
    pkr = 0;
  } else if (e.key == 'ArrowLeft') {
    pkl = 0;
  }
  
  if (e.key == 'ArrowUp') {
    pku = 0;
  } else if (e.key == 'ArrowDown') {
    pkd = 0;
  }
});

window.requestAnimationFrame(render);
body, html {
  margin: 0;
}
<canvas id="canvas"></canvas>

答案 1 :(得分:0)

您可以将setInterval用作同一对象。

var rightCount = 1;
var moveRight = function () {
    rightCount++;
    character.x += 30;
}

var move = function () {
    setInterval(function () {
        if (rightCount < 2) {
            moveRight();
        }
    }, 2000)
}

move();