我想做一个小的应用程序,让我可以移动三角形的顶部/底部左/右。
而当我按w -〉向上旋转并向上移动时,s =〉向下旋转并向下移动,d -〉向右旋转并向右移动,a -〉向左旋转并向左移动。
下面是我代码:
# include <GL/glut.h> // (or others, depending on the system in use)
float xpoint1 = 0.0f;
float xpoint2 = 50.0f;
float xpoint3 = 25.0f;
float ypoint1 = 0.0f, ypoint2 = 0.0f, ypoint3 = 20.0f;
double direction = 0.0;
void Keys(unsigned char key, int x, int y) {
if (key == 'a') {
if (xpoint1 != 0) {
xpoint1 -= 1.0f;
xpoint2 -= 1.0f;
xpoint3 -= 1.0f;
direction = 90.0;
}
}
else if (key == 'd') {
if (xpoint2 != 200) {
xpoint1 += 1.0f;
xpoint2 += 1.0f;
xpoint3 += 1.0f;
direction = 270.0;
}
}
else if (key == 'w') {
if (ypoint3 != 150) {
ypoint1 += 1.0f;
ypoint2 += 1.0f;
ypoint3 += 1.0f;
direction = 0.0;
}
}
else if (key == 's') {
if (ypoint3 != 0) {
ypoint1 -= 1.0f;
ypoint2 -= 1.0f;
ypoint3 -= 1.0f;
direction = 180.0;
}
}
glutPostRedisplay();
}
void resizeChange(int w, int h) {
glClearColor(1.0, 1.0, 1.0, 0.0); // Set display-window color to white.
glMatrixMode(GL_PROJECTION); // Set projection parameters.
glLoadIdentity();
gluOrtho2D(0.0, 200.0, 0.0, 150.0);
glViewport(0, 0, w, h);
glMatrixMode(GL_MODELVIEW);
}
void lineSegment(void)
{
glClear(GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f(0.0, 0.4, 0.2); // Set line segment color to green.
//gluLookAt(0.0, 0.0, 5.0,
// 0.0, 0.0,0.0,
// 0.0, 1.0, 0.0
//);
glLoadIdentity();
glRotated(direction, 0.0, 0.0, 1.0);
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(xpoint1, ypoint1);
glColor3f(0.0, 1.0, 0.0);
glVertex2f(xpoint2, ypoint2);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(xpoint3, ypoint3);
glEnd();
//degree += 1.0;
glFlush(); // Process all OpenGL routines as quickly as possible.
//glutSwapBuffers();
}
void main(int argc, char**argv)
{
glutInit(&argc, argv); // Initialize GLUT.
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Set display mode.
glutInitWindowPosition(50, 100); // Set top-left display-window position.
glutInitWindowSize(600, 600); // Set display-window width and height.
glutCreateWindow("An Example OpenGL Program"); // Create display window.
glutDisplayFunc(lineSegment); // Send graphics to display window.
glutReshapeFunc(resizeChange);
//glutIdleFunc(lineSegment);
glutKeyboardFunc(Keys);
glutMainLoop(); // Display everything and wait.
}
问题是当我试图改变三角形的方向时,它消失了?!,有什么问题?!
1条答案
按热度按时间7rfyedvj1#
glRotated
围绕(0,0)旋转。实际上,将三角形旋转到看不见的地方。您必须先旋转三角形,然后将其移动到它在世界中的位置。不要更改顶点坐标,但添加一个平移矩阵glTranslate
:第一个