I got this code for first person camera but it will only look up and down. I cannot look left or right with it nor will my character move with where the camera goes and I’m not too sure how I should go about fixing this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FirstPersonCamera : MonoBehaviour
{
public float minX = -60f;
public float maxX = 60f;
public float sensitivity;
public Camera cam;
float rotY = 0f;
float rotX = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
rotY += Input.GetAxis("Mouse X") * sensitivity;
rotX += Input.GetAxis("Mouse Y") * sensitivity;
rotX = Mathf.Clamp(rotX, minX, maxX);
transform.localEulerAngles = new Vector3(0, rotY, 0);
cam.transform.localEulerAngles = new Vector3(-rotX, 0, 0);
if (Input.GetKeyDown(KeyCode.Escape))
{
//Mistake happened here vvvv
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
if (Cursor.visible && Input.GetMouseButtonDown(1))
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
}
The code itself looks ok I think - the question is which object is it attached to and how is your hierarchy set up? Please share your object hierarchy, and clearly show which object the script is attached to and the script inspector to show which objects are assigned in it?
If that’s your hierarchy (Camera at root), then line 29 and 30 are the same transform, hence only one of those lines will win, the second one… the one that looks up / down.
Hey, look at that… that’s the exact problem you reported!
If I had to guess, the above script is supposed to be on the character, and the Camera is supposed to be a child, which is not the case in your hierarchy above.
PS. If you would prefer something more full-featured here is a super-basic starter prototype FPS based on Character Controller (BasicFPCC):
That one has run, walk, jump, slide, crouch… it’s crazy-nutty!!