Why doesn't Mathf.Abs work to check for object movement?

I’m trying to use Mathf.Abs to test for a change in the object’s current and last position. Basically, if the absolute value of the difference in the object’s x or z value exceeds, say, .1, I want the script to know about it (the script then plays footsteps). Conversely, once the absolute value of the difference goes below 1, then I want the script to stop the footsteps sound.

Here’s the (non-working) script:

    function Update () 
{
	curPos = gameObject.transform.position;
	
	if(Mathf.Abs(curPos.x - lastPos.x) > .01 || Mathf.Abs(curPos.z - lastPos.z) > .01 && !isMoving)
	
	{
		isMoving = true;
		gameObject.audio.loop = true;
		gameObject.audio.clip = forestWalk;
		gameObject.audio.Play();
	}
	
	if(Mathf.Abs(curPos.x - lastPos.x) > .01 || Mathf.Abs(curPos.z - lastPos.z) > .01 && isMoving)
	
	{
	
		isMoving = false;
	}
	
	if(Mathf.Abs(curPos.x - lastPos.x) > .01 || Mathf.Abs(curPos.z - lastPos.z) > .01 && !isMoving)
	
	{
		gameObject.audio.Stop();
	}
	lastPos = curPos;
}

Any ideas? Thanks everyone.

This answer is no longer relevant since the code example was changed

The result of calling Mathf.Abs can never be less than 0 by definition. Absolute Value always returns a positive number - you’re checking to see if it’s less than 0.

Some little problems:

AND binds tighter than OR, like multiply and add. So xFar || zFar && not-Move really looks like xFar || (zFar && not-Move). Add your own parens: (xFar || zFar) && not-Move.

Your last if says “if they are far, stop footsteps.” I’m guessing you really want to do that if close. For that, use an AND: if(xClose && zClose && moving)

I’d probably redo the ifs, to make it simpler. Maybe start with a big if(close) {do close checks) else {do far checks}

Since position is a vector, you can use vector math rather than checking the individual components. If the distance between curPos and lastPos is larger than your threshold then you want the walking sounds, otherwise you don’t. You can get the distance between them by subtracting, then finding the magnitude. So something like this should work:

if ((lastPos - curPos).magnitude > 0.1)
{
  // TODO : start moving sound if it's not already playing
}
else
{
  // TODO : stop moving sound
}