- Home /
Plane.Raycast vs. Vector3.Projection
So I'm trying to find the intersection between the a ray from the cursor and a defined plane. Obviously, making a Plane and using Plane.Raycast will let me do exactly this. However, I am concerned about performance compared to simply solving the linear algebra without making the plane.
I'm new to C# and Unity, so I just wanted to double check about the performance of Plane.Raycast. It would make sense that they the projection approach is actually how it works under the hood, but given that Physics.Raycast can be quite computationally costly I just wanted to make sure that Plane.Raycast isn't. (btw I'm reusing the Plane structs a lot so allocation of Planes is not an issue)
Thanks
Answer by Hellium · Oct 28, 2019 at 03:39 PM
Here is the exact implementation of Plane.Raycast
// Intersects a ray with the plane.
public bool Raycast(Ray ray, out float enter)
{
float vdot = Vector3.Dot(ray.direction, m_Normal);
float ndot = -Vector3.Dot(ray.origin, m_Normal) - m_Distance;
if (Mathf.Approximately(vdot, 0.0f))
{
enter = 0.0F;
return false;
}
enter = ndot / vdot;
return enter > 0.0F;
}
As you can see, the implementation is not heavy, so you don't need to worry about the performance here.
Answer by Bunny83 · Oct 28, 2019 at 03:56 PM
Unity's Plane struct is pretty much one of the most simplest structs Unity has. It only consists of a normal vector and the distance from origin given as float. The Raycast method just does two dot products. Since Plane is a struct, allocation isn't an issue at all unless you create an array or List of these. If you create your plane with a given normal and a point the initialization is almost for free. The normalizing of the normal is too fast to be considering in most cases. Of course if you plan to test / raycast against the same plane a million times it makes sense to cache it just like any other intermediate value which you don't want to recalculate every time if it doesn't change.
If you really worry about performance because you literally use it million times per frame you might want to consider not using any of the methods Unity provides and inline that simple code to avoid the method calls which are the actual bottleneck of those methods.