From 83ad5e66dedec2717067eeab6a28406dd1b0b754 Mon Sep 17 00:00:00 2001 From: Misa Date: Fri, 16 Apr 2021 22:46:43 -0700 Subject: [PATCH] Show and hide mouse cursor based on user input This is quite simple - whenever the user uses their keyboard or controller, we hide the mouse cursor. Whenever they move the mouse, we show it again. This makes it so the cursor gets out of the way when they play the game, but reappears when they need it. There is also a timeout, to prevent strobing if the user decides to use the keyboard/controller and mouse at the same time. There is no timeout from hiding the mouse cursor, but there is a timeout from showing the mouse cursor - this because it's okay if the mouse lingers for a few frames when you start using the keyboard, but really annoying if the mouse doesn't instantly appear when you move it. --- desktop_version/src/KeyPoll.cpp | 77 +++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/desktop_version/src/KeyPoll.cpp b/desktop_version/src/KeyPoll.cpp index 5d152171..4fee8a73 100644 --- a/desktop_version/src/KeyPoll.cpp +++ b/desktop_version/src/KeyPoll.cpp @@ -81,8 +81,60 @@ void KeyPoll::toggleFullscreen(void) } } +static int changemousestate( + int timeout, + const bool show, + const bool hide +) { + int prev; + int new_; + + if (timeout > 0) + { + return --timeout; + } + + /* If we want to both show and hide at the same time, prioritize showing */ + if (show) + { + new_ = SDL_ENABLE; + } + else if (hide) + { + new_ = SDL_DISABLE; + } + else + { + return timeout; + } + + prev = SDL_ShowCursor(SDL_QUERY); + + if (prev == new_) + { + return timeout; + } + + SDL_ShowCursor(new_); + + switch (new_) + { + case SDL_DISABLE: + timeout = 0; + break; + case SDL_ENABLE: + timeout = 30; + break; + } + + return timeout; +} + void KeyPoll::Poll(void) { + static int mousetoggletimeout = 0; + bool showmouse = false; + bool hidemouse = false; bool altpressed = false; bool fullscreenkeybind = false; SDL_Event evt; @@ -324,8 +376,33 @@ void KeyPoll::Poll(void) VVV_exit(0); break; } + + switch (evt.type) + { + case SDL_KEYDOWN: + if (evt.key.repeat == 0) + { + hidemouse = true; + } + break; + case SDL_TEXTINPUT: + case SDL_CONTROLLERBUTTONDOWN: + case SDL_CONTROLLERAXISMOTION: + hidemouse = true; + break; + case SDL_MOUSEMOTION: + case SDL_MOUSEBUTTONDOWN: + showmouse = true; + break; + } } + mousetoggletimeout = changemousestate( + mousetoggletimeout, + showmouse, + hidemouse + ); + if (fullscreenkeybind) { toggleFullscreen();