Use vector dot product to rotate the model around the center
How to rotate a model around the center in a 3D space? This problem sounds easy, but after my practice, I found it quite difficult. In the initial stages of studying OpenGL and DirectX, I believe this problem still hurts everyone's brains. How can this function be implemented? I think you may need to go back and review our high school knowledge. Through the analogy of plane analysis and ry, you will find a good method.
This will be traced back to the vector and plane analytic ry we learned in our high school. Voice VectorAIs a common vector, VectorBYesAIt is formed by rotating the α angle clockwise relative to the center. Known VectorsAAndB, α.
The method is simple. First, translate the image as follows:
Here we can use the dot matrix formula of the vector,A·B= |A|B| Cos α, calculate α = arccos (A·B/|A|B|
). In the resolution ry, SetA(XA, ya ),B(XB, Yb), thenA·B= Xa xb + YA Yb. |A|B| = √ (Xa2 + YA2) · √ (XB2 + yb2), which makes it easy to solve.
Now the idea is changed to 3D space. Likewise,A·BSatisfies the generalized Cartesian inner product form. In this way, the angle between two three-dimensional vectors can also be obtained through the above formula.
Set a (XA, ya, za), B (XB, Yb, ZB), then a · B = XA XB + YA Yb + Za ZB. | A | B | = √ (xa2 + YA2 + za2) · √ (XB2 + yb2 + zb2). α is obtained according to the method.
This plays a major role in vector rotation. If the default position of a cone is like this (for example), you can take its upward vector.Up(, 0). You want to open it to a yellow line.Direction(,-1), the angle between the Blue Line and the yellow line is α, so we can perform this operation (in this example, QT is used ).
// Calculate the rotation axis and Rotation Angle float angleinradians = pi-ACOs (qvector3d: dotproduct (up, direction)/direction. length ()/up. length (); const qvector3d & axis = qvector3d: crossproduct (up, direction); glpushmatrix (); gltranslatef (POS. X (), POS. Y (), POS. Z (); glrotatef (angleinradians * 180/PI, axis. X (), axis. Y (), axis. Z ());
Here,AxisIs the axial volume of rotation, because the VectorUpAndDirectionIf they intersect at one point (the geometric center of the model), they are uniquely identified as a plane. The normal vector of this plane isUp×Direction, So makeUpVector rotation-DirectionVector (the reason is-DirectionIt is because you want to open up rather than tip up ).AxisTo rotate the axis. The following is the execution result.
The source code of my project has been uploaded and can be downloaded by anyone who needs it.
Demo program: here
Source code: here