So my code is not the same as Ben’s, I tried some different solutions, because of the challenges, which I think is a really good way to learn. Worst case scenario i will copy paste Ben’s script from github and delete my own
The only change in behaviour I think will be that A and D cancel eachother out if both are being pressed at the same time, because im not using “else if” from the input. I prefer this solution to having a dominant button.
My code otherwise works the same way, but i tried to keep input and audio in separate scripts, as It will be better for me in the future, if more sounds or input will be added/changed.
Would be appreciated with feedback, if you see some bad code in here!
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rocket : MonoBehaviour {
Rigidbody rigidBody;
AudioSource myAudioSource;
[SerializeField] float rcsThrust = 100f;
[SerializeField] float mainThrust = 1300f;
bool thrusting = false;
Vector3 myInputDirection = new Vector3();
// Use this for initialization
void Start () {
rigidBody = GetComponent<Rigidbody>();
myAudioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update ()
{
ProcessInput(); // get input before movement logic
Rotate();
AudioLogic();
}
private void AudioLogic()
{
if (thrusting && !myAudioSource.isPlaying)
{
myAudioSource.Play();
}
else if (!thrusting)
{
myAudioSource.Stop();
}
}
private void ProcessInput()
{
// Thrusting
if (Input.GetKey(KeyCode.Space))
{
thrusting = true; // used for audio logic
Thrust();
}
else
{
thrusting = false;
}
if (Input.GetKey(KeyCode.A))
{
myInputDirection += Vector3.forward;
}
if (Input.GetKey(KeyCode.D))
{
myInputDirection -= Vector3.forward;
}
}
private void Thrust()
{
float thrustThisFrame = mainThrust * Time.deltaTime;
rigidBody.AddRelativeForce(Vector3.up * thrustThisFrame);
}
private void Rotate()
{
float rotationThisFrame = rcsThrust * Time.deltaTime;
rigidBody.freezeRotation = true; // take manual control of rotation
transform.Rotate(myInputDirection * rotationThisFrame); // get input and rcs thrust, and rotate accordingly
myInputDirection = Vector3.zero; // reset input direction every frame, to prevent input vectors from accumulating
rigidBody.freezeRotation = false; // resume physics engine control of rotation
}
}