我一直在尝试使用OpenGL,GLUT和C++创建一个非常简单的小行星游戏。GLUT OpenGL glRotatef
我无法弄清楚为什么会发生这种情况,但在按键“a”或“d”上,我希望三角形沿Z轴旋转。问题是,当按下这些键时,glRotatef()围绕屏幕的0,0位置或左下角旋转。我已经尝试了许多不同的方法,教程和我要链接的代码是最好的运行示例。
我确定我错过了一些东西,但我无法让三角形围绕自身旋转而不是屏幕的原点。
#include <iostream>
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
//g++ -o game.exe -Wall main.cpp glut32.lib -lopengl32 -lglu32 -static-libgcc -static-libstdc++
float posX = 0, posY = 0, posZ = 0;
int width = 100, height = 100;
int triangle_height = 5, triangle_width = 4;
float move_unit = 1;
void display() {
std::cout << "display" << std::endl;
//glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glTranslatef(posX, posY, posZ);
glColor3f(1,1,1); //sets the current color to white
glBegin(GL_TRIANGLES); //tells openGL we are going to draw some triangles
//glTranslatef(0, 0, 0);
glVertex2i(width/2 , height/2); //specifies the first vertext of our triangle
glVertex2i(width/2 + triangle_width , height/2); //specifies the second vertext of our triangle
glVertex2i(width/2 , height/2 + triangle_height); //specifies the third vertext of our triangle
glEnd(); //tells openGL that we are done drawing
glPopMatrix();
glutSwapBuffers();
glFlush();
}
void keyboard(unsigned char key, int x, int y) {
switch(key) {
case 'w':
std::cout << "moving up" << std::endl;
posY += move_unit;
break;
case 's':
std::cout << "moving down" << std::endl;
posY -= move_unit;
break;
case 'a':
std::cout << "rotate left" << std::endl;
glRotatef(5.0f, 0.0f, 0.0f, 1.0f);
break;
case 'd':
std::cout << "rotate right" << std::endl;
glRotatef(5.0f, 0.0f, 0.0f, -1.0f);
break;
}
glutPostRedisplay();
}
void init() {
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION); //changes the current matrix to the projection matrix
glLoadIdentity();
gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char **argv) {
glutInit(&argc, argv); //inits the GLUT framework
glutInitWindowSize(800, 600);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutCreateWindow("Eric's Game");
init();
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMainLoop(); // Infinite event loop
return 0;
}
那么你的建议完美工作,使用旋转变量就像是一个“唔”的时刻,哈哈。但是,如何将对象置于屏幕上呢?这是我的问题,我希望三角形在屏幕上居中,而不是左下角。 \t \t \t 'glVertex2i(0,0); ' 'glVertex2i(0 + triangle_width,0);' 'glVertex2i(0,0 + triangle_height);' – neurosnap
将posX和posY初始化为屏幕宽度/高度的一半,你应该很好。 – godel9