Search Unity

Input.mousePosition doesn't update offscreen?

Discussion in 'Scripting' started by crandellbr, Aug 1, 2019.

  1. crandellbr

    crandellbr

    Joined:
    Apr 3, 2013
    Posts:
    130
    Hello. I'm trying to detect when the mouse leaves the game window so I can hide the in-game cursor. The problem is that Input.mousePosition doesn't appear to update while offscreen, as tested with the simple script below. The game window still has focus, so the game isn't paused.

    Code (CSharp):
    1. public class CoordsDisplay : MonoBehaviour
    2. {
    3.     public UILabel label;
    4.  
    5.     private void Update()
    6.     {
    7.         label.text = Input.mousePosition.x + ", " + Input.mousePosition.y;
    8.     }
    9. }
    This is for an old project I'm returning to and wrapping up, so I'm working in ancient 5.3. Maybe this was fixed in a more recent version? Are there any workarounds?
     
  2. doctorpangloss

    doctorpangloss

    Joined:
    Feb 20, 2013
    Posts:
    270
    Don't overthink it. Just don't render the mouse cursor if the mouse position is right at a screen edge.
     
  3. crandellbr

    crandellbr

    Joined:
    Apr 3, 2013
    Posts:
    130
    Depending on how fast the player is moving the mouse, it can jump many pixels in the frame it leaves the window. Even moving casually to the left, I was routinely seeing mousePosition.x stuck at 16, and it can easily go several times higher. I'm afraid this is not a reliable solution.
     
  4. PanicEnsues

    PanicEnsues

    Joined:
    Jul 17, 2014
    Posts:
    187
    This would require adding a full-screen GUI item, but then you could use OnMouseExit/OnMouseEnter. Docs make it look like it should work in 5.3.

    If that
     
  5. crandellbr

    crandellbr

    Joined:
    Apr 3, 2013
    Posts:
    130
    I didn't have a chance to test until now. The only way I could see any results was by hooking into the OnPointerEnter and OnPointerExit callbacks. OnMouseEnter and OnMouseExit just wouldn't register with a Canvas Image, even with an attached collider. Unfortunately, OnPointerExit doesn't work on a fullscreen element when leaving the window.

    I was still using NGUI for this project. I learned uGUI afterward but never had occasion to use OnMouse events. It would be nice if I could get that to work, but mixing UI systems just for this would be messy anyway. Thanks, it was worth a shot.