# [C#] Raycast based AI

i have this code

``````Vector3 fwd = transform.InverseTransformDirection(Vector3.forward);
Vector3 left = transform.InverseTransformDirection(new Vector3(-ViewAngle, 0, 1));
Vector3 right = transform.InverseTransformDirection(new Vector3(ViewAngle, 0 , 1));

bool CanMove;
if(Physics.Raycast(transform.position, fwd, out hit, StayD))
CanMove = false;
else if(Physics.Raycast(transform.position, left, out lhit, StayD-5) || Physics.Raycast(transform.position, right, out rhit, StayD-5))
CanMove = false;
else
CanMove = true;
if(CanMove)
transform.Translate(Vector3.forward * Time.deltaTime * MoveSpeed);
``````

When i run the code, the ai keeps going even though there is something infront of it, the code worked fine when there was no test for if there is something on itâ€™s forward left and forward right, what can i do to make this work, i need the ai to be able to see like this:

[1387-Ai+Diagram.png|1387]

the green is where can be seen.
i would like for the view angle to be adjustable.
any suggestions, you can look at the full code here:
AiCode

Use Debug.DrawRay to check where the rays are cast. Make sure the distance is sufficient to hit the obstacles. You can use transform.forward instead of InverseTransformDirection.

This:

``````Vector3 fwd = transform.InverseTransformDirection(Vector3.forward);
Vector3 left = transform.InverseTransformDirection(new Vector3(-ViewAngle, 0, 1));
Vector3 right = transform.InverseTransformDirection(new Vector3(ViewAngle, 0 , 1));
``````

Should Be This:

``````Vector3 fwd = transform.TransformDirection(Vector3.forward);
Vector3 left = transform.TransformDirection(new Vector3(-ViewAngle, 0, 1));
Vector3 right = transform.TransformDirection(new Vector3(ViewAngle, 0 , 1));
``````