OpenGL rotation in 2D
I have a simple OpenGL application, which displays a line. I store x1, y1, x2
and y2
in global variables.
The rotation function uses the feedback
functionality, discussed here and the translation to origin method, suggested here. It's intended to rotate a line around it's center.
Here's the code:
void rotate( float theta )
{
GLfloat* buff = new GLfloat[5];
glFeedbackBuffer( 5, GL_2D, buff );
glRenderMode( GL_FEEDBACK );
int center_x = x1 + ( x2 - x1 )/2;
开发者_Go百科 int center_y = y1 + ( y2 - y1 )/2;
glPushMatrix();
glTranslatef( -center_x, -center_y, 0 );
glRotatef( theta, 0, 0, 1 );
glTranslatef( center_x, center_y, 0 );
line();
glPopMatrix();
x1 = (int)buff[1];
y1 = (int)buff[2];
x2 = (int)buff[3];
y2 = (int)buff[4];
delete[] buff;
glutPostRedisplay();
}
However, the two translations seem to have little effect - the line still rotates around the lower-left corner of the window. In addition, the line gets clipped if it doesn't fit on the visible surface ( this doesn't happen with the translations commented out - the line simply refuses to move if it would fall outside the visible surface ).
Why doesn't this code work ? How do I rotate a line around it's center ( or any arbitrary point ) in 2D ?
Looks to me like you're translating in the wrong direction and the origin is being placed outside your viewport in the lower-left. You want to move the origin to the point you want to translate around--so if the origin is in the lower-left, you need to translate +center_x, +center_y. Rotate, translate back (-center_x, -center_y), then draw.
精彩评论