when i
click down on object and
mouse move slowly object will move follow.
if i move mouse faster mouse will leave or out of object and stop moving.what wrong with my code and how to fix it.#include <SFML/Graphics.hpp>
bool isMouseOver(sf::Sprite &sprite, const sf::Input &input)
{
sf::Vector2f mousePos(input.GetMouseX(), input.GetMouseY());
if(
// check mouse position
(mousePos.x >= sprite.GetPosition().x)
&&
(mousePos.x <= sprite.GetPosition().x + sprite.GetSubRect().GetWidth())
&&
(mousePos.y >= sprite.GetPosition().y)
&&
(mousePos.y <= sprite.GetPosition().y + sprite.GetSubRect().GetHeight())
&&
// check pixel on sprite
(sprite.GetPixel(mousePos.x - sprite.GetPosition().x, mousePos.y - sprite.GetPosition().y).a == 255)
)
return true;
return false;
}
bool isMouseButtonDown(sf::Sprite &sprite, const sf::Input &input)
{
if (input.IsMouseButtonDown(sf::Mouse::Left))// && isMouseOver(sprite, input))
return true;
return false;
}
int main()
{
// image
sf::Image image;
if (!image.LoadFromFile("image.png"))
return EXIT_FAILURE;
// window
sf::RenderWindow window(sf::VideoMode(640, 480), "SFML window: Mouse Event");
window.SetFramerateLimit(60);
const sf::Input& input = window.GetInput();
// sprite
sf::Sprite sprite;
sprite.SetImage(image);
float lastMouseX = 0;
float lastMouseY = 0;
bool dragStarted = false;
// game loop
while (window.IsOpened())
{
sf::Event Event;
// event loop
while (window.GetEvent(Event))
{
// close window
if (Event.Type == sf::Event::Closed)
{
window.Close();
}
// if mouse over sprite
if(isMouseOver(sprite, input))
{
//if mouse button down
if (isMouseButtonDown(sprite, input))
{
if(!dragStarted)
{
//start drag
dragStarted = true;
}
else
{
//drag
sprite.Move(input.GetMouseX() - lastMouseX, input.GetMouseY() - lastMouseY);
}
//get current mouse position
lastMouseX = input.GetMouseX();
lastMouseY = input.GetMouseY();
}
// if mouse button up
else
{
//stop drag
dragStarted = false;
}
}
// mouse not over sprite
else
{
//stop drag
dragStarted = false;
}
}
// clear screen
window.Clear(sf::Color(255, 255, 255));
// draw the sprite
window.Draw(sprite);
// update the window
window.Display();
}
return EXIT_SUCCESS;
}