- Home /
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.
Comment
Best Answer
Answer by Addyarb · Jun 24, 2015 at 05:46 AM
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());
}
Answer by kmgr · Jun 24, 2015 at 10:48 AM
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;
}
}
Answer by ShinyTaco · Jun 24, 2015 at 06:22 AM
Yeah, that's it. Thanks a million, much appreciated.
Any time, glad to hear it worked for you and good luck with your game!