Reputation: 625
I'm learning C++ and SFML right now, trying to create a chess program in which I can drag and drop the pieces around the board. I drag the pieces by checking if the left mouse button is down and if the mouse is over a piece. If these are both true, I change the position of the piece to that of the mouse.
The only problem is when I drag the pieces really quickly, thus having my mouse down but not hovering over the piece.
I want to fix this using something like:
sf::Sprite pieceSelected;
sf::Sprite Pawn;
bool selected;
...
if (LeftButtonDown && isMouseOver(Pawn,Input)) {
pieceSelected=&Pawn;
selected = true;
}
if (LeftButtonDown && selected)
pieceSelected.SetPosition(MouseX - (XSizeSprite / 2), MouseY - (YSizeSprite / 2));
else
selected=false;
App.Draw(Pawn);
I want 'pieceSelected' to be referencing 'Pawn' so that when I'm moving 'pieceSelected' I'm actually moving 'Pawn' at the same time.
EDIT
I fixed this by changing
sf:Sprite pieceSelected;
to
sf::Sprite * pieceSelected;
and
pieceSelected.SetPosition
to
pieceSelected->SetPosition
Upvotes: 0
Views: 109
Reputation: 180010
Right, from the comments I spotted the problem. Your drag-and-drop code repeatedly picks up and drops the pawn. That's indeed not the correct solution. Instead, you should only drop the piece on a LeftMouseUp
.
What you want is a DragOperation
class. You create it when you detect the begin of a drag operation (mouse down over a pawn). The DragOperation
class has a sf::Sprite & pieceSelected
, set of course in its constructor. You should also store both the mouse and pawn coordinates where the drag operation started.
While dragging, the responsibility of drawing the selected piece should be moved to the DragOperation
class. This allows you to smoothly drag the pawn, in pixel increments, instead of drawing it only in the middle of a square.
When the mouse button is released, check the result and then delete your DragOperation
object.
Upvotes: 1