How to Play a Sound Every Time a X,Y,Z Coordinates Change?

Should be pretty simple but can’t think of a solution.

I just need to play a short sound everytime an X,Y,Z coordinate changes, preferable every time it increases or decreases by 1.0.

Any suggestions?

Thanks.

Hey there!

Try something like this… (Warning, untested code)

Vector3 CurrentPosition;
public float timeIncrement = 1;
public AudioClip yourAudioClip;

void Start(){
CurrentPosition = transform.position;
StartCoroutine(CheckPosition());
}

IEnumerator CheckPosition(){
yield return new WaitForSeconds(timeIncrement);
float x = transform.position.x;
float y = transform.position.y;
float z = transform.position.z;

if(CurrentPosition.x > x + 1 || CurrentPosition.x < x - 1 ||
(CurrentPosition.y > y + 1 || CurrentPosition.y < y - 1 ||
(CurrentPosition.z > z + 1 || CurrentPosition.z < z - 1)
GetComponent<AudioSource>().PlayOneShot(yourAudioClip);
CurrentPosition = transform.position;
StartCoroutine(CheckPosition());
}

The simplest way I can think of is to keep a copy of your position vector and check distance every frame. Something along these lines:

public class MyClass : MonoBehaviour
{
    private Vector3 m_pos;

    void Start()
    {
        m_pos = transform.position;
    }

    void Update()
    {
        if (Vector3.Distance(m_pos, transform.position) >= 1.0f)
            {
                PlaySound();
            }

            m_pos = transform.position;
    }
}

Yeah, that’s it. Thanks a million, much appreciated.