Premium Features
Player Movement
With gravity pulling our player down, it's time to give them control. In this lesson, we'll implement keyboard-based movement—jumping, moving left and right, and handling input in a way that feels responsive.
Listening for Key Presses
JavaScript's event listener system lets us respond to keyboard input:
window.addEventListener('keydown', (event) => { console.log(event.key) })The
event.keyproperty tells us exactly which key was pressed—'w', 'a', 'd', etc.
Implementing Jump
When the player presses W, we set a negative Y velocity to move upward:
switch (event.key) { case 'w': player.velocity.y = -20 break }Thanks to our gravity system, the player naturally falls back down after jumping.
Preventing Double Jumps
Without a check, players could spam jump infinitely. Only allow jumping when grounded:
case 'w': if (player.velocity.y === 0) { player.velocity.y = -20 } breakHorizontal Movement
For left and right movement, we modify the X velocity:
case 'a': player.velocity.x = -5 break case 'd': player.velocity.x = 5 breakDon't forget to apply X velocity in the Player's update method:
this.position.x += this.velocity.xSmooth Input with a Keys Object
Using keydown alone causes jitter when switching directions. Instead, track which keys are currently pressed:
const keys = { w: { pressed: false }, a: { pressed: false }, d: { pressed: false } }Update these values on keydown/keyup, then check them in your animation loop:
// In animate() player.velocity.x = 0 if (keys.d.pressed) player.velocity.x = 5 else if (keys.a.pressed) player.velocity.x = -5Organizing Event Listeners
Move your event listeners to a separate js/eventListeners.js file to keep index.js focused on game logic.
Why This Matters
This input handling pattern—tracking pressed keys and checking them each frame—is the foundation for responsive game controls. It prevents input bugs and makes movement feel tight.
Comments
Want to participate?
Create a free Chris Courses account to begin
No comments yet, be the first to add one