I'm trying to figure out how I can click on a sprite, then drag it and drop it at a new position. I'm guessing either I shouldn't be using Sprite.SetPosition() like this OR I'm going about calculating a mouseover incorrectly.
#include <SFML/Graphics.hpp>
bool isMouseOver(const sf::Sprite& sprite, const sf::Input& input)
{
const int mousex = input.GetMouseX();
const int mousey = input.GetMouseY();
const sf::Vector2f spritesize = sprite.GetSize();
const sf::Vector2f spritecenter = sprite.GetCenter();
// If the distance between the mouse and the sprite's center
// is less than the length/width of the sprite.
if (mousex - spritecenter.x < spritesize.x &&
mousey - spritecenter.y < spritesize.y)
return true;
return false;
}
int main()
{
sf::RenderWindow App(sf::VideoMode(800, 600), "SFML window");
// Usually I use a resource manager to do this.
sf::Image Image;
Image.LoadFromFile("cb.bmp");
sf::Sprite Sprite;
Sprite.SetImage(Image);
while (App.IsOpened())
{
const sf::Input& Input = App.GetInput();
sf::Event Event;
while (App.GetEvent(Event))
{
if (Event.Type == sf::Event::KeyPressed)
{
if (Event.Key.Code == sf::Key::Escape)
App.Close();
}
if (Event.Type == sf::Event::Closed)
App.Close();
}
}
if (Input.IsMouseButtonDown(sf::Mouse::Left))
if (isMouseOver(Sprite, Input))
Sprite.SetPosition(Input.GetMouseX(), Input.GetMouseY());
App.Clear();
App.Draw(Sprite);
App.Display();
}
return EXIT_SUCCESS;
}
What happens is that the sprite DOES get dragged around.. but only as long as the mouse is on the sprite's original sprite area. So I'm guessing that I should be modifying something else about the sprite or something, or resetting the center. I've tried that, but I'm not sure how to go about doing it correctly.