Hi Folks,
I am trying to implement method that can detect whether a user is holding down the left mouse button, thus indicating that the user is dragging a sprite.
In my event loop, I have this - note some is pseudo code. Basically I am sleeping the program for 100 milliseconds after the a sf::Mouse::Left event is detected. If the mouse is still pressed then I say the user is attempt to drag an icon.
I cannot assume that just having a sf::Mouse::Left indicates that the user is dragging an icon as he could just be left clicking the sprite to select it. If I did then it starts dragging/dropping icons when the user is just trying to select them.
It just seems a bit of an inefficient way to detect whether a user is dragging by adding a sleep. Is there a more efficient method to implement drag/drop, whilst at the same time support left clicking
if (event.type == sf::Event::MouseButtonPressed)
{
//if left button pressed
if (event.mouseButton.button == sf::Mouse::Left)
{
cout << "left pressed \n";
sf::sleep(sf::milliseconds(100));
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
isDragging = true;
cout << "left pressed and isDragging \n";
//Here I check if mouse was within the bounds of the sprite and do what I need to do
}
}
}
Is the sleep there to ensure that the button is held rather than just clicked?
Yes that is exactly why the sleep is there. Basically if the left pressed event is triggered then I want to know if the user is still holding the left button. If I don't have that sleep in there then it takes left clicks as dragging attempts and moves the sprite when I just trying to left-click on the sprite.
I don't think I fully understand the timing method that you are describing. Are you able to clarify how the timer would work?
I did make an attempt as below, but it always seemed to be saying the user was dragging, even during a left-click.
So in my class I defined a gameClock
sf::Clock gameClock;
Then at the beginning of the event loop, I have this to check if the left button is pressed and if the gameclock elapsed time is > 100 milliseconds. If not then restart the game clock
if (sf::Mouse::isButtonPressed(sf::Mouse::Left) && gameClock.getElapsedTime().asMilliseconds() >= 100)
{
cout << "gameClock.getElapsedTime().asMilliseconds() = " << gameClock.getElapsedTime().asMilliseconds() << "\n";
cout << "setting isdragging to true\n";
isDragging = true;
}
else
{
gameClock.restart();
}
Now I am not entirely sure if this what you meant as to having a timer?
Then in my events I have more or less the same thing, except no sleep or isButton pressed check anymore.
if (event.type == sf::Event::MouseButtonPressed)
{
//if left button pressed
if (event.mouseButton.button == sf::Mouse::Left)
{
cout << "left pressed \n";
if (isDragging)
{
//Here I check if mouse was within the bounds of the sprite and if so then do the dragging updates.
}
else if (!isDragging)
{
//Do the stuff I want to do when user is not trying to do a drag and drop
}
}
}