And now for the explanation of the formula. I made a figure.
- paddlecollision.png (13.65 KiB) Viewed 2503 times
You see the ball in red and its bounding box (gray square around the balls). The coordinates of the ball are the upper left coordinates of the bounding box. The ball moves from right to left and somewhere crosses the line of the paddle.
To determine the coordinates of the potential collision, we have to find the coordinates of paddle.x and collision.y. Now comes some geometry. You see the horizontal arrows in blue and green. If you calculate the ration green divided by blue, then you get a number between 0 and 1. This is alpha. For geometrical reasons (its called
Intercept theorem) the ratio of the vertical green and blue arrows is the same.
So to find the value of collision.y we first calculate the vertical blue arrow (ball.y-ball.oldy) and multiply it by alpha to get the length of the green vertical arrow. We have to add this to the ball.oldy. So the final formula is
Code: Select all
collision.y = ball.oldy + (ball.y-ball.oldy)*alpha
To find alpha in the first place, we divide the horizontal green arrow by the horizontal blue one:
Code: Select all
alpha = (paddle.x - ball.oldx) / (ball.x-ball.oldx)
If you now check for collision on the right side, you have to take the balls width into account. For calculating alpha, instead of using paddle.x you need paddle.x-ball.width, because collision already occurs, when the balls right side collides with the paddle.