Reputation: 27
I'm trying to make a game in HTML5 canvas. For this, I created this control module with this function that adds listeners for keyboard and mouse inputs. However, the mouseup event is not working/working as expected. When clicking with the mouse, the object starts moving, but when releasing the mouse, the object does not stop.
Sorry for not posting a fiddle. The complete project is here: Github and the working version is here: Github Pages.
export let
goLeft = false,
goRight = false,
doShoot = false;
export function addEventListeners() {
// Adds listeners for the keys.
// On press:
addEventListener('keydown', ({code}) => {
switch (code) {
case 'Numpad4': goLeft = true; break;
case 'Numpad6': goRight = true; break;
case 'Space': doShoot = true; break;
}
});
// On release:
addEventListener('keyup', ({code}) => {
switch (code) {
case 'Numpad4': goLeft = false; break;
case 'Numpad6': goRight = false; break;
case 'Space': doShoot = false; break;
}
});
// Adds listeners for the mouse:
// On press (right or left side of the canvas):
canvas.addEventListener('mousedown', ({offsetX}) => {
(offsetX < canvas.width / 2) ? goLeft = true : goRight = true;
});
// On release (any place the canvas):
canvas.addEventListener('mouseup', () => {
goLeft = goRight = false;
});
}
Upvotes: 0
Views: 43