Premium Features
Let's add keyboard controls so our player can move left, right, and jump.
Use window.addEventListener to listen for key presses:
window.addEventListener('keydown', (event) => { switch (event.key) { case 'd': // Move right break case 'a': // Move left break case 'w': // Jump break } })Setting velocity directly in the event listener causes the player to keep moving after you release the key. Instead, track which keys are pressed:
const keys = { d: { pressed: false }, a: { pressed: false } }Set these to true on keydown and false on keyup.
Check key states inside animate() and update velocity accordingly:
player.velocity.x = 0 if (keys.d.pressed) { player.velocity.x = 5 } else if (keys.a.pressed) { player.velocity.x = -5 }Resetting velocity to zero each frame ensures the player stops immediately when you release the key.
For jumping, apply a negative Y velocity when pressing W:
case 'w': player.velocity.y = -20 breakGravity automatically brings the player back down, creating a natural jump arc.
Comments
Want to participate?
Create a free Chris Courses account to begin
No comments yet, be the first to add one