Search Unity

Switching to CursorLockMode.Locked causes MouseLook to jump (with solution)

Discussion in 'UGUI & TextMesh Pro' started by chilton, May 23, 2017.

  1. chilton

    chilton

    Joined:
    May 6, 2008
    Posts:
    564
    I had a problem, couldn't find a good answer in the forums, so I created this one. It might help someone else so I thought I'd post it.

    I have a game where the user regularly has to switch from using the FPS controller to UI elements.

    To do so, I modified MouseLook.cs to check if (Cursor.visible==true) and return in the LookRotation function.

    However, every time after the cursor is locked after doing this, since it centers it, the lookRotation function registers a massive jump, which can be jarring to the user. To further complicate things, that jump happens *after* the cursor is locked, which for some reason returns a zero delta for both x and y.

    To get around this and fix the UI jump, I added a class variable bool 'wasLocked' and changed the LookRotation so it starts with this...

    Code (CSharp):
    1.         public void LookRotation(Transform character, Transform camera)
    2.         {
    3.             if (Cursor.visible==true) {
    4.                 wasLocked = false;
    5.                 return;
    6.             }
    7.          
    8.             float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity;
    9.             float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity;
    10.  
    11.  
    12.             if (wasLocked==false) {
    13.                 if (xRot==0) return; // the first few times through here, a zero rotation is returned.
    14.                 if (yRot==0) return; // So we just ignore it if that happens.
    15.                 wasLocked = true;
    16.                 return;
    17.             }
    18.  
    ... this eliminates the jarring jump, and doesn't affect gameplay otherwise. I can set the cursor elsewhere like this...

    Code (CSharp):
    1.         Cursor.visible = false;
    2.         Cursor.lockState = CursorLockMode.Locked;
    3.  
    ... and all is well :)


    -Chilton