Question by
Awsomer3 · Jan 21, 2021 at 10:09 PM ·
c#cameracamera-movement
Can't figure out why cursor won't lock, from Brakeys FPS Turtorial https://www.youtube.com/watch?v=_QajrabyTJc
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
// Should work but isn't
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
,
Comment
Answer by undevable · Jan 25, 2021 at 04:18 PM
@Awsomer3 I followed this tutorial just a couple of days ago, and it worked. See if the script is enabled and attached to the GameObject. If so, then try copy-pasting my code EXACTLY how it is, because mine works (note: my code is a little different, since I went further in the video).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
// Finding the mouse position and adding the mouse speed (mouseSensitivity)
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
// Basically here, we're finding the mouse's distance in y, and rotating it by that for the y to move up and down
xRotation -= mouseY;
// Clamp prevents over rotating. So here, we're preventing over rotating from -90 degrees to 90 degrees
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
// localRotation is rotation relative to its parent. Euler simply rotates the object
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
// This is rotating for x so we can move left and right
playerBody.Rotate(Vector3.up * mouseX);
}
}
I don't really see anything wrong with your code though... Hope my code helps. Comment for any questions.