Is there a way to detect when the mouse leaves the game area (for example, going to another monitor, or even to another app in a windowed game)?
I was puzzled by a raycast that indicated my pointer was over a full-screen map whenever the mouse would go off-screen. I can’t imagine why Unity would have changed this, but apparently now the mouse position is constrained to the “screen” size (actually, window size), so it appears to be impossible to accurately detect when the mouse goes off-screen.
I found the suggestion below which attempts to calculate how far off-screen the mouse has moved based on GetInput reporting mouse position changes, but it isn’t reliable. The errors accumulate pretty quickly and the calculated position ends up being very unreliable.
By the way, since I don’t need to detect position at the very edges I thought I’d “sacrifice” the one pixel boundary around the edges and just check if the mouse was reported as being at the edge – but this fails in the resized in-editor Game window. For example, I have my Game window forced to 1920x1080, then scaled … Screen.height is still reported as 1080 even though the display area in the Game window is actually about 730 pixels. And even more illogically, the mouse position isn’t constrained the real Game window size, it’s constrained to the target (1080).
Pretty screwed up overall.
// exit if mouse is outside screen area
if (Input.mousePosition.x == 0 || Input.mousePosition.y == 0 || Input.mousePosition.x == Screen.width - 1 || Input.mousePosition.y == Screen.height - 1) return;
The GetMainGameViewSize always returns the game’s resolution, right? So if you scale the game view up or down the value will never change. The same for the Screen.width and height. The only thing that changes when I scale the game view is the Input.mousePosition. How can I check if the mouse is on the screen or not regardless of the scale?