using System.Collections;
using TMPro;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float _moveSpeed = 10f;
[SerializeField] private float _turnSpeed = 5f;
[SerializeField] private float _sprintSpeed = 4f;
public float horizontal;
public float vertical;
CharacterController _characterController;
public bool isGrounded;
Quaternion _targetRotation;
Coroutine _rotation;
public float rotationSpeed = 360.0f;
private void Awake()
{
_characterController = GetComponent();
}
private void Update()
{
CalculateMovement();
if (Input.GetKey(KeyCode.LeftShift) && vertical > 0)
{
if (_rotation != null)
{
StopCoroutine(_rotation);
_rotation = null;
}
Sprint();
}
else if (Input.GetKeyDown(KeyCode.Tab))
{
_targetRotation = Quaternion.Euler(0, 180, 0) * transform.rotation;
if(_rotation == null)
{
_rotation = StartCoroutine(RotateToTargetOvertTime());
}
}
}
private void CalculateMovement()
{
vertical = Input.GetAxis(“Vertical”);
horizontal = Input.GetAxis(“Horizontal”);
Vector3 direction = new Vector3(0f, 0f, vertical);
Vector3 movement = transform.TransformDirection(direction) * _moveSpeed;
transform.Rotate(0f, horizontal * _turnSpeed, 0f);
isGrounded = _characterController.SimpleMove(movement);
}
private void Sprint()
{
float newTurnSpeed = _turnSpeed - 1.4f; //this reduces the speed at which the player turns while sprinting, so they don’t turn on a dime
//3 or 3.5 should be a good newTurnSpeed
vertical = Input.GetAxis(“Vertical”);
horizontal = Input.GetAxis(“Horizontal”);
Vector3 direction = new Vector3(0f, 0f, vertical);
Vector3 movement = transform.TransformDirection(direction) * _sprintSpeed;
transform.Rotate(0f, horizontal * newTurnSpeed, 0f); //add the new turn speed
isGrounded = _characterController.SimpleMove(movement);
}
IEnumerator RotateToTargetOvertTime()
{
while(Quaternion.Angle(transform.rotation, _targetRotation) > 1f) //in this case, 1f means degrees
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, _targetRotation, rotationSpeed * Time.deltaTime);
yield return null;
}
_rotation = null;
}
}