Forked from KarlRamstedt/FirstPersonCameraRotation.cs
Created
January 17, 2024 15:25
-
-
Save erikfenriz/9f865c3e979562ee9c12e36681cca263 to your computer and use it in GitHub Desktop.
A simple First Person Camera rotation script for Unity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
/// <summary> | |
/// A simple FPP (First Person Perspective) camera rotation script. | |
/// Like those found in most FPS (First Person Shooter) games. | |
/// </summary> | |
public class FirstPersonCameraRotation : MonoBehaviour { | |
public float Sensitivity { | |
get { return sensitivity; } | |
set { sensitivity = value; } | |
} | |
[Range(0.1f, 9f)][SerializeField] float sensitivity = 2f; | |
[Tooltip("Limits vertical camera rotation. Prevents the flipping that happens when rotation goes above 90.")] | |
[Range(0f, 90f)][SerializeField] float yRotationLimit = 88f; | |
Vector2 rotation = Vector2.zero; | |
const string xAxis = "Mouse X"; //Strings in direct code generate garbage, storing and re-using them creates no garbage | |
const string yAxis = "Mouse Y"; | |
void Update(){ | |
rotation.x += Input.GetAxis(xAxis) * sensitivity; | |
rotation.y += Input.GetAxis(yAxis) * sensitivity; | |
rotation.y = Mathf.Clamp(rotation.y, -yRotationLimit, yRotationLimit); | |
var xQuat = Quaternion.AngleAxis(rotation.x, Vector3.up); | |
var yQuat = Quaternion.AngleAxis(rotation.y, Vector3.left); | |
transform.localRotation = xQuat * yQuat; //Quaternions seem to rotate more consistently than EulerAngles. Sensitivity seemed to change slightly at certain degrees using Euler. transform.localEulerAngles = new Vector3(-rotation.y, rotation.x, 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment