I have a game in c++ using SFML library, if I press escape a menu should be drawn, for that i have a UI class, this class is drawn when I press escape so when the player opens the menu, for this UI i have a Button class that creates a button with a texture and a function to call when pressed, but my problem is that even though the button position is set to 0,0 the Sprite is somewhere around 200,200 but to call the function that the button should execute, I have to click at around 0,0? But the texture position isnt set to anything but the 0,0?
This is the button:
Button::Button(float x, float y, float wf, float hf, std::string path, std::function<void()> callback)
: onClick(callback)
{
if (!buttonTexture.loadFromFile(path))
{
std::cerr << "Error loading tilesheet from " << path << std::endl;
}
buttonSprite.setTexture(buttonTexture);
buttonSprite.setPosition(0, 0);
buttonSprite.setScale(wf, hf);
}
void Button::draw(sf::RenderWindow &window)
{
window.draw(buttonSprite);
}
void Button::handleEvent(const sf::Event &event, const sf::RenderWindow &window)
{
if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Left)
{
sf::Vector2i mousePos = sf::Mouse::getPosition(window);
sf::FloatRect bounds = buttonSprite.getGlobalBounds();
if (bounds.contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y)))
{
if (onClick)
{
onClick();
}
}
}
}
}
and this is the Implementation in the UI.cpp
UI::UI(sf::RenderWindow &window)
{
testButton = new Button(0.0f, 0.0f, 1.0f, 1.0f, "res/Ships/PNGs/ship.png",
[]()
{
std::cout << "Button clicked!" << std::endl;
});
}
and the button gets also updated and drawn:
if (UItrue)
{
testButton->handleEvent(event, window);
}
...
if (UItrue)
{
testButton->draw(window);
}
the UI gets also updated and drawn in the main loop
I tried to print out the position of the buttonSprite but it said 0,0. Also the image I use for the button is currently the same as the players so I know its not because of that?
If you need further info or have any Ideas on why the sprite is offset please tell me.
Also if you want more of the code, I have it here on Github
Abbadon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.