Does anyone know a very simple physics engine, or just a set of basic functions that could complete these tasks: Simple point, line, and rectangle collision detection? I looked at Box2D but it is way too advanced for what I am making. I just need some simple code. Thanks in advance!
Share
Here’s my shot at point/line collision detection. The important thing is to avoid trig functions, divisions, and other expensive operations so as not to slow things down too much.
As GMan’s comment notes, you need to bear in mind that the point will be moving. So you’ll have the current position of the point (let’s call it
A) and the possible new position of the point (B). You need to find out if, when the point moves fromAtoB, it would collide with a line.Let’s call the start and end points of the line
CandD. A collision will occur only if the linesABandCDintersect.Let’s describe the line
ABusing the standard equationUx + Vy + W = 0. After some algebra, the equation comes out as:We can describe the line
CDin terms of a parametertand constantsX Y U V:It’s helpful if we set
t=0at pointC, andt=1at pointD. By consideringt=0we can work outXandY. And by consideringt=1we can work outUandV. This givesTo find the intersection point of the two lines, substitute these into the equation we found for
AB, which givesThis reduces to
where q =
(ay - by)(cx - dx) - (ax - bx)(cy - dy)qis zero, the lines are parallel and do not meet.0 < t < 1then the line extrapolated fromABintersectsCD.But we still don’t know that this intersection is actually between the points
AandB. So we need to repeat all the previous steps, swappingABandCD, and writing the lineABin terms of a parameters. This gives:0 < s < 1then the line extrapolated fromCDintersectsAB.That’s it. So in your code you start by calculating
q. Ifqis zero then the lines are parallel. Otherwise, go on to calculatetands. If0 < t < 1and0 < s < 1then a collision is about to happen. To find the location of the collision, substitutetorsback into the original equations forCD.For extra speed you can remove the divisions by
q– it’s possible to just check whether the top half of each fraction is in the correct range, and then each check should only need 10 multiplication operations.