0
\$\begingroup\$

I want to know how can I make the control of the Pong Ball in Plain Javascript. I would like to know how to make the ball faster when it hits the edges just like the original pong game, or how if the ball hit's the middle of the paddle it would go straight and slow. I just want to get a feel for how it works.

\$\endgroup\$
2
\$\begingroup\$

This is one way on how to do it and might not be the best, there should be some other way.

If you want to change the speed according to where the ball hit the paddle you could do it like this: enter image description here

You calculate the ball's x position and the middle position of the paddle (x coordinate too of course). For the formula, you could do it like this: speed = extraSpeed * distance / (0.5f * paddleWidth) + constant;

For distance, you can do it like this: abs(paddleMiddle.x - ball.x); We don't want it to be negative/minus.

Okay, with the formula above distance / (0.5f * paddleWidth) will return 0.0f when the ball hits the middle (distance = 0.0f), and will return 1.0f when the ball hits the edge of the paddle (it can return more than 1.0f though, you might want to do something about it like clamping the value or perhaps checking the distance from the side of the ball). This value will multiply extraSpeed, so the ball will not gain any extra speed when it hits the middle and gain full extra speed when it hits the edge of the paddle. And constant here will act as the base speed or you can say the slowest speed (when it hits the middle) you don't want the ball to stop when it hit the middle, do you?

\$\endgroup\$
  • \$\begingroup\$ I thought of this idea but when I implemented the code, it was just riddled with errors. I'll try this now. Thanks \$\endgroup\$ – user79408 Jun 11 '16 at 6:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.