-
Hi... I know this question has been posted loads of times. I tried out all those solutions, but none of them are giving me desired output. I want to click on a sprite which will trigger an action, but it is not working for some reason. I tried two alternatives,
Mouse Click event in the event loop:
while(window.pollEvent(event))
{
if(event.key.code == sf::Keyboard::Escape)
window.close();
if(event.type == sf::Event::Closed)
window.close();
if(event.mouseButton.button == sf::Mouse::Left)
{
if(event.mouseButton.x > ebound.left && event.mouseButton.x < (ebound.left + ebound.width) && event.mouseButton.y > ebound.top && event.mouseButton.y < (ebound.top + ebound.height))
window.close();
}
}
Mouse Click in the window loop:
float mouseX = (float)sf::Mouse::getPosition().x;
float mouseY = (float)sf::Mouse::getPosition().y;
if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
if(ebound.contains(mouseX, mouseY))
window.close();
What is wrong? Why is it not working? Please tell me. Thank you.
-
You need to check that the type of the event is sf::Event::MouseButtonPressed before using event.mouseButton.button or event.mouseButton.x/y)
Yes, using contains is good.
If you use a view which has been moved / scaled / rotated, you probably want to use mapPixelToCoords. (take a look at the last paragraph of the view tutorial)
sf::Mouse::getPositions takes one argument (window) or it will be relative to the top left corner of the screen.
-
I an not using any View, just a static stationary image. I changed the code to:
if(event.type == sf::Event::MouseButtonPressed)
if(event.mouseButton.button == sf::Mouse::Left)
if(event.mouseButton.x > ebound.left && event.mouseButton.x < (ebound.left + ebound.width) && event.mouseButton.y > ebound.top && event.mouseButton.y < (ebound.top + ebound.height))
window.close();
That didn't work. So, I tried:
float mouseX = (float)sf::Mouse::getPosition(window).x;
float mouseY = (float)sf::Mouse::getPosition(window).y;
if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
if(ebound.contains(mouseX, mouseY))
window.close();
Still it isn't working. What am I doing wrong? Please help.
-
Maybe ebound isn't correct.
If you have to post code, posting a minimal (remove everything not related to the "error") and complete (so people only have to make one copy/paste to test/compile it) code is a good habit here.
-
OK OK... I only thought minimal. And you're right. I didn't update the bounding box after transformation.
if(!e1.loadFromFile("quit.png"))
return EXIT_FAILURE;
e.setTexture(e1);
sf::FloatRect ebound = e.getGlobalBounds();
e.setOrigin(ebound.width/2, ebound.height/2);
e.setPosition(resolution.getDesktopMode().width/2 + ebound.width, resolution.getDesktopMode().height/2 + ebound.height*2);
This was my mistake. Thanks a lot, G. :)