PaulCunningham wrote:piku wrote:
I was trying to work this through in my head the other day, and can't work out what should happen if the ball does hit a corner of a rectangle, or if it hits the end of a line. Should it bounce back in the direction it came from, or reflect off (but which way?).
Take a look at this article by Paul Nettle:
http://www.gamedev.net/reference/articl ... le1026.asp
Ultimately he uses it to perform ellipsoid collision in a 3d world but starts off with some simple circle / plane and then circle / line tests and there's lots of pictures too!
I had a quick look at this, and it does nothing of the sort ! I've worked out the maths for generalised ellipsoid collisions and it's a few order of magnitudes harder than box/sphere/polygon collisions. As he only supplies pseudocode not source code or a working app it's difficult to see what he's actually achieved.
Going back to the original problem, how you bounce a ball off the end of a line is up to you: it's a design problem which is pretty important in Pong, Arkanoid and similar. The most 'realistic' approach, i.e. the one that matches idealised physics of a ball hitting a line, is to think of the lines as having rounded ends and bounce the ball off them. Helpfully Arkanoid makes this explicit by rounding the ends of its bats:
What you do is:
At the point where the ball gets close enough to a line (e.g. dist == ball radius) project it onto the line to see if it is alongside the line or at an end.
If alongside the line reflect it off the line
If not it's at an end. Work out the vector from the end to the ball centre. The reflection then takes place using this vector, i.e. it bounces as if it hit a surface with this vector as normal/perpendicular.
If your ball is small and moving quickly you might need to work out the time too, to get an accurate result. Simplest is something like binary subdivision, i.e. once you detect a collision at t = t1, and they were seperate at t = t0, calculate the seperation at t2 = (t0 + t1) / 2. Then if they are also close enough then check at t3 = (t0 + t2) / 2, otherwise use t3 = (t2 + t1) / 2. Its easiest to this a fixed number of times, as many as you need to get an accurate enough time.