I am working on a script which makes my enemy object patrol around a randomly generated map. What my script does is it has the enemy move forward until it reaches a certain distance from any wall right in front of it where it sets the speed variable to 0 so that forward motion stops. The next step it goes through (and this is where the issue is) is it does a ray cast 45 degrees to the left to see if there is a wall then looks to the right to see if there is a wall. if there is no wall on the left it runs left and checks the front again. if it detects the wall on the left it looks to the right and goes through a similar process. once there is no longer a detected wall in front the script changes the speed variable back to the enemy’s starting speed so that it can move again. in the even that there is a wall to the left and right I set it to randomly choose left or right with a slight bias to left.
The main issue I am having is that when the object detects the wall in front it just stutters back and forth and doesn’t rotate more than a fraction of a degree in either direction, which I can see in the transform component of the enemy object. I attempted to troubleshoot this my self and found that the program is never getting to the part of the script where it rotates so it might be something with that but I have been unable to determine for sure. This is not my full script, only the function I made to do the searching, the rest is just a FixedUpdate which calls the function and then does a vector3 transform forward based on the speed variable changed during the search function
Any help, comments, criticism is appreciated
public void search(){
RaycastHit hit;
Ray ray = new Ray(transform.position, Vector3.forward);
if (Physics.Raycast (ray, out hit, wallDistance)) {
transform.Translate (Vector3.forward * Time.deltaTime * speed, Space.Self);
speed = killSpeed;
test1 = 3;
Ray rayLeft = new Ray (transform.position, vecLeft);
Ray rayRight = new Ray (transform.position, vecRight);
// the if statments in this section check the left, then the right to see if it is clear. if the way is clear for left it will immediatly go left, if not it will check
// the right then go right if it is clear. if both directions are obstructed it will randomly choose left or right with a bias to right and check again. if the path is
// clear it will move forward
if (Physics.Raycast (rayLeft, out hit, wallDistance)) {
if (Physics.Raycast (rayRight, out hit, wallDistance)) {
test1 = 5;
float path = Random.Range(0.0f,1f);
if (path >= 0.65f) {
transform.rotation = Quaternion.Slerp (transform.rotation, left, Time.deltaTime);
} else {
transform.rotation = Quaternion.Slerp (transform.rotation, right, Time.deltaTime);
}
} else {
transform.rotation = Quaternion.Slerp (transform.rotation, right, Time.deltaTime);
}
} else {
transform.rotation = Quaternion.Slerp (transform.rotation, left, Time.deltaTime);
}
} else {
test2 = 5;
speed = startSpeed;
}
}