-
Hello, i need help with mouse and rectangle collision. I had draw a rectangle if shop window should be open and tryed to get proper its locations x and location y, the problem is the mouse x and y position are global, while rectangle shows completele different numbers,
Here is example of the code
if (ShopKeeper1.shopOpen == true)
{
std::cout << "SHOP IS OPEN" << std::endl;
std::cout << shopOne.rect.getGlobalBounds().top << std::endl;
if(shopOne.rect.getGlobalBounds().contains(sf::Mouse::getPosition().x,sf::Mouse::getPosition().y))
{
std::cout << "MOUSE ON THE SHOP" << std::endl;
}
}
i can only get rectangles starting position which is 0, its width and height, if someone could help me out here would be appriciated.
-
sf::Mouse::getPosition can take a window as a parameter.
https://www.sfml-dev.org/tutorials/2.5/window-inputs.php#mouse
You may also want to use sf::RenderWindow::mapPixelToCoords (https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1RenderTarget.php#a0103ebebafa43a97e6e6414f8560d5e3), especially if you use views.
-
Yes i use views, i got it working thanks, but i think where should be better way to do this...
if (ShopKeeper1.shopOpen == true)
{
std::cout << "SHOP IS OPEN" << std::endl;
if (shopOne.rect.getGlobalBounds().contains(sf::Mouse::getPosition(mainWindow).x -195,sf::Mouse::getPosition(mainWindow).y + 110 ))
{
std::cout << "MOUSE ON THE SHOP" << std::endl;
}
}
added mainWindow, its my sf::RenderWindow object, but had to add and minus the postitions to get it right.
As i said i think wher eshould be better way to do this.
-
The position returned by getPosition is a pixel location of the entire screen/desktop.
The co-ordinates used by any of the drawn objects - such as, I presume, your shopOne.rect - are co-ordinates within the view.
To compare two types, you must convert (map) one to the other (as mentioned by G.).
So, it would be something closer to:
if (shopOne.rect.getGlobalBounds().contains(mainWindow.mapPixelToCoords(sf::Mouse::getPosition(mainWindow))))