Why?
Performance, faster than Raycasts
Accuracy, plane intersections are more precise
What is a Plane?
A plane in Unity is defined by an origin (position vector), and a normal (direction vector perpendicular to the plane). For instance, a plane with origin Vector3.zero and normal Vector3.up
var plane = new Plane(Vector3.up, Vector3.zero); // new Plane(normal, origin)
creates a theoretical plane on the X/Z axes that is infinite in size and located at the origin. Make sure the normal vecor is normalized!
How to intersect a plane with a ray?
Using the Plane.Raycast(ray) method, you input the ray and receive the distance from the intersection point. You then input this distance into the Ray.GetPoint(distance) method inside your ray. Like this:
// var plane from before
var distance : float;
plane.Raycast (new Ray(Vector3(0, 10, 0), -Vector3.up), distance);
var point = Ray.GetPoint(distance);
Debug.Log(point.ToString());
The code should print "(0,10,0)", since the ray starts at 10 units along the Y axis above the origin and travels downward 10 units before it hits the plane.
Example?
Here is an example of using the Plane struct with the Ray struct to efficiently calculate an intersection point.
public Plane groundPlane;
void Update() {
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 point = GetIntersectionPoint(groundPlane, ray)
Debug.Log(point.ToString());
}
}
Vector3 GetIntersectionPoint(Plane plane, Ray ray) {
float rayDistance;
if (plane.Raycast(ray, out rayDistance))
{
return ray.GetPoint(rayDistance);
}
}
Note
Don't be deceived by the Ray struct being used. The plane.Raycast() uses the ray for vector line calculations with the plane and returns a distance on that line to the intersection point.