Understanding elements in an function update(); to move player paddle in pong game


Hi fellow coders

Can you help me explain whats going on inside this update function? My understanding so far is such: Getting y.pos of right paddle; If playerPaddleY is less than or equal 0 AND if I’m pressing up-key, THEN …
The rest of the code, I’m having difficulties understanding - primarily the code being executed if the conditions are true in the if-statements…

Thanks in advance.

function update(dt){

var playerPaddleY = paddleRight.y();

if (playerPaddleY <= 0 && paddleDirection == -1) {
paddleRight.cy(paddleHeight / 2);
} else if (playerPaddleY >= height-paddleHeight && paddleDirection == 1) {
paddleRight.y(height - paddleHeight);
} else {
paddleRight.dy(paddleDirection * paddleSpeed);

Outside update();

[CODE]// Define paddle direction and speed

var paddleDirection = 0; // -1 is up, 1 is down, 0 is still
var paddleSpeed = 5; // pixels per frame

// detect if up and down arrows are pressed to change direction
// 38 is up-arrow, 40 is down-arrow.
// myVar = condition ? value-if-true : value-if-false

SVG.on(document, ‘keydown’, function(e) {
paddleDirection = e.keyCode == 40 ? 1 : e.keyCode == 38 ? -1 : 0

// Direction is reset once the key is not pressed (‘keyup’)
SVG.on(document, ‘keyup’, function(e) {
paddleDirection = 0

Link to pen with full code: https://codepen.io/sellew/pen/Qgzmbb?editors=0010


Update: My understanding is now that statement #1 and #2 stops the paddle and #3 basically moves it. But I still don’t quite understand the execution codes.


It’s important to remember that y == 0 is the top of the screen.

if (playerPaddleY <= 0 && paddleDirection == -1)

If the player tries to move the paddle past the top, then…

paddleRight.cy(paddleHeight / 2);

…set the center position of the paddle to be 1/2 of the paddle’s height from the top. If the paddle is 20 pixels long, then this will set the paddle’s center to 10px from the top. This makes sure that the paddle never travels past the top edge.

else if (playerPaddleY >= height-paddleHeight && paddleDirection == 1)

Since y == 0 is the top, then y == height is the bottom. So, height - paddleHeight is the lowest the paddle can go before it crosses the boundary. At this point, the bottom of the paddle is touching the bottom edge of the play area. If the player tries to move lower than this…

paddleRight.y(height - paddleHeight);

… set the paddle’s Y position to that lowest point. If neither of these conditions are true, then

paddleRight.dy(paddleDirection * paddleSpeed);

This changes the paddle’s position relative to where it currently is by calculating its instantaneous velocity. paddleSpeed is 5, so if the player wants to go up, the paddle gets shifted by -5 pixels, bringing it towards the top.


Thanks for the explanation. That was very helpful.