我对自上而下游戏中的玩家移动有疑问。
玩家应该能够顺畅地向上,向下,向左,向右和对角移动。我写的代码首先起作用,但是当你长按两个键让玩家沿对角线方向移动时,它会在按住两个键大约一秒后立即从平滑过渡到抖动。
以下是代码:我非常感谢任何帮助。谢谢!
gameCanvas = document.getElementById("gameCanvas");
gameCanvasContext = gameCanvas.getContext("2d");
gameCanvas.width = window.innerWidth;
gameCanvas.height = window.innerHeight;
window.addEventListener("keydown", handleKeyAction);
window.addEventListener("keyup", handleKeyAction);
playerPosition = {xPosition: gameCanvas.width / 2, yPosition: gameCanvas.height / 2};
var keys = [];
function handleKeyAction(event) {
if(event.type === "keydown" && !keys.includes(event.keyCode)) {
keys.push(event.keyCode);
} else {
for(var index = 0; index < keys.length; index++) {
if(keys[index] === event.keyCode) {
keys.splice(index, 1);
break;
}
}
}
}
function movePlayer() {
if(keys.includes(87)) {
playerPosition.yPosition -= 5;
} if(keys.includes(65)) {
playerPosition.xPosition -= 5;
} if(keys.includes(83)) {
playerPosition.yPosition += 5;
} if(keys.includes(68)) {
playerPosition.xPosition += 5;
}
}
function drawPlayer() {
gameCanvasContext.beginPath();
gameCanvasContext.fillStyle = "#000000";
gameCanvasContext.arc(playerPosition.xPosition, playerPosition.yPosition, 15, 0, Math.PI * 2);
gameCanvasContext.fill();
gameCanvasContext.closePath();
}
function animate() {
gameCanvasContext.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
movePlayer();
drawPlayer();
requestAnimationFrame(animate);
}
animate();
答案 0 :(得分:0)
Because your else
in handleKeyAction
. It fired the else
even in situations that should not.
Try this (JSFiddle):
function handleKeyAction(event) {
if(event.type === "keydown" && !keys.includes(event.keyCode)) {
keys.push(event.keyCode);
}
if(event.type === "keyup") {
for(var index = 0; index < keys.length; index++) {
if(keys[index] === event.keyCode) {
keys.splice(index, 1);
break;
}
}
}
}