How do we rotate a figure in 2d in openGL relative to a point (other than the origin)?

Using the glrotatef() function rotates the figure by a given angle relative to the origin. How to rotate the same drawing relative to another point without using the transformation matrices manually? Thanks!

 void display(){ glClear(GL_COLOR_BUFFER_BIT); gluOrtho2D(0,499,0,499); glMatrixMode(GL_PROJECTION); glColor3f(1,0,0); drawhouse(); glFlush(); glColor3f(0,0,1); glTranslatef(0.5 ,0.5,0.5); glRotatef(45,1,1,1); glTranslatef(-0.5 ,-0.5,-0.5); drawhouse(); glFlush(); } 

Here is a screenshot for what is happening. http://postimage.org/image/q81bhupw/

+4
source share
2 answers

Basically:

If you want to rotate around P , translate to -P (so that P moves to the origin), then rotate it and then translate to P (so that the origin returns to P ).

 glTranslatef(Px, Py, Pz); glRotatef(angle, Ax, Ay, Az); glTranslatef(-Px, -Py, -Pz); 

(Note: it is in “reverse order” because the last transformation added is the first one applied according to OpenGL rules.)

So, in your installation code, you need these calls:

 glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, 499, 0, 499); glMatrixMode(GL_MODELVIEW); 

And then your display() method should look something like this:

 void display() { glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glTranslatef(0.5f, 0.5f, 0.5f); glRotatef(45.f, 1.f, 1.f, 1.f); glTranslatef(-0.5f, -0.5f, -0.5f); glColor3f(0.f, 0.f, 1.f); drawhouse(); glFlush(); } 
+7
source

Your code is complete garbage. First, you should apply the transformation in the moelview matrix, not the projection matrix. Secondly, you must transfer the conversion to glPushMatrix/glPopMatrix , otherwise they will not be canceled when rendering the next frame. Third, you should apply gluOrtho2d to the projection matrix, not the matrx matrix representation.

According to John's answer, your code should look like this:

 void display(){ glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,499,0,499); glMatrixMode(GL_MODELVIEW); glColor3f(1,0,0); drawhouse(); glFlush(); glColor3f(0,0,1); glPushMatrix(); glTranslatef(0.5 ,0.5,0.5); glRotatef(45,1,1,1); glTranslatef(-0.5 ,-0.5,-0.5); drawhouse(); glPopMatrix(); glFlush(); } 

EDIT: Even (or because) you are afraid of matrices, I suggest you read some introductory materials about vector and matrix operations and transforms. And you should also read some OpenGL introductory materials to really understand how this works, especially the principle of the state machine.

+2
source

All Articles