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
My Base Project: https://github.com/l-paz91/SFMLProjects/blob/main/main.cpp
In this project, we'll make a simple app that includes the basics of a button class that handles, hover, pressed and released events. Here's what the finished product will look like:
Step 1 - Creating a rectangle button
To start off, we'll stick this in a separate header file instead of doing it in main. So create a new header file. Right click on the header file folder, add -> new item -> choose a .h file.
In the same way, create a matching cpp file.
In the header file we'll create the definition of the class (don't forget the includes for types):
Then we'll create the function implementations in the cpp file:
Now over in main, we'll create an instance of the button (include the button header):
If you run this code, you should see just a white rectangle on the screen. Very exciting.
Step 2 - Add Hover Event
In this next few steps we'll add 3 new functions, on hover, on pressed and on released. Knowing if you're hovering can be useful if you want to change the colour of the button so it's obvious that you're in the collision rect. On pressed is useful for situations where you might want a press and hold mechanic and released is useful for a one-time event, often used for "doing something" when someone clicks a button.
I'm going to start off with hovering. First we need to know if the mouse is within the bounds of the rectangle. I'll add a simple function to the header file to check for that as well as a bool to track to the state and an event function:
I also added a new argument parameter to update so we can get the mouse positions relative to our window (the global positions are relative to the desktop screen).
Over in main, we'll now just call the button update function in the update section:
Now when you build, whenever you hover over the button, it should turn green. Then back to white. You might want to store the hover colour as its own variable...
Step 3 - Add On Pressed Event
Now we'll tackle the on pressed. This is very similar to the hover code. Instead of checking in the update function though, we'll need to poll our events to see if the left mouse button has been pressed whilst hovering over the button. In the header let's add another event function and a state:
Then in the cpp we check for button presses and if we're hovering, if so call onPressed():
Now when you run the program, it should turn green when hovering and red when pressed. But it doesn't turn back to green again, that's because onRelease() hasn't been implemented so it doesn't know what to do.
Let's do that.
Step 4 - Add On Release Function
Let's add another function:
And give it a definition:
Now we just need to handle the button release event:
And that's it. We created a basic button class.
No comments:
Post a Comment