Talstra

Talstra

Shifting Focus...

Array

Unity

Camera Controller – First Person

Estimated reading: 2 minutes 87 views Contributors

To create a camera controller, you would write a script that captures mouse movement and applies it to rotate the camera around the player.

CameraController.cs

using UnityEngine;

// This script will make the camera follow the player and allow the player to rotate the camera around by moving the mouse.
public class CameraController : MonoBehaviour
{
    public Transform player; // Player's transform
    public float mouseSensitivity = 2f; // Sensitivity of mouse movement
    private float cameraVerticalRotation = 0f; // Stores the vertical rotation of the camera

    void Start()
    {
        // Lock the cursor to the center of the screen and make it invisible
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {
        // Collect Mouse Input
        float inputX = Input.GetAxis("Mouse X") * mouseSensitivity;
        float inputY = Input.GetAxis("Mouse Y") * mouseSensitivity;

        // Rotate the Camera around its local X axis (up and down movement)
        cameraVerticalRotation -= inputY;
        // Clamp the vertical rotation to prevent flipping the camera over
        cameraVerticalRotation = Mathf.Clamp(cameraVerticalRotation, -90f, 90f);
        // Apply the rotation to the camera's local Euler angles in the X axis
        transform.localEulerAngles = new Vector3(cameraVerticalRotation, transform.localEulerAngles.y, 0f);

        // Rotate the Player Object and the Camera around its Y axis (left and right movement)
        // We rotate the player instead of the camera to avoid issues with the player's orientation
        player.Rotate(Vector3.up * inputX);
    }
}

How to Use:

  1. Create a new C# script in Unity and name it CameraController.
  2. Drag the script onto your camera GameObject in the Unity Editor.
  3. Assign the player’s transform to the player variable in the script component.
  4. Adjust the mouseSensitivity if necessary to get the desired responsiveness.

When you enter Play mode, you should be able to move the mouse to rotate the camera up and down, as well as rotate the player left and right, creating a third-person camera experience that follows the player’s orientation.

Remember to experiment with different values for mouse sensitivity and the clamp range to find what feels best for your particular game.

Share this Doc

Camera Controller – First Person

Or copy link

CONTENTS
Chat Icon Close Icon