To get a simple, responsive, 4-directional movement in a 2D game, I've implemented the following. When a key is pressed, the add
method adds the direction to the keys
array. When the key is released, the remove
method removes the direction from the keys
array. In my Update
method, I call getLast
to get the last direction and move the player in that direction.
I want to restrict movement to one direction, but when I press multiple keys, I want the last key's direction to be used. Basically, if I'm going left and press up, but then release up while still holding down left, I want the character to go left, up, and continue going left.
I'm rather inexperienced when it comes to this kind of Javascript, so I'm hoping anyone has some tips / best practices recommendations for this small code snippet. I know naming is a bit iffy - I wanted to name it 'stack', but it's hardly a stack implementation.
function Keys() {
this.keys = [];
}
// Only add the direction if it doesn't exist yet
Keys.prototype.add = function (dir) {
for (var i = 0; i < this.keys.length; i++) {
if (this.keys[i] == dir) {
return;
}
}
this.keys[this.keys.length] = dir;
};
// Find the index of the first occurrence and splice the array there without it
Keys.prototype.remove = function (dir) {
for (var i = 0; i < this.keys.length; i++) {
if (this.keys[i] == dir) {
this.keys.splice(i, 1);
}
}
};
Keys.prototype.getLast = function () {
if (this.keys.length > 0) {
return this.keys[this.keys.length - 1];
}
};
In my main file, I use it as: var keys = new Keys();