Well, I did solve the problem of adding thruster sounds. It is not very eloquent but it gets the job done. I don’t like the sound I made and I hope I can just swap out the sound file for a different named exactly the same.
Here is the solution that I came up with:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
[SerializeField] float mainThrust = 100f;
[SerializeField] float rotationThrust = 1f;
[SerializeField] AudioClip mainEngine;
[SerializeField] AudioClip thrusters;
[SerializeField] ParticleSystem mainEngineParticles;
[SerializeField] ParticleSystem leftThrusterParticles;
[SerializeField] ParticleSystem rightThrusterParticles;
Rigidbody rb;
AudioSource audioSource;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
ProcessThrust();
ProcessRotation();
}
void ProcessThrust()
{
if (Input.GetKey(KeyCode.Space))
{
StartThrusting();
}
else
{
StopThrusting();
}
}
void ProcessRotation()
{
if (Input.GetKey(KeyCode.A))
{
RotateLeft();
audioSource.PlayOneShot(thrusters);
}
else if (Input.GetKey(KeyCode.D))
{
RotateRight();
audioSource.PlayOneShot(thrusters);
}
else
{
StopRotating();
}
}
void StartThrusting()
{
rb.AddRelativeForce(Vector3.up * mainThrust * Time.deltaTime);
if (!audioSource.isPlaying)
{
audioSource.PlayOneShot(mainEngine);
}
if (!mainEngineParticles.isPlaying)
{
mainEngineParticles.Play();
}
}
void StopThrusting()
{
audioSource.Stop();
mainEngineParticles.Stop();
}
private void RotateLeft()
{
ApplyRotation(rotationThrust);
if (!rightThrusterParticles.isPlaying)
{
rightThrusterParticles.Play();
}
}
private void RotateRight()
{
ApplyRotation(-rotationThrust);
if (!leftThrusterParticles.isPlaying)
{
leftThrusterParticles.Play();
}
}
private void StopRotating()
{
rightThrusterParticles.Stop();
leftThrusterParticles.Stop();
}
void ApplyRotation(float rotationThisFrame)
{
rb.freezeRotation = true; // freezing rotation so we can manually control rotation
transform.Rotate(Vector3.forward * rotationThisFrame * Time.deltaTime);
rb.freezeRotation = false; // unfreezing rotation so physics system can take over
}
}