I have problem but I don't know how to describe it so I have drawn it.
As you can see ball bounces when collision is detected. Nevermind the angle - I have just drawn it that way. But sometimes ball goes through the paddle leaving it other way.
Why that happens ? Becase when I detect the collision I change vx to -vx. What should I do in that case ? Change also y ? But how to check which side of the paddle ball hit?
Maybe other ideas?
In the classic game of Pong, there is a little ball that bounces around off various walls and objects. Importantly, the ball changes direction when it bounces but it never really slows down in speed. This is a big hint that the collisions that the ball is experiencing are elastic collisions.
The reason is that the 'soft' surface gives a little and absorbs some of the energy of the ball. (In technical terms it is called an 'inelastic collision'.) Having less energy, the ball doesn't bounce as high. That answer works well for a nice bouncy tennis ball.
The ball bounces off it that bit harder, gaining twice that extra velocity relative to the floor. Repeat for several bounces and the difference might become noticeable. This is one real part. The other arises because the ball slows as it rises and accelerates again as it falls.
This is quite a common problem for people writing pong clones. The solution is to, upon detecting a collision, not only reverse the velocity but also alter the ball position so that it doesn't intersect the paddle.
Otherwise it is possible for the ball to become stuck inside the paddle, constantly negating vx = -vx = vx = -vx each frame. It won't leave the paddle until its y momentum moves it far enough up or down to escape.
A number of things could be causing the problem.
Notably, if the ball can travel more than one pixel per "tick" or "frame", it may intersect the paddle by more several pixels by the time the collision is detected.
You then reverse bounce the ball off the paddle by altering its velocity, but depending on the new angle, it may take several frames for the ball to completely leave the paddle. So, on the next tick, it's still intersecting and you're reversing the velocity again. A freak occurrence of this may well lead to the ball eventually leaving the paddle on the other side, appearing to fly straight through.
You may want to put a "do not collide for a while" flag on that paddle-ball combination, when the intersection is first detected.
As a related issue, if the ball is going fast enough (particularly when its x
-component is highest, like when the ball is travelling almost entirely horizontally, so that there is the least of the paddle for it to get through), there may in fact be no frames where the ball is physically intersecting the paddle.
This all depends on your code, which we can't see. Hopefully the above should give you some ideas, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With