Hi community,
I’m in the learning process and have a little bug which I can’t fix.
When I play the game and press the space bar, the sound plays not one time and it repeats and repeats and you hear a distorted sound. I checked my code but couldn’t find out why.
Here is the code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rocket : MonoBehaviour {
Rigidbody rigidBody;
AudioSource audioSource;
void Start () {
rigidBody = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update ()
{
Thrust();
Rotate();
}
private void Thrust()
{
if (Input.GetKey(KeyCode.Space))
{
rigidBody.AddRelativeForce(Vector3.up);
print("Thrusting");
//so it doesn't layer the sound on each other
if (!audioSource.isPlaying)
{
audioSource.Play();
}
else
{
audioSource.Stop();
}
}
}
private void Rotate()
{
rigidBody.freezeRotation = true; //make manual control of rotation
if (Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.forward);
print("Rotating Left");
}
else if (Input.GetKey(KeyCode.D))
{
transform.Rotate(-Vector3.forward);
print("Rotating Right");
}
rigidBody.freezeRotation = false; // resume physics control of rotation
}
}