JavaScript - 06: Fancier bouncing

Experienced Pong players will know that the angle at which the ball bounces depends on what part of the paddle it hits. That doesn’t really make sense from a physics standpoint, but whatever. Anyway, let’s see if we can implement this for our game. Our first step will be removing the bounceOff line for the paddle—while bounceOff is convenient, it doesn’t give us much control over the angle. We want to start by checking if the ball is touching the paddle with if(ball.isTouching(paddle)), then we want to change the ball’s direction. Luckily, we’ve got a setSpeedAndDirection block. We’ve got two blanks—we could check the documentation just in case, but they’re most likely speed and direction (surprise!). We don’t need to change speed, so let’s just plug in the existing speed (getSpeed) for the existing speed in the first box. In the second box, we put the new direction (in the documentation, we can see that 0° points to the right). Let’s see if we can work out a formula for the angle we want the ball to travel in (there’s no right answer per se—we just want something that slants the ball upward if it hits the top part of the paddle and vice versa).

Hint: This’ll probably be based on the difference in y position between the ball and the paddle.


The formula I used was (paddle.y - ball.y)*(70/37.5)+180 (again, not the only right answer). Let’s plug that in, and we’ll see that the ball seems to move differently depending on how we hit it.