Search code examples
c#unity-game-engineraycastinggameobject

Multiple raycasts from game object


I got a little scene in unity with obstacles and such where the AI shoots off a raycast to detect if there is wall infront of it, and after that it decides to rotate if such a matter occurs. I am now trying to get multiple raycasts so it can check the same but with the +45 and - 45 angle of vision, otherwise the robot can only check its front ray. How would i do this? Code sample below.

ray = new Ray(transform.position + Vector3.up, transform.forward);
     RaycastHit hit;
     if (Physics.Raycast(ray, out hit, 55f))
     {
         if (hit.collider.tag == ("Pick Up"))
         {
             Debug.DrawLine(ray.origin, hit.point, Color.red);
             transform.position = Vector3.MoveTowards(transform.position, hit.point, Time.deltaTime * speed);
         }
         else
         {
             Debug.DrawLine(ray.origin, hit.point, Color.blue);
             transform.Rotate(0, -80 * Time.deltaTime, 0);
         }
     }
     else
     {
         transform.position += transform.forward * speed * Time.deltaTime;
         Debug.DrawLine(ray.origin, hit.point, Color.white);
     }

Solution

  • Creating many rays is not efficient way to solve this problem. You can use Physics.SphereCast. You will cast it like you did with raycast and give it a radius to fill between 45 and -45 angle of vision.

    You can calculate the distance between two angle like this;

    Create 2 more raycasts, 1 for 45, 1 for -45. You will take their normalized vector.

    Vector3 distance = Vector3.Distance(Raycast45.normalized, Raycast-45.normalized);
    

    I hope it helps..