Ray/plane intersections
Here, I'll go over how to test for the intersection between a ray and a plane. I've also provided code at the bottom as a public domain work.
Defining our shapes
If you take the dot product of two vectors that are perpendicular, then the result is zero. This means that we can define our plane as follows:
- Po
- origin of the plane
- Pn
- plane surface normal
- V
- any point on the plane
The above equation imposes a simple requirement: the vector from any point on the plane to any other point on the plane must be perpendicular to the plane's normal. The "plane origin" is just a point that we already know is on the plane; it doesn't have to be at any specific part of the plane (e.g. a centerpoint), and it isn't otherwise "special."
Our ray, meanwhile, is most usefully defined as:
- Ro
- the ray's origin
- Rd
- the ray's direction
- Hp
- the position at which the ray hits some surface
- Hd
- the hit distance: the distance from the ray origin to the hit position
Solving for the ray
We check for intersections by substituting our ray equation into our plane equation:
We want to solve for
Let's group the terms that are multiplied by
Now, we can recombine some of these multiplications-and-additions back into dot products:
Of course, we want to get
Voila! Every ray that intersects the plane will have a solution for the above equation, which means that if the above equation is unsolveable — that is, if it would involve a division by zero — then the ray doesn't intersect the plane.
That said, we also need to double-check one more condition:
We need to make sure that the hit distance isn't negative — that our hit position isn't behind our ray.
Free code!
The following C++ code is licensed under CC0 (full legal text / summary), and so is effectively a public domain work. You can incorporate it into your programs without the need for attribution, payment, or similar. (That said, linking back here would be polite!)
This code makes use of the GLM library for vector math.