94 lines
2.3 KiB
C#
94 lines
2.3 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class FreeCamera : MonoBehaviour
|
|
{
|
|
[Header("Movement")]
|
|
[SerializeField] private float moveSpeed = 8f;
|
|
[SerializeField] private float fastMoveMultiplier = 3f;
|
|
|
|
[Header("Look")]
|
|
[SerializeField] private float lookSensitivity = 2f;
|
|
[SerializeField] private float minPitch = -89f;
|
|
[SerializeField] private float maxPitch = 89f;
|
|
|
|
private float pitch;
|
|
|
|
private void Start()
|
|
{
|
|
pitch = NormalizeAngle(transform.localEulerAngles.x);
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
HandleCursor();
|
|
HandleLook();
|
|
HandleMovement();
|
|
}
|
|
|
|
private void HandleCursor()
|
|
{
|
|
if (Input.GetKeyDown(KeyCode.Escape))
|
|
{
|
|
Cursor.lockState = CursorLockMode.None;
|
|
Cursor.visible = true;
|
|
}
|
|
else if (Input.GetMouseButtonDown(1))
|
|
{
|
|
Cursor.lockState = CursorLockMode.Locked;
|
|
Cursor.visible = false;
|
|
}
|
|
}
|
|
|
|
private void HandleLook()
|
|
{
|
|
if (!Input.GetMouseButton(1))
|
|
{
|
|
return;
|
|
}
|
|
|
|
float yaw = Input.GetAxis("Mouse X") * lookSensitivity;
|
|
float pitchDelta = Input.GetAxis("Mouse Y") * lookSensitivity;
|
|
|
|
pitch = Mathf.Clamp(pitch - pitchDelta, minPitch, maxPitch);
|
|
transform.localRotation = Quaternion.Euler(pitch, transform.localEulerAngles.y + yaw, 0f);
|
|
}
|
|
|
|
private void HandleMovement()
|
|
{
|
|
float speed = moveSpeed;
|
|
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
|
|
{
|
|
speed *= fastMoveMultiplier;
|
|
}
|
|
|
|
float horizontal = Input.GetAxisRaw("Horizontal");
|
|
float vertical = Input.GetAxisRaw("Vertical");
|
|
float elevation = 0f;
|
|
|
|
if (Input.GetKey(KeyCode.E))
|
|
{
|
|
elevation += 1f;
|
|
}
|
|
|
|
if (Input.GetKey(KeyCode.Q))
|
|
{
|
|
elevation -= 1f;
|
|
}
|
|
|
|
Vector3 direction = new Vector3(horizontal, elevation, vertical).normalized;
|
|
transform.position += transform.TransformDirection(direction) * speed * Time.deltaTime;
|
|
}
|
|
|
|
private static float NormalizeAngle(float angle)
|
|
{
|
|
if (angle > 180f)
|
|
{
|
|
angle -= 360f;
|
|
}
|
|
|
|
return angle;
|
|
}
|
|
}
|