Context: In following the "SFML game development book" (Moreira, Hansson, Haller) chapter 4 and 6 cover input handling and game menu's respectively. The menu's in the example code are all keyboard based while I'd like to apply mouse based input for a project I am currently working on. A button class is used to pair a sf::Sprite and sf::Text and ultimately inherits from sf::transformable so you only need to make one call of setPosition on the wrapper class in order to move/align both the text and button sprite.
Problem: I am unsure on the
proper way of checking collision with the mouse for the buttons. My current work around based on previous forum post is as follow:
In MenuState.cpp - replace the calls of setPosition of the wrapper class with a function that directly passes the coordinates to the sprite and text object.
// A subset of the constructor of the MenuState
auto playButton = std::make_shared<GUI::Button>(context);
float offsetX = playButton->getSize().width / 2 ;
playButton->setPos(winX/2 - offsetX, winY/3); // Replace a call of setPosition here ***
playButton->setText("Play");
playButton->setCallback([this] ()
{
requestStackPop();
requestStackPush(States::Game);
});
In Button.cpp a method is added to directly apply the position to the sprite and text.
// Add a function to pass the position to the underlying objects (sprite and text) instead of the button itself
void Button::setPos(float x, float y)
{
this->mSprite.setPosition(x,y);
this->mText.setPosition(x + this->getSize().width /2 ,y + this->getSize().height /2);
}
The reason this work around was applied was because in a method which handles the Mouse event, I could not check collision with the sprite since the Button class was moved but the globalPosition of the sprite and text was still set to 0,0 (moving mouse to top left corner would select last piece of menu). For the draw menu the transforms are passed down so this is not an issue when drawing. The final menu has a container for the buttons that are iterated over and the position of the sprite it checked using .contains against the mouse event coordinates.
Final question: What would be the best way to pass a wrapper objects transform to an underlying sprite to check if the sprite (or wrapper object) contain the position of the mouse click?
Hope this question is not too verbose or vague this is my first post and welcome to feedback.