Check if mouse is outside pygame window

user12692182 :

I was running a game in pygame, and I discovered a flaw. The way I coded it, if the mouse went outside of the window, the game started to go around in circles. When you get pygame.mouse.get_pos(), it will return the last value the mouse was detected in the window, but other wise no indication that the mouse has left the window. So, is there any way to check if the mouse has stopped hovering over the pygame window, and has left it?

Stellan :

A simple answer to this would be to use the pygame.mouse.get_focused() function. This returns 0 when the mouse isn't focused on the screen. So if you wanted to check if the mouse was outside the window, you could simply do

mouseFocus = pygame.mouse.get_focused()

During the main loop and have an if statement checking if the mouse has left the screen.

if mouseFocus == 0:
    print("mouse is out of screen.")

Hope this helps

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=10154&siteId=1