Discuss Scratch

denhaerynckjonathan
Scratcher
18 posts

How do you fix in ping pong games when the ball hits the paddle and bounces back to the other player?

How do you fix in ping pong games when the ball hits the paddle and bounces back to the other player?
I'm trying to solve it, but I can't find the error. Here's the link you do with the arrows:

https://scratch.mit.edu/projects/696265527/
If you found the error, leave a comment on the project page!

Thank You Very Much!
deck26
Scratcher
1000+ posts

How do you fix in ping pong games when the ball hits the paddle and bounces back to the other player?

So you need to bounce when the ball touches a paddle, not just when it hits the edge.

Your paddles are vertical so the bounce angle is just -1 * the approach angle - eg you hit at 60 degrees and you bounce at -60.

So in your loop where you move the ball check for touching either paddle and change direction if you are.
RT_Borg
Scratcher
1000+ posts

How do you fix in ping pong games when the ball hits the paddle and bounces back to the other player?

Hi denhaerynckjonathan,

I like the random angles your ball bounces with (but if you want traditional angles, follow the advice from deck26).

But what I think you're asking about is the way the ball is getting stuck jiggling on the paddle for a little while. This is because the ball is actually touching the paddle for more than just a single instant. So in this code you end up broadcasting singal1 a bunch of times:

when green flag clicked
forever
if <touching (PingPong Ball)> then
set [sting v] to [0]
broadcast [singal1 v]
end
end

each time it does, the code in PingPong Ball sets the ball at a different angle.

You can fix this (in both paddles) by waiting until the paddle is no longer touching the PingPong Ball, like this

when green flag clicked
forever
if <touching (PingPong Ball)> then
set [sting v] to [0]
broadcast [singal1 v]
wait until <not <touching (PingPong Ball)>> // this will let the ball move away before continuing to check for touches
end
end

I hope this helps. I'm happy to answer questions.

– RT_Borg
deck26
Scratcher
1000+ posts

How do you fix in ping pong games when the ball hits the paddle and bounces back to the other player?

Another useful trick is to use the ball's position. If it is moving right (positive direction) it can only bounce if x>0 and if moving left it can only bounce if x < 0. That fixes the problem when the ball gets stuck as once it has turned it is no longer able to bounce until it gets back across the screen.

However if you're turning a random amount when you bounce @RT_Borg's solution is better. Depends if you want the bounce to be at all realistic though - just turnhing a random amount will never look realistic.

My preference is to turn as I indicated before but apply a small nudge clockwise or anti-clockwise (depending on circumstances) if the ball is near the end of the paddle.

Powered by DjangoBB