{steinsoft.net}
 
 
 
 
 
Home/News
Code Snippets
Board
Projects
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Leipzig
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
//..
//..
 
LRESULT WndProc(..)
{
   switch(message)
   {
   //..
   //..
   case WM_LBUTTONDOWN:
      //Mouse is pressed
      mouseDown = true;
      break;
   case WM_LBUTTONUP:
      //Mouse isn't pressed anymore
      mouseDown = false;
      break;
   case WM_MOUSEMOVE:
      //If we aren't dragging..
      if (!mouseDown)
      {
         return 0;
      }
  
      //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;
  
      break;
   //... 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!

 Last edited 2002-12-07 20:10:17 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0