first commit
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(CharacterController))]
|
||||
public class SimpleFPSController : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private Camera playerCamera;
|
||||
[SerializeField] private float moveSpeed = 5f;
|
||||
[SerializeField] private float mouseSensitivity = 2f;
|
||||
[SerializeField] private float gravity = -20f;
|
||||
[SerializeField] private bool allowJump = true;
|
||||
[SerializeField] private float jumpHeight = 1.2f;
|
||||
|
||||
private CharacterController characterController;
|
||||
private float verticalVelocity;
|
||||
private float cameraPitch;
|
||||
|
||||
public void Configure(Camera targetCamera)
|
||||
{
|
||||
playerCamera = targetCamera;
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
characterController = GetComponent<CharacterController>();
|
||||
|
||||
if (playerCamera == null)
|
||||
{
|
||||
playerCamera = GetComponentInChildren<Camera>();
|
||||
}
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
GameUIState.Reset();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
HandleLook();
|
||||
HandleMovement();
|
||||
}
|
||||
|
||||
private void OnApplicationFocus(bool hasFocus)
|
||||
{
|
||||
if (hasFocus)
|
||||
{
|
||||
GameUIState.SyncCursorAndTime();
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleLook()
|
||||
{
|
||||
if (GameUIState.IsAnyBlockingUIOpen || playerCamera == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
|
||||
var mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
|
||||
|
||||
cameraPitch -= mouseY;
|
||||
cameraPitch = Mathf.Clamp(cameraPitch, -80f, 80f);
|
||||
|
||||
playerCamera.transform.localRotation = Quaternion.Euler(cameraPitch, 0f, 0f);
|
||||
transform.Rotate(Vector3.up * mouseX);
|
||||
}
|
||||
|
||||
private void HandleMovement()
|
||||
{
|
||||
if (characterController == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (characterController.isGrounded && verticalVelocity < 0f)
|
||||
{
|
||||
verticalVelocity = -2f;
|
||||
}
|
||||
|
||||
if (!GameUIState.IsAnyBlockingUIOpen)
|
||||
{
|
||||
var horizontal = Input.GetAxisRaw("Horizontal");
|
||||
var vertical = Input.GetAxisRaw("Vertical");
|
||||
var moveDirection = (transform.right * horizontal + transform.forward * vertical).normalized;
|
||||
|
||||
characterController.Move(moveDirection * moveSpeed * Time.deltaTime);
|
||||
|
||||
if (allowJump && Input.GetButtonDown("Jump") && characterController.isGrounded)
|
||||
{
|
||||
verticalVelocity = Mathf.Sqrt(jumpHeight * -2f * gravity);
|
||||
}
|
||||
}
|
||||
|
||||
verticalVelocity += gravity * Time.deltaTime;
|
||||
characterController.Move(Vector3.up * verticalVelocity * Time.deltaTime);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user