My AI keeps flickering between stopping and moving.

I’m having a problem with my Enemy AI, I have 2 animations set for my AI, an idle one and a running one, as you might of guessed, they’re for standing and moving respectively.

However, the AI keeps switching between the 2 animations, regardless of whether or not they’re actually moving. When debugging it, getting to log the bool that tells it if it’s moving or not, I noticed it kept flickering between the true and false.

Here’s the code, I hope you guys notice something I overlooked:

    			if (CompareVector3 (myTransform.position, previousPosition)) 
    			{
    				moving = false;
    			} 
    			else 
    			{
    				moving = true;
    			}
    	public bool CompareVector3 (Vector3 a, Vector3 b)
    	{
    		if (Mathf.Approximately (a.x, b.x) &&
    			(Mathf.Approximately (a.y, b.y)) &&
    			(Mathf.Approximately (a.z, b.z))) {
    			return true;
    		} 
else 
{
    			return false;
    		}
    	}

What am I doing wrong?

I know that isn’t much info, but aside from the previousPosition value is set to the current position at the end of “Update()”, that’s the only code that relates to the problem.

copy paste at the start of comparevector3

Debug.log("a.x " + a.x + " b.x " + b.x + " are approx = " + Mathf.Approximately (a.x, b.x))
Debug.log("a.y " + a.y + " b.y " + b.y + " are approx = " + Mathf.Approximately (a.y, b.y))
Debug.log("a.z " + a.z + " b.z " + b.z + " are approx = " + Mathf.Approximately (a.z, b.z))

that will let you know if your results are making sense.

if you see really really small changes it’s either wierd movement code or approx isn’t doing a good job and you need to write up your own if approx statement

something like

if(mathf.abs(a.x - b.x) > .1)