First Person Camera in Unity

Sdílet
Vložit
  • čas přidán 29. 07. 2024
  • In this short video we will learn how to make a First Person Camera inside Unity. It is a very simple but effective Camera Script. It rotates the Camera around its local X-axis. On the Y-axis we gonna Rotate the Camera and the Player together so the player faces the direction the Camera is facing. If you have any questions or get some trouble making FPS camera feel free to ask in the comments section below.
    For you lazy folks here is the script ^.^ :
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class FirstPersonCamera : MonoBehaviour
    {
    // Variables
    public Transform player;
    public float mouseSensitivity = 2f;
    float cameraVerticalRotation = 0f;
    bool lockedCursor = true;
    void Start()
    {
    // Lock and Hide the Cursor
    Cursor.visible = false;
    Cursor.lockState = CursorLockMode.Locked;
    }
    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
    cameraVerticalRotation -= inputY;
    cameraVerticalRotation = Mathf.Clamp(cameraVerticalRotation, -90f, 90f);
    transform.localEulerAngles = Vector3.right * cameraVerticalRotation;
    // Rotate the Player Object and the Camera around its Y axis
    player.Rotate(Vector3.up * inputX);
    }
    }
    NOTE: For this script to work you need to have the same name of the script in the Unity editor. This script goes to the Main Camera that is a child of the Player Object. And you reference the Player Object at the player Transform slot inside the Unity Editor.
    #FirstPersonCameraUnity #FPS #CameraUnity

Komentáře • 76