使用OpenGL固定功能旋转和平移2D图像

Rotating and translating a 2D image with OpenGL fixed function

本文关键字:2D 图像 旋转 OpenGL 功能 使用      更新时间:2023-10-16

我的代码在2D四边形上绘制了一个纹理,应该进行平移、旋转和缩放:

double width = ... //window width
double height = ... //window height
double imagewidth = ... 
double imageheight = ...
vec2 usertranslation = ... //additional translation in x,y direction from user input
double rot_angle = ... //rotation angle from user input
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, 0.0, height, 0.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// translate to the top center of the image and add user input translation
double transx = (width - imagewidth) / 2 + usertranslation.x;
double transy = height - imageheight + usertranslation.y;
glTranslatef(transx, transy, 0);
//this currently rotates around the center of the image, but what I need
//is to rotate the image around the center of the window. 
glTranslatef(imagewidth / 2, imageheight / 2, 0);
glRotatef(rot_angle, 0, 0, 1.0);
glTranslatef(-imagewidth / 2, -imageheight / 2, 0);
//bind the texture and draw the quad
drawTexturedQuad(); 

现在我的问题是,我需要改变什么才能让图像始终围绕窗口的中心点旋转。我已经尝试过这样的轮换:

glTranslatef(imagewidth / 2, imageheight - usertranslation.y - height, 0);
glRotatef(rot_angle, 0, 0, 1.0);
glTranslatef(-imagewidth  / 2, -(imageheight - usertranslation.y - height), 0);

但是,如果图像旋转180度(图像在平移时沿opsite方向移动),我会得到一个倒置的自上而下的平移。

要围绕屏幕中心(0,0)旋转,您可以根据以下公式更改实体的位置:

x=x*cos(角度)-y*sin(角度)
y=x*sin(角度)-y*cos(角度)

其中x和y是实体的位置,角度是旋转角度。如果要在旋转后面对同一点(如旋转中心),则还必须围绕其中心以负角度旋转实体。这与旋转矩阵使用的相同,但

如果要绕特定点旋转,则必须使用相对于该点的坐标。这很容易,只需减去实体坐标的中心点坐标,进行旋转并将中心坐标添加到新位置。这很重要,因为你是相对于另一个点而不是中心的,这就是矢量的工作方式。