I am working on a very simple "GUI framework" for my game.


As you can see from the GIF, i have a window object that can be selected when the mouse is inside of it and dragged, when the left mouse button is being pressed.

I tried to solve the problem this way:

Basically i calculate the x and y component of the distance between the center of the window and the mouse cursor. I then add the component values to the window function, which looks something like:

//mousePosition is a Vector2() that stores the mouse position
//x_component is a float, calculated by doing: 
//float x_component = mousePosition.x - window.getPosition().x;
//same for the y_component variable.

window.setPosition(Vector2(mousePosition.x + x_component, mousePosition.y + y component));//set position takes in a Vector2

But for some reason, this is not working. I think that it's because we are not taking in consideration the fact that the x or y component could be negative, in relation to where we press the mouse inside the window.

Can someone help me?

  • \$\begingroup\$ Your .gif link appears to be broken. \$\endgroup\$ Jan 31, 2018 at 4:08

1 Answer 1


If the idea is to click and drag the window then you are assuming that the coordinates of the mouse cursor relative to the upper-left corner of the window will be the same before and after the mouse moves. So when you get a mouse-down event, record that offset: offset_at_grab_time = mouse_position_in_screen_coordinates - window_position_in_screen_coordinates. Then, when the mouse moves you can update the window position to have the same relative offset to the mouse as when you grabbed it by setting the position such that new_window_position_in_screen_coordinates = new_mouse_position_in_screen_coordinates - offset_at_grab_time

Ignore the center of the window; rather, you are interested in the position of the window in the same coordinate system as the mouse coordinates.

  • \$\begingroup\$ Okay, thanks for the answer! I'm going to test this out as soon as possible. Is there a particular reason why we store the position of the cursor relative to the upper left corner of the window instead of its center? \$\endgroup\$
    – user100681
    Jan 30, 2018 at 19:26
  • 1
    \$\begingroup\$ @GabrieleVierti No, It doesn't really matter. It just makes the calculation of where the window postion all that much easier. If the client rectangle is offset relative to the position of the window, then that's yet another offset you will have to take into consideration - and often mouse coordinates are given in client coordinates (relative to a point that is in the interior "client" portion of the rect, below the titlebar). Whereas the window position itself is often (0,0) in window coordinates (relative to the top left corner outside the window - above the titlebar). \$\endgroup\$
    – Wyck
    Jan 31, 2018 at 2:24

You must log in to answer this question.