[英]Html5 canvas game moving x, y
我的代碼可以工作了,您可以使用箭頭鍵控制元素。 但是,我只希望我的元素上下左右移動。 因此,當我按UP鍵時,我應該不能同時按RIGHT鍵。 但是我不確定如何防止這種情況發生? 有人可以將我帶往正確的方向嗎?
我如何檢查運動
// 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);
這里有兩個假設:
編輯:
為了說明更簡化的版本,下面是代碼。
// 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);
在對第二把鑰匙進行任何操作之前,請檢查是否可以移動
嘗試這個:
// Tracking keys
var keysDown = {};
var canMove = true; // If it can move.
// 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) {
if (canMove) {
keysDown[e.keyCode] = true;
canMove = false;
}
}, false);
addEventListener('keyup', function(e) {
if (keysDown[e.keyCode]) {
delete keysDown[e.keyCode];
canMove = true;
}
}, false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.