Reputation: 1241
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?
Upvotes: 18
Views: 3671
Reputation: 26
A solution I found when making pong was to use vx = abs(vx) when a collision with the left paddle is detected and vx = -abs(vx) when a collision with the right paddle is detected. this ensures the ball bounces only once,eliminating the travel inside the paddle caused by multiple bounces.
Upvotes: 0
Reputation: 3835
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.
Upvotes: 29
Reputation: 385088
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.
Upvotes: 10
Reputation: 7387
This is usually caused by too fast movement of a ball. Where one frame it is traveling to a wall and next frame it is already placed behind the wall. Rhe collision just does not happens. You can negate that by looking further along balls trajectory and checking for obstacles.
Upvotes: 0
Reputation: 76519
Your awesome drawing shows me that you're not detecting a vertical collision. You should do the same thing you do for the x coordinates for the y coordinates.
Upvotes: 0