In the example below, I'm trying to print "COLLISION" when I mouseover the box sprite.
Even though the sprite position is set elsewhere, getGlobalBounds() thinks that it's centered on coordinates 0,0.
What am I doing wrong here?
#include <SFML/Graphics.hpp>
#include <iostream>
class Box : public sf::Drawable, public sf::Transformable
{
public:
sf::Sprite sprite;
sf::Texture texture;
void load()
{
texture.loadFromFile("box.png");
sprite = sf::Sprite(texture);
sprite.setTextureRect(sf::IntRect(0, 0, 420, 120));
sprite.setOrigin(210, 60);
}
private:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states)const
{
states.transform *= getTransform();
states.texture = &texture;
target.draw(sprite, states);
}
};
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML");
window.setFramerateLimit(10);
Box box;
box.load();
box.setPosition(300, 300);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
sf::Vector2f Mouse = window.mapPixelToCoords(sf::Mouse::getPosition(window));
std::cout << "Mouse.x = " << Mouse.x << ", Mouse.y = " << Mouse.y << std::endl;
if (box.sprite.getGlobalBounds().contains(Mouse))
{
std::cout << "COLLISION!" << std::endl;
}
window.clear();
window.draw(box);
window.display();
}
return 0;
}