Improving Click and Drag with C++

Posted by Josh on Game Development See other posts from Game Development or by Josh
Published on 2013-11-05T04:44:29Z Indexed on 2013/11/05 10:14 UTC
Read the original article Hit count: 313

Filed under:
|
|

I'm currently using SFML 2.0 to develop a game in C++. I have a game sprite class that has a click and drag method. The method works, but there is a slight problem. If the mouse moves too fast, the object the user selected can't keep up and is left behind in the spot where the mouse left its bounds. I will share the class definition and the given function implementation.

Definition:

class codePeg
{
protected:
    FloatRect bounds;
    CircleShape circle;
    int xPos, yPos, xDiff, yDiff, once;
    int xBase, yBase;
    Vector2i mousePos;
    Vector2f circlePos;
public:
    void init(RenderWindow& Window);
    void draw(RenderWindow& Window);
    void drag(RenderWindow& Window);
    void setPegPosition(int x, int y);
    void setPegColor(Color pegColor);
    void mouseOver(RenderWindow& Window);
    friend int isPegSelected(void);
};

Implementation of the "drag" function:

void codePeg::drag(RenderWindow& Window)
{
mousePos = Mouse::getPosition(Window);
circlePos = circle.getPosition();

if(Mouse::isButtonPressed(Mouse::Left))
{
    if(mousePos.x > xPos && mousePos.y > yPos
        && mousePos.x - bounds.width < xPos && mousePos.y - bounds.height < yPos)
    {
        if(once)
        {
            xDiff = mousePos.x - circlePos.x;
            yDiff = mousePos.y - circlePos.y;
            once = 0;
        }
        xPos = mousePos.x - xDiff;
        yPos = mousePos.y - yDiff;
        circle.setPosition(xPos, yPos);
    }
}
else
{
    once = 1;
    xPos = xBase;
    yPos = yBase;
    xDiff = 0;
    yDiff = 0;
    circle.setPosition(xBase, yBase);
}
Window.draw(circle);
}

Like I said, the function works, but to me, the code is very ugly and I think it could be improved and could be more efficient. The only thing I can think of as to why the object cannot keep up with the mouse is that there are too many function calls and/or checks. The user does not really have to mouse the mouse "fast" for it to happen, I would say at an average pace the object is left behind. How can I improve the code so that the object remains with the mouse when it is selected?

Any help improving this code or giving advice is greatly appreciated.

© Game Development or respective owner

Related posts about c++

Related posts about game-design