Ethan Harris-Austin
Ethan Harris-Austin

Reputation: 63

Changing cursor.LockMode to Locked makes Input.GetAxis("Mouse X") become a really large number

In my game I have a character that rotates with the mouse. To prevent the user from clicking outside of the game's window, I have locked the cursor to the center of the screen for when they're in gameplay. When the user pauses the game, the mouse unlocks so that they can interact with the pause menu buttons. When they resume, the mouse locks back into the centre of the screen, however this gives the "Mouse X" axis a huge number which makes the character "jump" to a new rotation which I don't want to happen.

Here's the basic code:

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

public class FirstPersonController : MonoBehaviour
{
    bool gamePaused = false;

    void Start() {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update() {
        if (!gamePaused)
            CharacterRotation();
    }

    void CharacterRotation() {
         transform.Rotate(0, Input.GetAxis("Mouse X") * 10, 0);
    }

    public void Pause() {
        gamePaused = true;
        Cursor.lockState = CursorLockMode.None;
    }
    public void Resume() {
        gamePaused = false;
        Cursor.lockState = CursorLockMode.Locked;
    }
}

Any ideas on how to prevent this? Any help would be greatly appreciated :)

Upvotes: 1

Views: 849

Answers (1)

Taksah
Taksah

Reputation: 221

Input.GetAxis("Mouse X") //returns the mouse delta!

It happens because the cursor moves (for example) from the edge of the screen to the center which gives huge numbers (screenCenter - screenEdge => huge delta). To prevent it:

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

public class FirstPersonController : MonoBehaviour
{
    bool gamePaused = false;
    bool afterPause = false;

    void Start() {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update() {
        if (!gamePaused)
            CharacterRotation();
    }

    void CharacterRotation() {
        if(afterPause)
        {
            afterPause = false;
            return;
        }
         transform.Rotate(0, Input.GetAxis("Mouse X") * 10, 0);
    }

    public void Pause() {
        gamePaused = true;
        Cursor.lockState = CursorLockMode.None;
    }
    public void Resume() {
        gamePaused = false;
        afterPause = true;
        Cursor.lockState = CursorLockMode.Locked;
    }
}

Upvotes: 1

Related Questions