This are some changes I made to the CameraController
script, in my opinion they make the code more readable and organized.
using UnityEngine;
public class CameraController : MonoBehaviour
{
private Transform thisTransform;
private void Awake()
{
thisTransform = transform;
}
private void Update()
{
CameraMovement();
CameraRotation();
}
private void CameraMovement()
{
Vector3 inputMoveDir = Vector3.zero;
if (Input.GetKey(KeyCode.W))
inputMoveDir += Vector3.forward;
if (Input.GetKey(KeyCode.S))
inputMoveDir += Vector3.back;
if (Input.GetKey(KeyCode.A))
inputMoveDir += Vector3.left;
if (Input.GetKey(KeyCode.D))
inputMoveDir += Vector3.right;
Vector3 moveVector = thisTransform.forward * inputMoveDir.z + thisTransform.right * inputMoveDir.x;
const float moveSpeed = 10f;
thisTransform.position += moveVector * (moveSpeed * Time.deltaTime);
}
private void CameraRotation()
{
Vector3 rotationVector = Vector3.zero;
if (Input.GetKey(KeyCode.Q))
rotationVector += Vector3.up;
if (Input.GetKey(KeyCode.E))
rotationVector += Vector3.down;
const float rotationSpeed = 100f;
thisTransform.eulerAngles += rotationVector * (rotationSpeed * Time.deltaTime);
}
}
The main changes are:
- Removed the {} on the ifs because they have only one line inside (I know this is very controversial, and deppends on personal preference)
- Separated the camera movement and camera rotation in two different private methods, so it is more clear what each part of this code does.
- Saved the transform reference in a private variable. Since its going to get accesed a lot, I think this is a good optimizacion to not look for the same reference lots of times on Update.
- Reordered this multiplication to make it (as my IDE recommends) more efficent.
moveVector * (moveSpeed * Time.deltaTime)
. The result is exactly the same, as multiplying vector * number or number * vector is commutative. The explanation for this one is that it is easier for the computer to calculate vector * (number) than vector * number, and then resulting vector * number again.
Hope you like my modifications to this code, if there is something you do not agree or think I am wrong dont doubt in telling me.
Thanks!