I’m a mostly a beginner in Unity (been at it for no more than 2 weeks), and I’d like to get feedback on a player controller I’ve been working on today. It’s based off of some Internet tutorials, forum answers and try and error learning.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float moveSpeed = 7f;
public float turnSpeed = 90f;
public float turnAroundSpeed = 720f;
public float turnAroundCooldown = 0.2f;
private Vector3 movement;
private float angle;
private bool doTurnAround = false, canTurnAround = true, hasTurnedAround = true;
private bool isWalking = false;
private bool isRotating = false;
private Rigidbody rigidbody;
// Use this for initialization
private void Start () {
rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
private void Update () {
float vInput = Input.GetAxis("Vertical");
float hInput = Input.GetAxis("Horizontal");
doTurnAround = (canTurnAround && vInput < 0f) ? true : false;
isWalking = (vInput > 0f) ? true : false;
isRotating = (hInput != 0f) ? true : false;
if (doTurnAround)
StartTurnAround();
if (!hasTurnedAround)
return;
if (isWalking)
{
Walk(vInput);
Rotate(hInput);
}
else if (isRotating)
Rotate(hInput);
else
Idle();
}
private void FixedUpdate()
{
rigidbody.MoveRotation(Quaternion.Euler(Vector3.up * angle));
rigidbody.MovePosition(rigidbody.position + (movement * Time.deltaTime));
}
private void Idle()
{
}
private void Walk(float vInput)
{
Debug.Log("WALK");
movement = transform.forward * vInput * moveSpeed;
}
private void Rotate(float hInput)
{
Debug.Log("ROTATE");
float rotation = turnSpeed * hInput;
angle = Mathf.LerpAngle(
transform.rotation.eulerAngles.y,
transform.rotation.eulerAngles.y + rotation,
Time.deltaTime
);
}
private void StartTurnAround()
{
Debug.Log("TURN AROUND");
float targetAngle = transform.rotation.eulerAngles.y + 180f;
canTurnAround = false;
hasTurnedAround = false;
StartCoroutine(TurnAround(targetAngle));
}
private IEnumerator TurnAround(float targetAngle)
{
movement = Vector3.zero;
while (Mathf.Abs(Mathf.DeltaAngle(transform.rotation.eulerAngles.y, targetAngle)) > 0.05f)
{
angle = Mathf.MoveTowardsAngle(transform.rotation.eulerAngles.y, targetAngle, turnAroundSpeed * Time.deltaTime);
yield return null;
}
hasTurnedAround = true;
StartCoroutine(DoAfter(turnAroundCooldown, EnableTurnAround));
}
private void EnableTurnAround ()
{
canTurnAround = true;
}
private IEnumerator DoAfter (float delay, System.Action operation)
{
yield return new WaitForSeconds(delay);
operation();
}
}
Thing I’d like to get feedback on would be code structure on the Update function. And if there is a better way of doing things. Thanks!
P.S.: Just to clarify, I’m not a programmer noob, but even less an expert! Also haven’t really ever used C# before. So any and all opinions will be welcome!