Why is my enemy object shaking in my AI code?

My script here is attached to an 'enemy' object. My enemy walks to certain "points" if the player is far away from him. If the player gets close to him, the enemy follows the player. The problem is that after chasing the player, when he escapes, the enemy should walk back to the "points".

Now I see the enemy object shaking and walking far away from the expected direction?!

public class enemyscript: MonoBehaviour {

public Transform target;
public Transform[] waypoint; // points
NavMeshAgent ePath;
private int farPoint = 0;
public float elife = 100f,distance,look_range = 20.0f;

// Use this for initialization
void Start () {
ePath = GetComponent<NavMeshAgent>();
ePath.speed = 2;
}

// Update is called once per frame
void Update () {
distance = Vector3.Distance(gameObject.transform.position, target.transform.position);

if (ePath.remainingDistance < 0.5f)
{
nextpoint();
}

if (distance < look_range)
{
attack();
}
}

void attack() {
ePath.SetDestination(target.position);
ePath.speed = 6;
}

void nextpoint() {
if (waypoint.Length == 0)
return;
ePath.destination = waypoint[farPoint].position;
farPoint = Random.Range(0, waypoint.Length);
ePath.speed = 2;
}
}


Even though the description of your problem is pretty unclear (what do you mean exactly by shaking and walk far from his direction ?), I can see how your code fails.

In order for the enemies to do these routines, you should add a state variable. This state should take 2 values (or more if needed) PATROL and ATTACK. You can use an enum for this.

Then in your code it becomes easy to deal with the enemy's behaviour

if in PATROL mode, check if you need to switch to ATTACK mode, else follow target or find new one.

if in ATTACK mode, check if you need to go back to PATROL mode and then find new target


In your code you have implicit states as you change the speed and the target according to the distance from the player, but it seems once you went into "attack" mode, you never go back to patroling. If you were using states explicitely it would be pretty easy to track what is happening.

This other topic might prove useful Finite State Machines for Enemies (AI vs. Entity States)

• Man, my script is very simple. I don't know where is my mistake that make enemy object shaking after chasing player ? I mean by shaking...like "shaking bottle". walk far from his direction If player run away from enemy, enemy object should get back to "points" ? but he behaves like lost, running everywhere and shaking. – user43474 Jan 4 '17 at 16:14
• I do not know exactly what causes the "shaking" but with the code you posted I do not see how your AI goes from the ATTACK state to the PATROL state (even though these states are not explicitely declared as so) – realUser404 Jan 4 '17 at 17:07