Friday, 2 May 2025

[SFML & C++] 4 - Mouse Tracker // Tutorial

This is part of a series of small projects and tutorials using C++ and SFML

Library version: SFML 3.0.0
C++ Standard: ISO C++20

In this project, we'll make a simple app that tracks the mouse movement on the screen and prints the X and Y coordinates. Here's what the finished product will look like:

How To SFML Mouse Tracking (Checking inside window) Tutorial using C++ - Basic Beginner


Step 1 - Displaying Text

So first, we need to display some text to the screen. We can do that using SF::Text.

In SFML, you need to create a font as well that you can pass to the text object, otherwise you won't be able to display anything. So let's do that as well:




Step 2 - Getting The Mouse Coordinates

Next we need to get the mouse coordinates. This is something we can do in our update section.


If you run the program now, the coordinates will update depending on where the mouse is, relative to the top left-hand corner of the window.

Your mouse can go outside of the window though and it will still report where it is on the screen. Depending on the type of app you're building, you may want to allow the mouse to go outside the screen, or you may want the window to have full focus of the mouse.

As I'm a games developer, usually the mouse should stay inside the window, so I'm going to do that.



Here I used a function on the main window itself to "lock" the mouse inside the window, whilst the window has focus. I find this to be quite annoying as I like to use most things in windowed mode, but to each their own. Grabbing the mouse may cause some issues if you have a 3D camera as the mouse may need to "go outside" the window in order to rotate the camera properly.

In the update section, I modified the code slightly to check if the window has focus, so we only display the coordinates when it does. 

Another slightly different way to do this is use some events:



Here I created a bool to track if the mouse was in the window. I then used the events sent by the library to set that bool and used that instead of checking if the window has focus. This is an approach I prefer, however it really depends on the application. Sometimes you really don't want the mouse leaving the window.

You can read more about these classes here:

No comments:

Post a Comment