NeHe OpenGL Lesson48-ArcBall Rotation (Mouse Rotation)

Source: Internet
Author: User

This sample provides us an ArcBall module that we cocould use to rotate object along the screen with mouse. the underneath idea is mapping a 2d screen position into a 3d sphere coordinate. A rotation Quat cocould be calculated out by two sphere coordinates (the start, end position ). then a rotation matrix created based on the quat.

This sample also provide some other useful technologies:

1) convert quat to a rotation matrix;

2) use OpenGL fucntion"GlMultMatrixf (Transform. M );"To set up the model view matrix directly;

 

Mapping 2D Mouse Position into 3D Sphere Coordinate

At first we simply scale down the mouse coordinates from the range of [0... width), [0... height) to [-1... 1], [1... -1] (Y flipped ).

X  =  (MousePt.X / ((Width  - 1) / 2));Y  = -(MousePt.Y / ((Height - 1) / 2));

Calculate the 3D Sphere coordinates:

length      = (X * X) + (Y * Y);//If the point is mapped outside of the sphere... (length > radius squared)if (length > 1.0f){    GLfloat norm;    //Compute a normalizing factor (radius / sqrt(length))    norm    = 1.0f / FuncSqrt(length);    //Return the "normalized" vector, a point on the sphere    NewVec->s.X = TempPt.s.X * norm;    NewVec->s.Y = TempPt.s.Y * norm;    NewVec->s.Z = 0.0f;}else    //Else it's on the inside{    //Return a vector to a point mapped inside the sphere sqrt(radius squared - length)    NewVec->s.X = TempPt.s.X;    NewVec->s.Y = TempPt.s.Y;    NewVec->s.Z = FuncSqrt(1.0f - length);}

 

The full source code cocould be found here.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.