Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Simple FPS Camera

Discussion in 'Made With Unity' started by Rachan, Jun 14, 2024.

  1. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    806
    Hi there!

    Today I just want to share my Simple FPS Camera
    to anyone who want to movement to looking something.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class FPSCamera : MonoBehaviour
    6. {
    7.     [Range(0.1f, 100)] [SerializeField] float Speed = 20f;
    8.     [Range(0.1f, 9f)] [SerializeField] float Sensitivity = 2f;
    9.     [Range(0f, 90f)] [SerializeField] float UpLimit = 90f;
    10.  
    11.     private Vector2 rotation = Vector2.zero;
    12.     const string xAxis = "Mouse X";
    13.     const string yAxis = "Mouse Y";
    14.  
    15.     void Update()
    16.     {
    17.         // Lock cursor at center of screen
    18.         Cursor.lockState = CursorLockMode.Locked;
    19.  
    20.         // looking roation by mouse
    21.         rotation.x += Input.GetAxis(xAxis) * Sensitivity;
    22.         rotation.y += Input.GetAxis(yAxis) * Sensitivity;
    23.         rotation.y = Mathf.Clamp(rotation.y, -UpLimit, UpLimit);
    24.         var xQuat = Quaternion.AngleAxis(rotation.x, Vector3.up);
    25.         var yQuat = Quaternion.AngleAxis(rotation.y, Vector3.left);
    26.         transform.localRotation = xQuat * yQuat;
    27.  
    28.         // movement by W A S D
    29.         Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    30.         this.transform.position += this.transform.forward * movement.z * movement.magnitude * Time.deltaTime * Speed;
    31.         this.transform.position += this.transform.right * movement.x * movement.magnitude * Time.deltaTime * Speed;
    32.     }
    33. }
    34.  
    I hope it will be useful for you!