# calculate the offset between a quad and the mouse position Opengl

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?

• Your .gif link appears to be broken. Jan 31 '18 at 4:08

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