0
votes

I've tried to do a Button with SFML, but when i click on the Sprite, the program print : "You didn't press the Button"..

Window.cpp :

while(m_window.pollEvent(event))
        {
            switch(event.type)
            {
                 case sf::Event::MouseButtonPressed:
                 std::cout << "MouseButtonPressed !" << std::endl;
                 if(buttonEnter.eventMouse(m_window.mapPixelToCoords(
                    {event.mouseButton.x, event.mouseButton.y})))
                 {
                    std::cout << "You did press the Button " << std::endl;
                 }
                 else
                 {
                    std::cout << "You didn't press the Button" << std::endl;
                 }
                 break;

                case sf::Event::Closed:
                m_window.close();

                default:
                break;
            }
        }

And Button.cpp (buttonEnter)

bool Button::eventMouse(sf::Vector2f const &cursor_position)
{
    std::cout << "eventMouse" << std::endl;

    bool test = m_spriteButton.getGlobalBounds().contains(
    cursor_position.x,cursor_position.y);

    return test;
}

The program print (when i click on the Sprite) : MouseButtonPressed ! eventMouse You didn't press the button

{ I think that my code (Windows.cpp and Button.cpp) is good, so this is all my code : https://github.com/Moongm/LoadComponent }

Thank's for you help !

2

2 Answers

0
votes

I'm not so sure but mouse coordinates that given by MouseEvent may not be relative to the window.

You could give a try to this:

buttonEnter.eventMouse(m_window.mapPixelToCoords(sf::Mouse::getPosition(m_window)))
0
votes

I don't know why but I couldn't find window.cpp on your github that's why i don't know how works mapPixelToCoords, but try to use something like that:

Vector2f tempMouse(Mouse::getPosition(m_window));
   if(buttonEnter.eventMouse(tempMouse))

BTW your button will react to press anyone button on mouse, so you should check few important things

// It does not have to be like this, I just want to show conditions 
    Vector2f tempMouse(Mouse::getPosition(m_window));
    if(someObject.getGlobalBounds().contains(tempMouse) &&
        event.type == Event::MouseButtonReleased &&
        event.key.code == Mouse::Left)

Solution given above is not perfect, but in simple case it's okey i think.