2017-08-09 93 views
0

我在JavaScript中製作蛇遊戲,如果蛇在5秒內沒有吃掉蘋果,蘋果就會重新生成新生成的座標。我的問題是我如何動畫蘋果'移動'明顯的新座標,我的意思是蘋果應該在畫布上移動到新的位置,我試過moveTo等,但我找不到解決方案。提前致謝。Javascript遊戲將對象移動到座標

這裏是我的代碼:

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; 
    } 
} 

回答

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) 
} 
}