84 lines
2.5 KiB
C#
84 lines
2.5 KiB
C#
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
[RequireComponent(typeof(CharacterController))]
|
||
|
|
public class SimplePlayerController : MonoBehaviour
|
||
|
|
{
|
||
|
|
public PlayerStats playerStats;
|
||
|
|
public CharacterController characterController;
|
||
|
|
public Transform cameraTransform;
|
||
|
|
|
||
|
|
[Header("Movement")]
|
||
|
|
public float gravity = -25f;
|
||
|
|
public float rotationSpeed = 12f;
|
||
|
|
|
||
|
|
[Header("Camera")]
|
||
|
|
public Vector3 cameraOffset = new Vector3(0f, 9f, -8f);
|
||
|
|
public float cameraYaw = 45f;
|
||
|
|
public float cameraSmooth = 12f;
|
||
|
|
|
||
|
|
private float verticalVelocity;
|
||
|
|
|
||
|
|
private void Awake()
|
||
|
|
{
|
||
|
|
if (characterController == null)
|
||
|
|
{
|
||
|
|
characterController = GetComponent<CharacterController>();
|
||
|
|
}
|
||
|
|
|
||
|
|
if (playerStats == null)
|
||
|
|
{
|
||
|
|
playerStats = GetComponent<PlayerStats>();
|
||
|
|
}
|
||
|
|
|
||
|
|
if (cameraTransform == null && Camera.main != null)
|
||
|
|
{
|
||
|
|
cameraTransform = Camera.main.transform;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Update()
|
||
|
|
{
|
||
|
|
if (Input.GetMouseButton(1))
|
||
|
|
{
|
||
|
|
cameraYaw += Input.GetAxis("Mouse X") * 120f * Time.deltaTime;
|
||
|
|
}
|
||
|
|
|
||
|
|
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
|
||
|
|
input = Vector3.ClampMagnitude(input, 1f);
|
||
|
|
|
||
|
|
Quaternion yawRotation = Quaternion.Euler(0f, cameraYaw, 0f);
|
||
|
|
Vector3 moveDirection = yawRotation * input;
|
||
|
|
|
||
|
|
if (characterController.isGrounded && verticalVelocity < 0f)
|
||
|
|
{
|
||
|
|
verticalVelocity = -1f;
|
||
|
|
}
|
||
|
|
|
||
|
|
verticalVelocity += gravity * Time.deltaTime;
|
||
|
|
|
||
|
|
float speed = playerStats != null ? playerStats.MoveSpeed : 5f;
|
||
|
|
Vector3 velocity = moveDirection * speed;
|
||
|
|
velocity.y = verticalVelocity;
|
||
|
|
characterController.Move(velocity * Time.deltaTime);
|
||
|
|
|
||
|
|
if (moveDirection.sqrMagnitude > 0.001f)
|
||
|
|
{
|
||
|
|
Quaternion targetRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
|
||
|
|
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void LateUpdate()
|
||
|
|
{
|
||
|
|
if (cameraTransform == null)
|
||
|
|
{
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
Quaternion yawRotation = Quaternion.Euler(0f, cameraYaw, 0f);
|
||
|
|
Vector3 desiredPosition = transform.position + yawRotation * cameraOffset;
|
||
|
|
cameraTransform.position = Vector3.Lerp(cameraTransform.position, desiredPosition, cameraSmooth * Time.deltaTime);
|
||
|
|
cameraTransform.LookAt(transform.position + Vector3.up * 1.3f);
|
||
|
|
}
|
||
|
|
}
|