I have developed a JavaScript platform game where the player can navigate by moving left, right, or jumping using the arrow keys on the keyboard. I am interested in implementing this functionality using JavaScript buttons that I have created.
Below are the JavaScript buttons:
<button id="left" type="button">Left</button>
<button id="up" type="button">Jump</button>
<button id="right" type="button">Right</button>
Here is my original JavaScript code that enables the character to jump, move left, or move right using the keyboard arrow keys.
var playerXSpeed = 7;
var gravity = 30;
var jumpSpeed = 17;
Player.prototype.update = function(time, state, keys) {
let xSpeed = 0;
if (keys.ArrowLeft) xSpeed -= playerXSpeed;
if (keys.ArrowRight) xSpeed += playerXSpeed;
let pos = this.pos;
let movedX = pos.plus(new Vec(xSpeed * time, 0));
if (!state.level.touches(movedX, this.size, "wall")) {
pos = movedX;
}
let ySpeed = this.speed.y + time * gravity;
let movedY = pos.plus(new Vec(0, ySpeed * time));
if (!state.level.touches(movedY, this.size, "wall")) {
pos = movedY;
} else if (keys.ArrowUp && ySpeed > 0) {
ySpeed = -jumpSpeed;
} else {
ySpeed = 0;
}
return new Player(pos, new Vec(xSpeed, ySpeed));
};
This section of the code determines whether the arrow keys are pressed or released. If the arrow keys are held down, the character continues to move until they are released. I understand that additional modifications are needed for it to work with my JavaScript buttons, but I'm unsure of how to proceed.
function trackKeys(keys) {
let down = Object.create(null);
function track(event) {
if (keys.includes(event.key)) {
down[event.key] = event.type == "keydown";
event.preventDefault();
}
}
window.addEventListener("keydown", track);
window.addEventListener("keyup", track);
return down;
}
var arrowKeys =
trackKeys(["ArrowLeft", "ArrowRight", "ArrowUp"]);