我正在使用一个对象来记录实例上正在按下的箭头键。在按住的同时,left
如果我也开始按住right
,然后停止按下,则left
keydown函数仍将运行,但是如果我执行相同的设置但又停止按下right
,则该函数停止。
功能如下:
var keys = {};
$(document).keydown(function(e){
keys[e.which] = true;
console.log('h');
moveBall();
});
$(document).keyup(function(e){
console.log(e.which);
delete keys[e.which];
});
function moveBall(){
var vals = [];
var ball = $("#ball1");
var up = false;
var down = false;
var left = false;
var right = false;
for( var key in keys ) {
if ( keys.hasOwnProperty(key) ) {
vals.push(key);
}
}
if ($.inArray("39", vals)> -1) right = true; // Right
if ($.inArray("37", vals)> -1) left = true;
if ($.inArray("38", vals)> -1) up = true;
if ($.inArray("40", vals)> -1) down = true;
}
有人可以解释一下为什么我停止按键时命令的顺序是否keydown
仍在运行吗?
因此,您尝试循环“ moveBall”,并根据所按下的键进行操作。
我将稍微改变您的逻辑。
//Global object for what keys are active right now.
var keysBeingPressed = {
right: false,
left: false,
up: false,
down: false
};
$(document).keydown(function(e){
// Set the right direction = true
if (e.which == "39") keysBeingPressed.right = true;
if (e.which == "37") keysBeingPressed.left = true;
if (e.which == "38") keysBeingPressed.up = true;
if (e.which == "40") keysBeingPressed.down = true;
});
$(document).keyup(function(e){
// Set the right direction = false
if (e.which == "39") keysBeingPressed.right = false;
if (e.which == "37") keysBeingPressed.left = false;
if (e.which == "38") keysBeingPressed.up = false;
if (e.which == "40") keysBeingPressed.down = false;
});
function moveBall(){
var ball = $("#ball1");
// Going left is decreasing X, right is increasing X.
// Going up is decreasing Y, down increases Y.
// So, up+left, is diagonal, you move x and y both..
var movement = {
x: 0,
y: 0
}
if(keysBeingPressed.right) movement.x++;
if(keysBeingPressed.left) movement.x--; //If left+right; x = 1 - 1 = 0 so no movement.
if(keysBeingPressed.up) movement.y--;
if(keysBeingPressed.down) movement.y++;
// add your movement in x/y to top/left
ball.css({
top: "+="+movement.y, //+= adds the value
left: "+="+movement.x
});
}
// Loop this function, you want it to run every "animation frame"
setInterval(function(){
moveBall();
}, 10);
我确实添加了代码来移动球。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句