89 lines
2.4 KiB
C#
89 lines
2.4 KiB
C#
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
[RequireComponent(typeof(CharacterController))]
|
||
|
|
public class SimplePlayerController : MonoBehaviour
|
||
|
|
{
|
||
|
|
[Header("Movement")]
|
||
|
|
public float moveSpeed = 4.5f;
|
||
|
|
public float jumpForce = 1.2f;
|
||
|
|
public float gravity = -18f;
|
||
|
|
|
||
|
|
[Header("Look")]
|
||
|
|
public Camera playerCamera;
|
||
|
|
public float mouseSensitivity = 2.2f;
|
||
|
|
public float minPitch = -75f;
|
||
|
|
public float maxPitch = 75f;
|
||
|
|
|
||
|
|
private CharacterController characterController;
|
||
|
|
private Vector3 verticalVelocity;
|
||
|
|
private float pitch;
|
||
|
|
private bool inputEnabled = true;
|
||
|
|
|
||
|
|
private void Awake()
|
||
|
|
{
|
||
|
|
characterController = GetComponent<CharacterController>();
|
||
|
|
|
||
|
|
if (playerCamera == null)
|
||
|
|
playerCamera = GetComponentInChildren<Camera>();
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Start()
|
||
|
|
{
|
||
|
|
SetInputEnabled(true);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Update()
|
||
|
|
{
|
||
|
|
if (!inputEnabled)
|
||
|
|
return;
|
||
|
|
|
||
|
|
Look();
|
||
|
|
Move();
|
||
|
|
}
|
||
|
|
|
||
|
|
public void SetInputEnabled(bool enabled)
|
||
|
|
{
|
||
|
|
inputEnabled = enabled;
|
||
|
|
|
||
|
|
if (!enabled)
|
||
|
|
verticalVelocity = Vector3.zero;
|
||
|
|
|
||
|
|
Cursor.visible = !enabled;
|
||
|
|
Cursor.lockState = enabled ? CursorLockMode.Locked : CursorLockMode.None;
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Look()
|
||
|
|
{
|
||
|
|
float yaw = Input.GetAxis("Mouse X") * mouseSensitivity;
|
||
|
|
float pitchDelta = Input.GetAxis("Mouse Y") * mouseSensitivity;
|
||
|
|
|
||
|
|
transform.Rotate(Vector3.up * yaw);
|
||
|
|
pitch = Mathf.Clamp(pitch - pitchDelta, minPitch, maxPitch);
|
||
|
|
|
||
|
|
if (playerCamera != null)
|
||
|
|
playerCamera.transform.localEulerAngles = new Vector3(pitch, 0f, 0f);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Move()
|
||
|
|
{
|
||
|
|
bool grounded = characterController.isGrounded;
|
||
|
|
if (grounded && verticalVelocity.y < 0f)
|
||
|
|
verticalVelocity.y = -2f;
|
||
|
|
|
||
|
|
float horizontal = Input.GetAxis("Horizontal");
|
||
|
|
float vertical = Input.GetAxis("Vertical");
|
||
|
|
Vector3 move = transform.right * horizontal + transform.forward * vertical;
|
||
|
|
|
||
|
|
if (move.sqrMagnitude > 1f)
|
||
|
|
move.Normalize();
|
||
|
|
|
||
|
|
characterController.Move(move * (moveSpeed * Time.deltaTime));
|
||
|
|
|
||
|
|
if (grounded && Input.GetKeyDown(KeyCode.Space))
|
||
|
|
verticalVelocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
|
||
|
|
|
||
|
|
verticalVelocity.y += gravity * Time.deltaTime;
|
||
|
|
characterController.Move(verticalVelocity * Time.deltaTime);
|
||
|
|
}
|
||
|
|
}
|