- Home /
Camera gets stuck when cursor is locked
Hello there. This is my first time posting here and I'm hoping it'd be worth it. I'm trying to make a FPS character. I've got an empty gameObject as Player with a Capsule and a Camera as its children. This is the code I've written for the character to look around and assigned it to Player gameObject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class MouseLook : MonoBehaviour {
public float mouseSensitivity = 50f;
Transform cam;
Vector2 mouseMovement;
float mouseX;
float mouseY;
float xRotation = 0f;
void Start()
{
cam = gameObject.transform.Find("Camera");
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
mouseX = mouseMovement.x * mouseSensitivity * Time.deltaTime;
mouseY = mouseMovement.y * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.Rotate(Vector3.up * mouseX);
cam.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
void OnLook(InputValue mouseValue)
{
mouseMovement = mouseValue.Get<Vector2>();
}
}
The problem started when I decided to lock the cursor. Before that it worked just fine expect the character could look around just as far as cursor could go. I couldn't rotate past when the cursor hit the edge of screen. So I decided to lock the cursor by using Cursor.lockState = CursorLockMode.Locked; After this tweak whenever I press the Play button the cursor doesn't get automatically locked, I have to click somewhere inside the Game view for the cursor to get locked. But when I do this and try to move the mouse the character starts looking towards any random position and gets stuck there. Mostly it's looking down. Moving the mouse or clicking doesn't work. Only when I press escape the cursor gets unlocked then I stop the game.
I'm using Unity 2020.3.3f1 on Ubuntu. I'm having this issue since 2020.3.1f1. Please let me know if there's anything wrong with the code or is there another way to solve the issue. All help is greatly appreciated.
It seems to be a problem with entering the game view from the editor. If you build, is there still an issue?
I just built and ran and it's working totally fine. Thank you for the suggestion. I can work with this as long as the built game is okay. Have a nice day/evening :)