我一直在嘗試使用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