Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- [RequireComponent(typeof(CharacterController))]
- public class FPSCamera : MonoBehaviour
- {
- [Header("Movement")]
- public float moveSpeed = 5f;
- public float sprintSpeed = 8f;
- public float gravity = -9.81f;
- [Header("Mouse Look")]
- public float mouseSensitivity = 200f;
- public Transform cameraHolder;
- public float lookSmooth = 10f;
- [Header("Camera Effects")]
- public float headBobAmount = 0.05f;
- public float headBobSpeed = 10f;
- public float swayAmount = 2f;
- public float normalFOV = 60f;
- public float sprintFOV = 70f;
- public float fovSmooth = 8f;
- CharacterController controller;
- Camera cam;
- float xRotation;
- float headBobTimer;
- Vector3 velocity;
- void Start()
- {
- controller = GetComponent<CharacterController>();
- cam = cameraHolder.GetComponentInChildren<Camera>();
- Cursor.lockState = CursorLockMode.Locked;
- }
- void Update()
- {
- HandleMouseLook();
- HandleMovement();
- HandleCameraEffects();
- }
- void HandleMouseLook()
- {
- float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
- float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
- xRotation -= mouseY;
- xRotation = Mathf.Clamp(xRotation, -80f, 80f);
- cameraHolder.localRotation = Quaternion.Lerp(
- cameraHolder.localRotation,
- Quaternion.Euler(xRotation, 0f, 0f),
- lookSmooth * Time.deltaTime
- );
- transform.Rotate(Vector3.up * mouseX);
- }
- void HandleMovement()
- {
- float speed = Input.GetKey(KeyCode.LeftShift) ? sprintSpeed : moveSpeed;
- float x = Input.GetAxis("Horizontal");
- float z = Input.GetAxis("Vertical");
- Vector3 move = transform.right * x + transform.forward * z;
- controller.Move(move * speed * Time.deltaTime);
- if (controller.isGrounded && velocity.y < 0)
- velocity.y = -2f;
- velocity.y += gravity * Time.deltaTime;
- controller.Move(velocity * Time.deltaTime);
- }
- void HandleCameraEffects()
- {
- // Head bob
- if (controller.velocity.magnitude > 0.1f && controller.isGrounded)
- {
- headBobTimer += Time.deltaTime * headBobSpeed;
- float bob = Mathf.Sin(headBobTimer) * headBobAmount;
- cameraHolder.localPosition = Vector3.Lerp(
- cameraHolder.localPosition,
- new Vector3(0, bob, 0),
- Time.deltaTime * lookSmooth
- );
- }
- // Camera sway
- float swayX = -Input.GetAxis("Mouse X") * swayAmount;
- float swayY = -Input.GetAxis("Mouse Y") * swayAmount;
- Quaternion swayRotation = Quaternion.Euler(swayY, swayX, 0);
- cameraHolder.localRotation *= swayRotation;
- // FOV kick
- float targetFOV = Input.GetKey(KeyCode.LeftShift) ? sprintFOV : normalFOV;
- cam.fieldOfView = Mathf.Lerp(
- cam.fieldOfView,
- targetFOV,
- Time.deltaTime * fovSmooth
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment