X axis buggy in mouse look script, but y axis fine?

Viewed 301

In Unity I used this little script to move the mouse around like in an FPS, but looking from side to side is extremely buggy and it will only move a bit in either direction before defaulting to looking straight forward. Looking up and down works perfectly, and I have a clamping script to only look up 90 degrees or down 90 degrees. For some reason, before adding in the code for looking up and down, it worked perfectly, but the two together makes it all buggy. Any help?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class MouseLook : MonoBehaviour
{
    public float mouseSpeed = 100f;


    public Transform playerBody;


    float xRotation = 0f;
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSpeed * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSpeed * Time.deltaTime;


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

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }
}
2 Answers

you may have to experiment but this line looks like it doesnt belong

xRotation -= mouseY;

This is a problem i get too when i first make fps fames and i think i fix it by adding the code to FixedUpdate(). Alternativelly you can try and switching the playerBody.Rotate() with the transform.localRotation

Related