From 9c3da7a3e32a9de618e45e8ac53c14e749b24c07 Mon Sep 17 00:00:00 2001 From: Ben Wiederhake Date: Wed, 8 Sep 2021 22:50:22 +0200 Subject: Pong: Switch to global tracking When I play Pong, I don't really pay attention to whether my mouse is in the Pong window. That means that sometimes, annoyingly, the window loses my mouse, and I lose control of the paddle. Gasp! D: This commit teaches Pong the wonders of global mouse tracking, thus enabling the player to focus solely on the game. --- Userland/Games/Pong/Game.cpp | 5 +++-- Userland/Games/Pong/Game.h | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) (limited to 'Userland') diff --git a/Userland/Games/Pong/Game.cpp b/Userland/Games/Pong/Game.cpp index e11ff38778..53aad289cb 100644 --- a/Userland/Games/Pong/Game.cpp +++ b/Userland/Games/Pong/Game.cpp @@ -108,7 +108,7 @@ void Game::keydown_event(GUI::KeyEvent& event) } } -void Game::mousemove_event(GUI::MouseEvent& event) +void Game::track_mouse_move(Gfx::IntPoint const& point) { if (m_up_key_held || m_down_key_held) { // We're using the keyboard to move the paddle, the cursor is doing something else @@ -118,7 +118,8 @@ void Game::mousemove_event(GUI::MouseEvent& event) if (m_cursor_paddle_target_y.has_value()) update(cursor_paddle_target_rect()); - m_cursor_paddle_target_y = clamp(event.y() - m_player1_paddle.rect.height() / 2, 0.f, game_height - m_player1_paddle.rect.height()); + auto relative_point = point - window()->position(); + m_cursor_paddle_target_y = clamp(relative_point.y() - m_player1_paddle.rect.height() / 2, 0.f, game_height - m_player1_paddle.rect.height()); if (m_player1_paddle.rect.y() > *m_cursor_paddle_target_y) { m_player1_paddle.moving_up = true; m_player1_paddle.moving_down = false; diff --git a/Userland/Games/Pong/Game.h b/Userland/Games/Pong/Game.h index 8a464a1f1c..4ff0a4e535 100644 --- a/Userland/Games/Pong/Game.h +++ b/Userland/Games/Pong/Game.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -17,7 +18,8 @@ namespace Pong { -class Game final : public GUI::Widget { +class Game final : public GUI::Widget + , GUI::MouseTracker { C_OBJECT(Game); public: @@ -32,8 +34,8 @@ private: virtual void paint_event(GUI::PaintEvent&) override; virtual void keyup_event(GUI::KeyEvent&) override; virtual void keydown_event(GUI::KeyEvent&) override; - virtual void mousemove_event(GUI::MouseEvent&) override; virtual void timer_event(Core::TimerEvent&) override; + virtual void track_mouse_move(Gfx::IntPoint const&) override; void reset(); void reset_ball(int serve_to_player); -- cgit v1.2.3