0

我现在正在学习 C++ 和 SFML,试图创建一个国际象棋程序,我可以在其中拖放棋子周围的棋子。我通过检查鼠标左键是否按下以及鼠标是否在一块上来拖动这些块。如果这两个都是真的,我将棋子的位置更改为鼠标的位置。

唯一的问题是当我非常快速地拖动碎片时,我的鼠标向下但没有悬停在碎片上。

我想使用以下方法解决此问题:

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);

我希望“pieceSelected”引用“Pawn”,这样当我移动“pieceSelected”时,我实际上是在同时移动“Pawn”。

编辑

我通过改变来解决这个问题

sf:Sprite pieceSelected;

sf::Sprite * pieceSelected;

pieceSelected.SetPosition

pieceSelected->SetPosition
4

1 回答 1

1

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.

于 2013-04-07T23:43:56.100 回答