Reputation: 8584
I'm using an object to record what arrow keys are being pressed at an instance. While holding down left
if I then also start holding down right
, then stop holding down left
my keydown function still runs, but if I do the same setup but stop holding down right
instead, the function stops.
Here's the functions:
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;
}
Can someone please explain why the ordering of when I stop pressing keys changes whether the keydown
function still runs?
Upvotes: 2
Views: 94
Reputation: 1709
So, you are trying to loop "moveBall" and so actions depending om which key is pressed.
I'm going to change your logic a little bit.
//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);
I did add code to move the ball.
Upvotes: 3