我一直在研究如何围绕原点和用户指定的坐标旋转三角形。任务是旋转相同的三角形(相同的尺寸)。到目前为止,我可以在原点做。但是当它在用户指定的坐标旋转时,三角形的形状会变大。
#include<GL/glut.h>
#include<stdio.h>
int x,y;
int where_to_rotate=2;
void draw_pixel(float x1,float y1)
{
//glColor3f(0.0,0.0,1.0);
glPointSize(5.0);
glBegin(GL_POINTS);
glVertex2f(x1,y1);
glEnd();
}
void triangle(int x,int y)
{
glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON); // this is what is bothering me.I have to maintain the same triangle even at user specified coordinates
glVertex2f(x,y);
glVertex2f(x+50,0);
glVertex2f(0,y+50);
glEnd();
}
float rotate_angle=0.0;
float translate_x=0.0,translate_y=0.0;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glColor3f(1,1,1);
draw_pixel(0.0,0.0);
if(where_to_rotate==1) //Rotate Around origin
{
translate_x=0.0;
translate_y=0.0;
rotate_angle+=.2;
draw_pixel(0.0,0.0);
}
if(where_to_rotate==2) //Rotate Around Fixed Point
{
translate_x=x;
translate_y=y;
rotate_angle+=.2;
glColor3f(0.0,0.0,1.0);
draw_pixel(x,y);
}
glTranslatef(translate_x,translate_y,0.0); //works fine for origin
glRotatef(rotate_angle,0.0,0.0,1.0);
glTranslatef(-translate_x,-translate_y,0.0);
triangle(translate_x,translate_y);
glutPostRedisplay();
glutSwapBuffers();
}
void myInit()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-800.0, 800.0, -800.0, 800.0);
glMatrixMode(GL_MODELVIEW);
}
void rotateMenu (int option)
{
if(option==1)
where_to_rotate=1;
if(option==2)
where_to_rotate=2;
if(option==3)
where_to_rotate=3;
}
int main(int argc, char **argv)
{
printf( "Enter Fixed Points (x,y) for Rotation: \n");
scanf("%d %d", &x, &y);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(800, 800);
glutInitWindowPosition(0, 0);
glutCreateWindow("Create and Rotate Triangle");
myInit();
glutDisplayFunc(display);
glutCreateMenu(rotateMenu);
glutAddMenuEntry("Rotate around ORIGIN",1);
glutAddMenuEntry("Rotate around FIXED POINT",2);
glutAddMenuEntry("Stop Rotation",3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
}
最佳答案
在函数triangle
中,必须将平移应用于所有顶点坐标:
glVertex2f(x,y);
glVertex2f(x+50,y);
glVertex2f(x,y+50);
注意,设置模型矩阵和指定静态三角形几何体就足够了,并且
glTranslatef(-translate_x,-translate_y,0.0);
取消由triangle(translate_x,translate_y);
设置的平移如果希望三角形保持其位置并围绕固定点旋转,则必须这样做:
glTranslatef(translate_x, translate_y, 0.0);
glRotatef(rotate_angle, 0.0, 0.0, 1.0);
glTranslatef(-translate_x, -translate_y, 0.0);
triangle(0.0, 0.0);
说明:
矩阵堆栈上的顶部操作以这种方式变换三角形,使其原点为旋转点:
glTranslatef(-translate_x, -translate_y, 0.0);
第二个操作围绕当前原点旋转三角形
glRotatef(rotate_angle,0.0,0.0,1.0);
最后,旋转的三角形向后移动:
glTranslatef(translate_x, translate_y, 0.0);
另见OpenGL translation before and after a rotation
关于c - 在原点和用户指定的旋转点上,相对于其坐标保持相同的三角形?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49178444/