How to create first person camera script in unity

 This example script allow us to control movement and rotation of camera in first person perspective. Example code is given below:

Code :
using UnityEngine;

public class FirstPersonCamera : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float mouseSensitivity = 2f;

    private float rotationX;
    private float rotationY;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        // move our camera forward, backward, left and right
        float moveX = Input.GetAxis("Horizontal");
        float moveZ = Input.GetAxis("Vertical");
        transform.position += new Vector3(moveX, 0f, moveZ) * moveSpeed * Time.deltaTime;

        // rotate our camera
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;

        rotationX -= mouseY;
        rotationX = Mathf.Clamp(rotationX, -90f, 90f);

        rotationY += mouseX;

        transform.localRotation = Quaternion.Euler(rotationX, rotationY, 0f);
    }
}

"moveSpeed" is a public variable which control movement speed of our camera and "mouseSensitivity" variable control sensitivity of mouse look.

"rotationX" and "rotationY" are private variables which are used for storing current rotation of camera.

"Start()" function will lock our cursor so player is unable to move it outside of game window.

"Update()" function will use Input.GetAxis("Horizontal") and Input.GetAxis("Vertical") method for getting input for movement of camera so we can move our camera left, right, forward, and backward by horizontal and vertical keys like WASD or arrow.

Input.GetAxis("Mouse X") and Input.GetAxis("Mouse Y") for getting input for rotation of camera.

We used "Mathf.Clamp()" function in this script for limiting rotationX between a certain range so this will prevent our camera from rotating upside down.

We used Time.deltaTime to multiply movement so this will make camera movement smooth regardless of frame rate.

first person camera controller in unity


Add this script to Main Camera in your scene for enabling simple first-person camera movement. You can tweak moveSpeed and mouseSensitivity variables as per your requirement.


Comments