[英]GLUT OpenGL glRotatef
我一直在嘗試使用OpenGL,GLUT和C ++創建一個非常簡單的小行星游戲。
我無法弄清楚為什么會發生這種情況,但是在按鍵“ 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;
}
OpenGL以相反的順序應用矩陣。 換句話說,如果要旋轉然后平移,則需要在 glTranslatef
之后調用glRotatef
。 最好的方法是顯式存儲當前旋轉,而不僅僅是對glRotatef
進行一系列調用:
float rotation = 0.0;
void display() {
// ...
glPushMatrix();
glTranslatef(posX, posY, posZ);
glRotatef(rotation, 0.0f, 0.0f, 1.0f);
// Rewrite triangle vertex coordinates to be centered at (0, 0)
glPopMatrix();
// ...
}
void keyboard(unsigned char key, int x, int y) {
switch(key) {
// ...
case 'a':
std::cout << "rotate left" << std::endl;
rotation += 5.0f;
break;
case 'd':
std::cout << "rotate right" << std::endl;
rotation -= 5.0f;
break;
}
// ...
}
通常,您只應在繪圖例程中調用OpenGL函數。
由於將旋轉應用於原點,因此應串聯三個轉換:
1.首先,在原點上平移三角形
2.然后應用旋轉
3.之后,您將第一個平移反向,以便將其放回原始位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.