108 lines
3.1 KiB
C#
108 lines
3.1 KiB
C#
using UnityEngine;
|
|
|
|
public class FirstPersonController : MonoBehaviour
|
|
{
|
|
[Header("Movement Settings")]
|
|
public float walkSpeed = 8f;
|
|
public float runSpeed = 14f;
|
|
public float jumpHeight = 2.5f;
|
|
public float gravity = -20f;
|
|
|
|
[Header("Mouse Look Settings")]
|
|
public float mouseSensitivity = 3f;
|
|
public float maxLookAngle = 90f;
|
|
|
|
[Header("References")]
|
|
public Camera playerCamera;
|
|
|
|
// Private variables
|
|
private CharacterController controller;
|
|
private Vector3 velocity;
|
|
private bool isGrounded;
|
|
private float xRotation = 0f;
|
|
|
|
void Start()
|
|
{
|
|
Debug.Log( "Starting game" );
|
|
// Get the CharacterController component
|
|
controller = GetComponent<CharacterController>();
|
|
|
|
// If no camera is assigned, try to find one
|
|
if (playerCamera == null)
|
|
{
|
|
playerCamera = GetComponentInChildren<Camera>();
|
|
}
|
|
|
|
// Lock and hide the cursor
|
|
Cursor.lockState = CursorLockMode.Locked;
|
|
Cursor.visible = false;
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
// Check if player is on the ground
|
|
isGrounded = controller.isGrounded;
|
|
|
|
// Reset vertical velocity when grounded
|
|
if (isGrounded && velocity.y < 0)
|
|
{
|
|
velocity.y = -2f;
|
|
}
|
|
|
|
// Get movement input
|
|
float moveX = Input.GetAxis("Horizontal"); // A/D or Left/Right arrows
|
|
float moveZ = Input.GetAxis("Vertical"); // W/S or Up/Down arrows
|
|
|
|
// Calculate movement direction
|
|
Vector3 move = transform.right * moveX + transform.forward * moveZ;
|
|
|
|
// Determine current speed (run if Shift is held)
|
|
float currentSpeed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;
|
|
|
|
// Move the character
|
|
controller.Move(move * currentSpeed * Time.deltaTime);
|
|
|
|
// Jumping
|
|
if (Input.GetButtonDown("Jump") && isGrounded)
|
|
{
|
|
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
|
|
}
|
|
|
|
// Apply gravity
|
|
velocity.y += gravity * Time.deltaTime;
|
|
controller.Move(velocity * Time.deltaTime);
|
|
|
|
// Mouse look
|
|
HandleMouseLook();
|
|
|
|
// Press Escape to unlock cursor
|
|
if (Input.GetKeyDown(KeyCode.Escape))
|
|
{
|
|
Cursor.lockState = CursorLockMode.None;
|
|
Cursor.visible = true;
|
|
}
|
|
|
|
// Click to lock cursor again
|
|
if (Input.GetMouseButtonDown(0) && Cursor.lockState == CursorLockMode.None)
|
|
{
|
|
Cursor.lockState = CursorLockMode.Locked;
|
|
Cursor.visible = false;
|
|
}
|
|
}
|
|
|
|
void HandleMouseLook()
|
|
{
|
|
// Get mouse input
|
|
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
|
|
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
|
|
|
|
// Rotate camera up/down (pitch)
|
|
xRotation -= mouseY;
|
|
xRotation = Mathf.Clamp(xRotation, -maxLookAngle, maxLookAngle);
|
|
playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
|
|
|
|
// Rotate player left/right (yaw)
|
|
transform.Rotate(Vector3.up * mouseX);
|
|
}
|
|
}
|