I followed this question/answer to create a multiple key press detector. It works as intended: you press D and the square moves right, then you press S while pressing the D and the square moves in angle. So far so good. However, if you are pressing D and S at the same time and you unpress the S, the square will stop moving. The expected behaviour is that it keeps moving to the right, since you are still pressing D.
Here's a jsfiddle and the demo I'm making (my web).
So, why is .keyup()
making other .keydown()
event invalid? This is the offending jQuery code:
// Check if it's a function
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
// Store the keys pressed and callback for each key
var keys = {};
var keycalls = {};
// Loop and call all the needed callbacks
function run_keys() {
$.each(keys, function (index, value) {
if (value == true) {
console.log(keys);
var fun = keycalls[index];
if (isFunction(fun))
fun();
}
});
}
// Store a key
$(document).keydown(function (e) {
keys[e.which] = true;
run_keys();
});
// Delete a key
$(document).keyup(function (e) {
delete keys[e.which];
run_keys();
});
// Assign a callback to a key
keyboard = function (key, callback) {
console.log(callback);
keycalls[key.toUpperCase().charCodeAt()] = callback;
}
// Assign keys
// Assign w to up action
keyboard("w", function () {
$(".keyboard").animate({
'top': "-=5px"
}, 0);
});
keyboard("a", function () {
$(".keyboard").animate({
'left': "-=5px"
}, 0);
});
keyboard("s", function () {
$(".keyboard").animate({
'top': "+=5px"
}, 0);
});
keyboard("d", function () {
$(".keyboard").animate({
'left': "+=5px"
}, 0);
});
Disclaimer: this is just for fun and learning, not about having a game engine. I know there are many good ones already available.
UPDATE
One of the solutions I've thought is making an independent loop for calling run_keys(), but I'd like to avoid that if possible. It works, however I'm still interested in the problem.