Using the glrotatef()
function rotates the figure by a specified angle with respect to the origin. How do I rotate the same figure with respect to another point without making use of 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's a screenshot for what happens. http://postimage.org/image/q81bhupw/
Basically:
If you want to rotate around P
, translate by -P
(so that P
moves to the origin), then perform your rotation, then translate by P
(so that the origin moves back to P
).
glTranslatef(P.x, P.y, P.z);
glRotatef(angle, A.x, A.y, A.z);
glTranslatef(-P.x, -P.y, -P.z);
(Note: This is in "reverse order" because the last transformation added is the first one applied, under OpenGL rules.)
So in your setup 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();
}
Your code has quite a few problems. First, you have to apply the transformation on the moelview matrix and not the projection matrix. Second, you should wrap you transformation into a glPushMatrix/glPopMatrix
, otherwise, they aren't reversed when rendering the next frame. Third, you should apply gluOrtho2d
on the projection matrix and not the modelview matrx.
In accordance to John's answer your code should look like:
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 to read some introductory material on vector and matrix operations and transformations. And you should also read some introductory material on OpenGL, to really understand how it works, especially the state machine principle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With