//
you're reading...
Tech

Using Mouse to Scale & Rotate Object in OpenGL

We will use the wheel to scale the object and the *drag* action to rotate an object. Using wxWidgets, we are able to listen to the mouse events. To make it general, I will use comments only to indicate when the code happens.

Firstly, in the display function, we would have the typical rotate and translate functions listed, something like:

 glTranslatef(0.0f, 0.0f, -6.0f);
 glRotatef((preRotX + rotX), 0.0f, 1.0f, 0.0f);
 glRotatef((preRotY + rotY), 1.0f, 0.0f, 0.0f);

I would explain the parameters later. For scaling it’s pretty simple, something like:

// in mouse wheel event handler
scale += mouseRotation * weight;

And scale is a parameter controlling the scale of your object. There are so many ways to implement scaling.

For rotating we need to listen to two events: when the mouse is being pushed down and when the mouse is released. In my case I also use three sets of coordinates to manage data, namely,

  • orgX, orgY //the position where the mouse is pushed down;
  • rotX, rotY //the difference between current coordinates and (orgX, orgY);
  • preRotX, preRotY //the accumulated coordinates’ differences of each mouse action.

Why are we talking about X and Y? Because the idea of interactive rotation is to rotate the object according to the position changes of the mouse. So the difference of coordinates actually represents the angles to rotate w.r.t the X-axis and Y-axis, respectively.

Firstly, we should record the changes of coordinates when doing the dragging.

// in mouse pushed-down event handler
if(isFirstDown)
{
    isFirstDown = false;
    orgX = x;
    orgY = y;
}
else
{
    rotX = x - orgX;
    rotY = y - orgY;
}

When the mouse is firstly pushed down, we record the position and then each time we just obtain the latest position and calculate the difference. When the dragging is done, we do the following:

// in mouse released event handler
isFirstDown = true;
preRotX += rotX;
preRotY += rotY;
rotX = 0;
rotY = 0;

We reset some flags, update or reset some variables. Now we would have recorded the latest rotation of the object so that we can start from there in next time.

Advertisements

About Xiang 'Anthony' Chen

Making an Impact in Your Life

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Twitter Updates

%d bloggers like this: