Pong-2 adds interactivity to the paddles by letting us move them up and down using the w and s keys for the left paddle, and the up and down keys for the right paddle.
Important Functions
canvas.addEventListener(eventName, function)- This registers an event listener that triggers a callback function that executes whenever we press a key. We will use this to set different keys in our
keysobject totrueandfalsewhich will allow us to receive input from the keyboard for our game.
- This registers an event listener that triggers a callback function that executes whenever we press a key. We will use this to set different keys in our
Important Code
You’ll notice we’ve added a new constant near the top:
const PADDLE_SPEED = 1000;This is an arbitrary value that we’ve chosen for our paddle speed. It will be scaled by DeltaTime, so it’ll be multiplied by how much time has passed (in terms of seconds) since the last frame, so that our paddle movement will remain consistent regardless of how quickly or slowly our computer is running.
You’ll also find some new variables:
let player1Score = 0;let player2Score = 0;let player1Y = 30;let player2Y = CANVAS_HEIGHT - 230;In particular, we’ve created two variables for the purpose of scorekeeping and two variables to keep track of each paddle’s vertical position. Since the paddles will be able to move up and down, we only need to keep track of the Y position and not the X.
Next, you’ll see that we’ve finally defined behavior for update().
Player 1 already demonstrates the movement pattern in the starter code. Your job is to apply the same idea to player 2:
- when the up key is held, the paddle’s Y position should decrease,
- when the down key is held, the paddle’s Y position should increase,
- both movements should be scaled by
PADDLE_SPEED * dt.
Recall that our 2D coordinate system starts at the top-left of the screen. Moving upward means subtracting from Y, which can feel counterintuitive at first.
🧩 Challenge: Wire up player 2 movement
Finish the ArrowUp/ArrowDown branch so the right paddle moves with DeltaTime just like player 1.
- Installing dependencies
- Starting Vite dev server