简体   繁体   English

如何引用功能?

[英]How can I refer to a function?

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. 我现在正在学习C ++和SFML,试图创建一个国际象棋程序,在其中可以将棋子拖放到棋盘上。 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. 我希望'pieceSelected'引用'Pawn',这样当我移动'pieceSelected'时,我实际上是在同时移动'Pawn'。

EDIT 编辑

I fixed this by changing 我通过更改来解决此问题

sf:Sprite pieceSelected;

to

sf::Sprite * pieceSelected;

and

pieceSelected.SetPosition

to

pieceSelected->SetPosition

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 . 相反,您应该只将片段放在LeftMouseUp

What you want is a DragOperation class. 您想要的是DragOperation类。 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. DragOperation类在其构造函数中具有sf::Sprite & pieceSelected集合。 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. 拖动时,应将绘制选定片段的职责移至DragOperation类。 This allows you to smoothly drag the pawn, in pixel increments, instead of drawing it only in the middle of a square. 这样,您就可以以像素为单位平滑拖拽pawn,而不是仅在正方形的中间进行绘制。

When the mouse button is released, check the result and then delete your DragOperation object. 释放鼠标按钮时,请检查结果,然后删除您的DragOperation对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM