i need help with my code again

I got an error message that says “Cannot implicitly convert type ‘UnityEngine.Quaternion’ to ‘UnityEngine.Transform’”. Here is my code

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()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;

        Transform localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        playerBody.Rotate(Vector3.up * mouseX);
    }
}

Well, three things. First of all this line:

is the line that causes the error. You declared a local variabled calle “localRotation” of type Transform and then you try to assign a Quaternion to it. Of course that doesn’t make much sense. You probably wanted to do this:

transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

The second thing is you should place this line:

xRotation = Mathf.Clamp(xRotation, -90f, 90f);

before the line we just fixed. It makes no sense to clamp the rotation after you assigned it as this would introduce a one frame delay and can cause jitter at the limits.

Finally you have to remove the Time.deltaTime from your mouseX and mouseY lines. Input.GetAxis("Mouse X") returns already a delta value. Multiplying by deltaTime would reintroduce frame dependency and does the opposite of what you want to do.

2 Likes