Search code examples
c++algorithmgame-physicsbounce

Bouncing Ball logics


I have got a ball which bounces of walls. This bounce is simple, i just do this, ( code snippet )

if ( x - moveSpeed < 0 ) // Ball hit left wall
    xVel *= -1;

However i also got a rectangle which the player moves. The bounce on this practically works as the bounce on walls.

But i figured out that when a ball got similar movement as the picture, its impossible for me to make it go straight up again. I therefore need some kind of calculation regarding the rectangles movement to influence the outcoming angle of the ball. The rectangle always got a constant movement speed when moving. This picture shows a rectangle moving to the left and the ball hitting it during its movement, which results in a 90 degree angle. ( Which shouldn't always be 90 ).

Sorry about my crappy pictures i hope they make sense. My math is rusty thats why i really could need a push in the right direction.


Solution

  • No need for any fancy math here. My understanding of these types of games is that the angle the ball comes off of the paddle is determined by where on the paddle it bounces. If it bounces in the middle, then the current angle is preserved. As it bounces closer to the edge of the paddle, the angle is adjusted in the direction of that side of the paddle. Think of the paddle as a rounded surface.