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?