Javascript游戏将对象移动到坐标

时间:2017-08-09 15:35:03

标签: javascript canvas

我正在使用JavaScript进行蛇形游戏,如果蛇在5秒内没有吃掉苹果,苹果会重新生成新生成的坐标。我的问题是我如何动画苹果以便移动'明显地看到新的坐标,我的意思是苹果应该在画布上移动到新的位置,我已经尝试过移动等等但我无法找到解决方案。提前致谢。

这是我的代码:

window.onload = function() {
canv = document.getElementById("gc");
ctx = canv.getContext("2d");
document.addEventListener("keydown", keyPush);
setInterval(game, 1000 / 15);
}
px = py = 10;
gs = tc = 20;
ax = ay = 15;
xv = yv = 0;
trail = [];
tail = 5;

var fps = 15;
var maxAppleAgeSeconds = 5;
var appleAge = 0;
var maxAppleAgeFrames = fps * maxAppleAgeSeconds;


function game() {
px += xv;
py += yv;
if (px < 0) {
px = tc - 1;
}
if (px > tc - 1) {
px = 0;
}
if (py < 0) {
py = tc - 1;
}
if (py > tc - 1) {
py = 0;
}
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canv.width, canv.height);

ctx.fillStyle = "lime";
for (var i = 0; i < trail.length; i++) {
ctx.fillRect(trail[i].x * gs, trail[i].y * gs, gs - 2, gs - 2);
if (trail[i].x == px && trail[i].y == py) {
  tail = 5;
}
}
trail.push({
x: px,
y: py
});
while (trail.length > tail) {
trail.shift();
}

appleAge++;

if (ax == px && ay == py) {
tail++;
ax = Math.floor(Math.random() * tc);
ay = Math.floor(Math.random() * tc);
appleAge = 0;
} else if (appleAge > maxAppleAgeFrames) {
ax = Math.floor(Math.random() * tc);
ay = Math.floor(Math.random() * tc);
appleAge = 0;
}


ctx.fillStyle = "red";
ctx.fillRect(ax * gs, ay * gs, gs - 2, gs - 2);
}

function keyPush(evt) {
switch (evt.keyCode) {
case 37:
  xv = -1;
  yv = 0;
  break;
case 38:
  xv = 0;
  yv = -1;
  break;
case 39:
  xv = 1;
  yv = 0;
  break;
case 40:
  xv = 0;
  yv = 1;
  break;
  }
 } 

1 个答案:

答案 0 :(得分:0)

使用requestAnimationFrame(https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)并计算苹果必须位于(ax0,ay0)和(ax1,ay1)之间的所有位置。您可以使用步长来计算每帧每个方向移动的距离。

} else if (appleAge > maxAppleAgeFrames) {
ax1 = Math.floor(Math.random() * tc);
ay1 = Math.floor(Math.random() * tc);
appleAge = 0;
animate();
}

function animate(){
 if(ax !== ax1 || ay !== ay1){
  ax += 1 // actually calculate this value, not necessarily 1
  ay += 1 // this too
  window.requestAnimationFrame(animate)
 }
}