我的代码可以正常工作,您可以使用箭头键控制元素。但是,我只希望我的元素上下左右移动。因此,当我按向上键时,我不应该同时按向右键(扫射)。但我不知道如何防止这种情况发生?谁能帮我指明正确的方向?
我如何检查我的运动,
// Tracking keys
var keysDown = {};
// Moving the player around on the map
if(39 in keysDown) { player.x+=gameSettings.speed; } // Move Right
if(37 in keysDown) { player.x-=gameSettings.speed; } // Move Left
if(38 in keysDown) { player.y-=gameSettings.speed; } // Move Up
if(40 in keysDown) { player.y+=gameSettings.speed; } // Move Down
addEventListener('keydown', function(e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener('keyup', function(e) {
delete keysDown[e.keyCode];
}, false);
我确信有一个简单的解决方案,但我已经研究这个问题太久了,所以任何正确方向的精确定位都会很棒!
最佳答案
我喜欢 miqdadamirali 的答案,但让我们看看是否可以稍微简化一下。
试试这个:
// Tracking keys
var keysDown = {};
// Moving the player around on the map
if(39 in keysDown) { player.x+=gameSettings.speed; } // Move Right
if(37 in keysDown) { player.x-=gameSettings.speed; } // Move Left
if(38 in keysDown) { player.y-=gameSettings.speed; } // Move Up
if(40 in keysDown) { player.y+=gameSettings.speed; } // Move Down
addEventListener('keydown', function(e) {
// we only want to set the key if it's empty
if (Object.keys(keysDown).length === 0) {
keysDown[e.keyCode] = true;
// call the function to make the actual movement
}
}, false);
addEventListener('keyup', function(e) {
delete keysDown[e.keyCode];
}, false);
这里有两个假设:
- 每次触发 keydown 事件时都会调用执行移动的代码块。我假设您在这里展示是为了说明目的。
- 根据您的描述,一次只能有一个移动,因此我们在任何时候 keyDown 对象中都应该只有一个属性。您可以使用一个变量并将其设置为零或 39 - 40。
编辑:
为了说明更简化的版本,下面是代码。
// Tracking keys
var keyPressed = 0;
// Moving the player around on the map
if(keyPressed === 39) { player.x+=gameSettings.speed; } // Move Right
if(keyPressed === 37) { player.x-=gameSettings.speed; } // Move Left
if(keyPressed === 38) { player.y-=gameSettings.speed; } // Move Up
if(keyPressed === 40) { player.y+=gameSettings.speed; } // Move Down
addEventListener('keydown', function(e) {
// we only want to set the key if keyPressed is zero
if (keyPressed === 0) {
keyPressed = e.keyCode;
// call the function to make the actual movement
}
}, false);
addEventListener('keyup', function(e) {
keyPressed = 0;
}, false);
关于javascript - Html5 Canvas 游戏移动x、y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37486776/