Created
September 17, 2021 16:52
-
-
Save SushiWaUmai/bd2c2af507490481acaa847269a0487b to your computer and use it in GitHub Desktop.
Unity Simple First Person Controller
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; | |
public class FirstPersonController : MonoBehaviour | |
{ | |
[SerializeField] private float _speed = 5; | |
[SerializeField] private float _sensitivity = 1; | |
[SerializeField] private float _clampRot = 85; | |
[SerializeField] private bool _lockCursor = true; | |
[SerializeField] private float _cameraSmoothing = 0.25f; | |
[SerializeField] private float _directionSmoothing = 0.25f; | |
private Transform _camTransform; | |
private Vector2 _mouseInput; | |
private Vector2 _currentMouse; | |
private Vector2 _mouseVel; | |
private Vector3 _currentDir; | |
private Vector3 _dirVel; | |
private void OnValidate() | |
{ | |
_camTransform = Camera.main.transform; | |
} | |
private void Start() | |
{ | |
if (_lockCursor) | |
{ | |
Cursor.lockState = CursorLockMode.Locked; | |
Cursor.visible = false; | |
} | |
} | |
private void Update() | |
{ | |
Move(); | |
Rotate(); | |
} | |
private void Move() | |
{ | |
Vector3 dir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")); | |
_currentDir = Vector3.SmoothDamp(_currentDir, dir, ref _dirVel, _directionSmoothing); | |
transform.position += _camTransform.TransformDirection(_currentDir) * _speed * Time.deltaTime; | |
} | |
private void Rotate() | |
{ | |
_mouseInput += new Vector2(Input.GetAxis("Mouse X"), -Input.GetAxis("Mouse Y")) * _sensitivity; | |
_mouseInput.y = Mathf.Clamp(_mouseInput.y, -_clampRot, _clampRot); | |
_currentMouse = Vector2.SmoothDamp(_currentMouse, _mouseInput, ref _mouseVel, _cameraSmoothing); | |
transform.rotation = Quaternion.Euler(0, _currentMouse.x, 0); | |
_camTransform.localRotation = Quaternion.Euler(_currentMouse.y, 0, 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use
Create a Player GameObject and make the Camera the child of the Player.
Add this script to the Player GameObject.