Search Unity

Unnecessary Ray Constructor when Raycasting

Discussion in 'Physics' started by hugeandy, Sep 20, 2021.

  1. hugeandy

    hugeandy

    Joined:
    Nov 2, 2016
    Posts:
    131
    Hi all,

    Noticed something strange today when raycasting. It would seem that even if I feed a Ray into the Raycast method, the profiler shows the a Ray constructor being executed. F12'ing on the methods reveals the following.

    1. My code:
    Code (CSharp):
    1. var ray = new Ray(Vector3.zero, Vector3.forward);
    2. Physics.Raycast(ray);
    2. Physics.Raycast source:
    Code (CSharp):
    1. public static bool Raycast(Ray ray) => Physics.defaultPhysicsScene.Raycast(ray.origin, ray.direction);
    3. PhysicsScene.Raycast source:
    Code (CSharp):
    1.  
    2. public bool Raycast(
    3.   Vector3 origin,
    4.   Vector3 direction,
    5.   [DefaultValue("Mathf.Infinity")] float maxDistance = float.PositiveInfinity,
    6.   [DefaultValue("Physics.DefaultRaycastLayers")] int layerMask = -5,
    7.   [DefaultValue("QueryTriggerInteraction.UseGlobal")] QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal)
    8. {
    9.   float magnitude = direction.magnitude;
    10.   if ((double) magnitude <= 1.40129846432482E-45)
    11.     return false;
    12.   Vector3 direction1 = direction / magnitude;
    13.   return PhysicsScene.Internal_RaycastTest(this, new Ray(origin, direction1), maxDistance, layerMask, queryTriggerInteraction);
    14. }
    15.  
    1. I create a Ray and feed it into Raycast
    2. Physics.Raycast unpacks my Ray and pases the pos and dir parameters into the PhysicsScene Raycast method
    3. PhysicsScene Raycast creates a new Ray (line 13) and passes that into PhysicsScene.Internal_RaycastTest

    Why is there not a PhysicsScene method which accepts a Ray, which can then pass that straight onto the internal method, which clearly accepts a Ray, avoiding the extra Ray constructor?

    Worth noting that the Ray constructor normalises the direction vector which is why this is slow and should be avoided.

    Code (CSharp):
    1. public Ray(Vector3 origin, Vector3 direction)
    2. {
    3.   this.m_Origin = origin;
    4.   this.m_Direction = direction.normalized;
    5. }
    Cheers,
    Andy
     
    p3t3rbruc3 and forestrf like this.