Ruben
Ruben

Reputation: 27

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);
     }

Upvotes: 0

Views: 6543

Answers (2)

FaTaLL
FaTaLL

Reputation: 511

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..

Upvotes: 0

user3275104
user3275104

Reputation:

You should be able to just create multiple raycasts (Simply create a new ray).

To achieve the degree you're looking for you could use something like this where you choose your ray direction:

(transform.forward + transform.right).normalized
(transform.forward - transform.right).normalized

Upvotes: 1

Related Questions