Hello, I'm learning about collision detection. Can someone explain the math behind these two simple collision functions below please? Couldn't understand it very well from the book I'm reading.
A plane in 3d is defined by two things:
- the position vector of one point in the plane (probably PositionOfPlane in your example);
- a vector normal to the plane (probably NormalOfPlane in your example); the direction of this will also decide which direction is "in front of" and which is "behind" the plane.
Your first function has an error in that it doesn't seem to return any required integer value. Presumably it should be returning -1, 1 or 0 for behind, in front, or in the plane , respectively.
That apart, if you take the dot product (aka "scalar product") of two vectors you will get essentially the projection of one onto the other (times the length of the "other"); the formula is a•b = a b cos(θ)
where a and b are the lengths of vectors a and b and θ is the angle between their positive directions. If their positive directions are less than 90 degrees apart the cosine will make the dot product positive; greater than 90 degrees will make the dot product negative.
To find this displacement dot-product'ed with the normal vector you want
(point - pointInPlane) dot (normal vector)
which your code separates as (in lines 6-9):
(point) dot (normal vector) - (pointInPlane) dot (normal vector).
If this works out positive then the displacement of the point is in the same direction as the normal vector ("forward of plane") and if negative then in the opposite direction ("backward of plane"). If 0 then the displacement between point and pointInPlane is perpendicular to the normal vector and hence you are actually in the plane.
For the second function, there will be intersection if either one point is forward and the other backward of the plane (the first two if conditions) or either point is in the plane (the last two if conditions).
Your line 25 could actually be simplified to if (startPosition * finishPosition <= 0 )
and would still encompass all the relevant possibilities.
I should make sure that you correct the first function to return the relevant integer if you are going to use it.