Home :: Programming :: Code Snippets :: OpenGL :: Mouse Dragging
[ Mouse Dragging ]
In this snippet I will show you how to move the viewport or rotate an object on the screen depending on how the mouse has moved. In this following example I will assume that there is a cube on the screen and that rotationX and rotationY hold the X and Y rotation of it.
Notice: I use the standard Win32 API to handle mouse movement. You could also use Mfc, GLUT or do the same in Linux. This snippet should only show you the basic idea how to handle the problem.
Here's the code:
//Specify two global variables
int oldMouseX = 200;
int oldMouseY = 200;
bool mouseDown = false;
//.. other code
//Mouse is pressed
mouseDown = true;
//Mouse isn't pressed anymore
mouseDown = false;
//If we aren't dragging..
//Get current mouse pos
int mouseX = LOWORD(lParam);
int mouseY = HIWORD(lParam);
//Test if mouse moved on the X-Axis
if ((oldMouseX - mouseX) < 0) //Mouse moved to the right
rotationX -= 0.1f;
else ((oldMouseX - mouseX) > 0) //Mouse moved to the left
rotationX += 0.1f;
//Test if the mouse moved on the Y-Axis
if ((oldMouseY - mouseY) < 0) //Mouse moved downwards
rotationY += 0.1f;
else ((oldMouseY - mouseY) > 0) //Mouse moved upwards
rotationY -= 0.1f;
//Save the current mouse positions
//for the next time
oldMouseX = mouseX;
oldMouseY = mouseY;
//... other event code
} //END SWITCH
So what we actually do is to calculate the movement on both the X and the Y-Axis. Depending on how the mouse has moved, the cube will be rotated. You could also transform the viewport or anything else. Notice that the cube will only be rotated when the left mouse button is down so if we are dragging. mouseDown is used to hold the state of the left mouse button (pressed or not pressed).
The code should be easy to understand and you should also be able to port it to another API. If you have problems, m@il me. Happy coding!