- Home /
The question is answered, right answer was accepted
[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:
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
Answer by TheDarkVoid · Jun 24, 2012 at 11:23 PM
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));
That's what I meant with transform.forward. However, your left and right vector are turned forward apparently, so you do need TransformDirection. Could rotate forward, but your method works too.
Answer by Berenger · Jun 24, 2012 at 08:06 PM
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.
i did, it draws the rays, and they are sufficient distance, but it just keeps moving, sometimes is stops and wait like it's suppose to but most of the time it just keeps going.
Follow this Question
Related Questions
AI Field of vision 1 Answer
AI script works, when we add a blocked function it stops working HELP 0 Answers
Need Help making Pong AI beatable 1 Answer
Collider Vision AI question. Solved! 0 Answers
AI raycasting problem 0 Answers