# Rotating a cube with the mouse.

I tried using sinusoidal and cosine functions to map the mouse position to a unit sphere and rotate my cube accordingly.But the cube moves in awkward directions and is not in sync with my mouse movement.

Could anyone suggest a way to do it?

Hi Optik,

Could you please paste the critical portions of your code so we can have a look. It’s hard to visualize what you want to do from your brief description.

Here is the pseudo code:

void render(void) // display callback
{

`````` glRotatef(anglex,1.0f,0.0f,0.0f);
glRotatef(angley,0.0f,1.0f,0.0f);
glRotatef(anglez,0.0f,0.0f,1.0f);

glutSolidCube(side); //or whatever it may be

glutSwapBuffers();
``````

}

void mouse(int mx,int my) //mouse callback
{
// here my approach goes like this.
// I feel I need to consider the local origin wrt the cube
// as my point of convergence of the 3 axes
// For instance if my resolution is say 800x600 and
// assume the object is at the center of my viewport which
// spans across the whole screen. then my origin wrt
// the viewing area is (400,300)(screen coordinates).
// Now when we obtain the mouse coordinates on the screen
// we find its coordinates wrt the new origin (400,300)
// by doing x = x - 400 and y = y - 300
// and assume a unit circle rotation here, ie
// anglex = arccos(x) and angley = arcsin(y)

`````` // and I am utterly lost when it comes to z-axis rotation
``````

}

PS: sorry I dont have my PC with me right now so i had to cook up this pseudo code.

Here’s the method I use. It works well for me.

``````
float movement[2]; // movement in the x direction, movement in the y direction
float length = sqrt(movement[0]*movement[0]+movement[1]*movement[1]);
glRotatef(length, movement[1]/length, 0.0, -movement[0]/length);
``````

Also, I scale the elements of movement to control the speed of the motion. I stopped using glRotatef, so you may have to play with the minus signs or swap the elements (if it’s rotating backwards, or about the wrong axis).

It works fine thanks, but What I need is for any fixed point of the cube to orient towards the mouse pointer all the time.