60 lines
2.0 KiB
C#
60 lines
2.0 KiB
C#
using UnityEngine;
|
|
|
|
public class Player : MonoBehaviour
|
|
{
|
|
[SerializeField] private float moveSpeed = 7f;
|
|
[SerializeField] private float rotateSpeed = 10f;
|
|
[SerializeField] private GameInput gameInput;
|
|
|
|
private bool isWalking;
|
|
private const float playerRadius = .7f;
|
|
private const float playerHeight = 2f;
|
|
|
|
private void Update()
|
|
{
|
|
Vector2 inputVector = gameInput.GetMovementVectorNormalized();
|
|
Vector3 moveDir = new(inputVector.x, 0, inputVector.y);
|
|
float moveDistance = moveSpeed * Time.deltaTime;
|
|
|
|
if (!CanMove(transform.position, moveDir, moveDistance))
|
|
{
|
|
// Cannot move towars moveDir
|
|
//Attempt only x movement
|
|
Vector3 moveDirX = new Vector3(moveDir.x, 0, 0).normalized;
|
|
|
|
if (CanMove(transform.position, moveDirX, moveDistance))
|
|
{
|
|
//Can move only on the X
|
|
moveDir = moveDirX;
|
|
}
|
|
else
|
|
{
|
|
//Cannot move only on the X
|
|
//Attempt only Z movement
|
|
Vector3 moveDirZ = new Vector3(0, 0, moveDir.z).normalized;
|
|
|
|
if (CanMove(transform.position, moveDirZ, moveDistance))
|
|
{
|
|
//Can move only on the Z
|
|
moveDir = moveDirZ;
|
|
}
|
|
else
|
|
{
|
|
//Cannot move in any direction
|
|
}
|
|
}
|
|
}
|
|
transform.position += moveDir * moveDistance;
|
|
|
|
isWalking = moveDir != Vector3.zero;
|
|
transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
|
|
}
|
|
|
|
public bool IsWalking() => isWalking;
|
|
|
|
private static bool CanMove(Vector3 position, Vector3 moveDir, float moveDistance)
|
|
{
|
|
return !Physics.CapsuleCast(position, position + Vector3.up * playerHeight, playerRadius, moveDir, moveDistance);
|
|
}
|
|
}
|