Premium Features

Download Video

Player movement

Let's add keyboard controls so our player can move left, right, and jump.

Event Listeners

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   } })

Key State Tracking

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.

Updating Velocity In The Animation Loop

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.

Implementing Jump

For jumping, apply a negative Y velocity when pressing W:

case 'w':   player.velocity.y = -20   break

Gravity automatically brings the player back down, creating a natural jump arc.

Comments

Want to participate?

Create a free Chris Courses account to begin

Login

No comments yet, be the first to add one

Providing the lift to launch your development career

© 2026 Chris Courses. All rights reserved.