I'm having problems controlling audio when pressing a key
I'm trying to control the audio on a game object when a key is held down, i.e. play a thrust audio clip for a ship when the Up Arrow is held down. The code looks like this:
void FixedUpdate ()
{
// *** forward movement ***
if (Input.GetKey(KeyCode.UpArrow))
{
// engage the engines.
GetComponent<Rigidbody>().AddForce(transform.forward * thrustForce * thrustForceBoost);
// show the thrust particle effect.
ThrustParticleEffect.Play();
}
if (Input.GetKeyDown(KeyCode.UpArrow) && Input.GetKeyUp(KeyCode.UpArrow) == false)
{
forwardTotal += 1; // count key presses
thrustAudioSource.Play(); // play thrust audio
}
if (Input.GetKeyUp(KeyCode.UpArrow) && Input.GetKeyDown(KeyCode.UpArrow) == false)
{
thrustForceBoost = 1f; //reset boost if key is no longer pressed
thrustAudioSource.Stop(); // stop thrust audio
}
Whats happening is that when the up arrow is help down most of the time the audio works correctly, then occasionally it seems to flip the audio, i.e. play when key is release and vice versa, and quickly pressing the key repeatedly also makes this happen.
I'm guessing it might be to do with the key detection but not sure. Some of the code above is for detecting a double key press but I don't think its causing this as I've commented is out and the problem persists.
Can anyone help?
Answer by Razorlance · Jan 31, 2017 at 04:01 PM
Ok, I made a rookie mistake, the code above should be in Update() not FixedUpdate(), doh! Once I changed it everything worked fine.