I refactored and added lots of new features. Thrust instead of mass, rotational multipliers, enhanced gravity (acceleration), and just neat, well-written code and nicely labeled objects.
When it comes to naming variables, methods, arguments, classes, files, and also when commenting, I have a general rule that, “If someone who does not know the programming language can read it, then you’ve made pretty, legible code”.
I see this as a major part of refactoring and annotating. Someone with zero programming experience should be able to read my code and generally understand it if I wrote it correctly.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RocketInput : MonoBehaviour
{
private Rigidbody rigidBodyRocket;
[SerializeField]
private float thrustMultiplier = 14.0f;
[SerializeField]
private float rotationMultiplier = 32.0f;
private AudioSource audioFXRocketBooster;
// Start is called before the first frame update
void Start()
{
AssignComponents();
}
private void AssignComponents()
{
rigidBodyRocket = GetComponent<Rigidbody>();
audioFXRocketBooster = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
ProcessInput();
ProcessAudio();
}
private void ProcessAudio()
{
ControlRocketBoosterSound();
}
private void ProcessInput()
{
LaunchRocketOnSpacePress();
RotateRocketOnAorDPress();
}
private void RotateRocketOnAorDPress()
{
rigidBodyRocket.freezeRotation = true; // Take manual control of rotation by stopping it so that our input applies properly.
if (Input.GetKey(KeyCode.A)) // Keep this separate from the SpaceBar if so you can thrust while rotating.
transform.Rotate(Vector3.forward * rotationMultiplier * Time.deltaTime);
else if (Input.GetKey(KeyCode.D))
transform.Rotate(-Vector3.forward * rotationMultiplier * Time.deltaTime);
rigidBodyRocket.freezeRotation = false; // Resume physics control of rotation.
// New code to add: if rocket is not moving, not being controlled either, then turn OFF freeze rotation.
// Basically, let the rocket fall off the landing area if the user doesn't balance it!
}
private void LaunchRocketOnSpacePress()
{
if (Input.GetKey(KeyCode.Space)) // Keep this separate from the A/D input if's so that you can thrust while rotating.
{
rigidBodyRocket.AddRelativeForce(
Vector3.up * Mathf.Pow(thrustMultiplier, 9 / 8)
);
}
}
private void ControlRocketBoosterSound()
{
if (Input.GetKeyUp(KeyCode.Space))
audioFXRocketBooster.Pause();
else if (audioFXRocketBooster.isPlaying == false && Input.GetKeyDown(KeyCode.Space))
audioFXRocketBooster.Play();
}
}