Home > Blockchain >  Unity 3D first person movement
Unity 3D first person movement

Time:12-23

I'm following brackeys 1st person movement tutorial. but I can't get the camera working. I followed the tutorial correctly, But this code isn't working. gives no errors but it doesn't work. here's the 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;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

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

This code gives no errors but doesn't work. how can i fix this?

CodePudding user response:

The code you've attached is correct.

I recommend you follow the tutorial once more and pay close attention to where this script should be attached.

Having checked the tutorial myself right now I got it to work by parenting camera as a child of player, attaching MouseLook.cs to Camera game object, and setting player game object as a Player Body variable in MouseLook.cs.I recommend making sure that mouseSensitivity variable is set to 100. Next, if that won't solve your issue, it could mean a number of things.

First, your project can have Axis "Mouse X" and "Mouse Y" unset, meaning that it does not record the movement of your mouse when you move it.

Second, player or camera rotation can be overridden by some other behavior that might cause MouseLook rotation to be ignored.

  • Related