Im creating a small game in javascript that requires multiple keys to be pressed at once for an avatars movement.
To recognize multiple key presses I'm using "Braden Best"s answer to the question JavaScript multiple keys pressed at once which works well except for the fact that the document doesn't seem to multitask keyup events. For example if I want to press the up arrow key followed by the left arrow key then release the left arrow key the avatar would stop completely.
Here is an example code: https://Jsfiddle.net/552gc9dh/1/
var c = document.getElementById("canv");
var canv = c.getContext("2d");
console.log("test");
var map = {};
var playerlist = [];
function player(width, height, x, y, color, speedx, speedy) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.color = color;
this.speedx = speedx;
this.speedy = speedy;
playerlist.push(this);
}
var player1 = new player(50, 50, 0, 0, "red", 2, 2);
console.log(playerlist[0]);
function gravity(playerY) {
}
function createplayerlistener(name, key1, key2, key3, key4) {
onkeydown = onkeyup = function(e) {
e = e || event;
map[e.keyCode] = e.type == 'keydown';
if (name.x + name.speedx < c.width - name.width) {
if (map[key1]) {
name.x += name.speedx;
}
}
if (name.x + name.speedx > 0) {
if (map[key2]) {
name.x -= name.speedx;
}
}
if (name.y + name.speedy < c.height - name.height) {
if (map[key3]) {
name.y += name.speedy;
}
}
if (name.y + name.speedy > 0) {
if (map[key4]) {
name.y -= name.speedy;
}
}
}
}
createplayerlistener(player1, 39, 37, 40, 38);
setInterval(function() {
canv.clearRect(0, 0, c.width, c.height);
for (var i = 0; i <= playerlist.length - 1; i++) {
canv.fillStyle = playerlist[i].color; // iterates through players and draws them
canv.fillRect(playerlist[i].x, playerlist[i].y, playerlist[i].width, playerlist[i].height);
}
}, 10);