I have these two pieces of code that work however when pressing down a key it does multiple instances instead of once. How can I fix this issue?
i've tried multiple places with setTimeout() eventually came to the conclusion that keyup event can be replaced by just inserting keys.a.pressed = false after charX--
Is there a better solution?
function animate(){
requestAnimationFrame(animate)
b.clearRect(-gameWidth / 2, 0, gameWidth, gameHeight)
boundaries.forEach(boundary => {
boundary.draw()
// console.log(boundary.position.x, boundary.position.y)
// console.log('boundary', boundary.position.x, boundary.position.y)
})
floors.forEach(floor => {
floor.draw()
})
if (keys.w.pressed && lastKey === 'w' && canMove(charX, charY - 1)) {
console.log('w', charY)
charY--;
// drawCharacter(charX, charY);
}
else if (keys.a.pressed && lastKey === 'a' && canMove(charX - 1, charY)) {
charX--;
// drawCharacter(charX, charY);
}
else if (keys.d.pressed && lastKey === 'd' && canMove(charX + 1, charY)) {
charX++;
// drawCharacter(charX, charY);
}
else if (keys.s.pressed && lastKey === 's' && canMove(charX, charY + 1)) {
charY++;
// drawCharacter(charX, charY);
}
player.update(charX, charY)
// console.log('player',player.position.x, player.position.y)
}
animate()
addEventListener ('keydown', ({key}) =>{
switch (key) {
case 'a': // left
keys.a.pressed = true
lastKey = 'a'
break;
case 'w': // up
keys.w.pressed = true
lastKey = 'w'
break