Skip to content

Instantly share code, notes, and snippets.

@abdelfattahradwan
Created July 6, 2021 04:13
Show Gist options
  • Save abdelfattahradwan/add665019fdfd8ac5c71503cc6f5bb82 to your computer and use it in GitHub Desktop.
Save abdelfattahradwan/add665019fdfd8ac5c71503cc6f5bb82 to your computer and use it in GitHub Desktop.
Simple FPS Character Controller for Unity
using UnityEngine;
public sealed class SimpleCharacterController : MonoBehaviour
{
[SerializeField] private float speed;
[SerializeField] private float jumpSpeed;
private Vector3 _velocity;
[SerializeField] private CharacterController characterController;
[SerializeField] private float xSensitivity;
[SerializeField] private float ySensitivity;
[SerializeField] private float xMin;
[SerializeField] private float xMax;
[SerializeField] private Transform fpsCamera;
private Vector3 _fpsCameraEulerAngles;
private bool _isFrozen;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
_isFrozen = !_isFrozen;
Cursor.visible = _isFrozen;
Cursor.lockState = _isFrozen ? CursorLockMode.None : CursorLockMode.Locked;
}
Move();
LookAround();
}
private void Move()
{
var x = Input.GetAxis("Horizontal");
var z = Input.GetAxis("Vertical");
var desiredVelocity = ((transform.right * x) + (transform.forward * z)) * (_isFrozen ? 0.0f : speed);
desiredVelocity = Vector3.ClampMagnitude(desiredVelocity, speed);
_velocity.x = desiredVelocity.x;
_velocity.z = desiredVelocity.z;
if (characterController.isGrounded)
{
_velocity.y = 0.0f;
if (!_isFrozen && Input.GetKey(KeyCode.Space))
{
_velocity.y = jumpSpeed;
}
}
else
{
_velocity.y += Physics.gravity.y * Time.deltaTime;
}
characterController.Move(_velocity * Time.deltaTime);
}
private void LookAround()
{
var multiplier = _isFrozen ? 0.0f : 1.0f;
var x = Input.GetAxis("Mouse X") * multiplier;
var y = Input.GetAxis("Mouse Y") * multiplier;
_fpsCameraEulerAngles.x = Mathf.Clamp(_fpsCameraEulerAngles.x - y * ySensitivity, xMin, xMax);
transform.Rotate(0.0f, x * xSensitivity, 0.0f);
fpsCamera.localEulerAngles = _fpsCameraEulerAngles;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment