2014-02-09 18 views
0

我想在按下左箭头键时使主体(方形)向左移动。不幸的是,它在数据结构中,我不知道要在void SpecialKeys(int key, int x, int y)部分放置什么。在OpenGL中进行简单的形状移动(形状处于数据结构中)

#include <vector> 
#include <time.h> 

using namespace std; 

#include "Glut_Setup.h" 



**struct Vertex 
{ 
float x,y,z; 
}; 
Vertex Body []= 
{ 
(-0.5, -2, 0), 
(0.5, -2, 0), 
(0.5, -3, 0), 
(-0.5, -3, 0) 
};** 




void GameScene() 
{ 
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 





glBegin(GL_QUADS); 
glColor3f(0.0, 0.0, 1.0); 
glVertex3f(-0.5, -2, 0); 
glVertex3f(0.5, -2, 0); 
glVertex3f(0.5, -3, 0); 
glVertex3f(-0.5, -3, 0); 
glEnd(); 







glutSwapBuffers(); 
} 

void Keys(unsigned char key, int x, int y) 
{ 
switch(key) 
{ 

} 
} 

**void SpecialKeys(int key, int x, int y) 
{ 
switch(key) 
{ 
} 
}** 
+0

抱歉,这是非常基本的OpenGL您几乎可以从任何书籍或教程网站获得知识。你正在寻找的东西叫做模型 - 视图矩阵。这个想法是(在固定管道的opengl中)你将一个矩阵推到与你的所有顶点相乘的矩阵栈上。然后你可以通过调用例如glTranslate。例如看这个:http://nehe.gamedev.net/tutorial/rotation/14001/(但使用glTranslate而不是glRotate)。现代opengl的教程网站在这里:http://www.opengl-tutorial.org/ –

+0

我上面的评论提到了一种新的和新的方式在opengl中做事。因为你显然刚开始使用opengl,所以我强烈建议直接去“现代”。 –

回答

1

你只需要调用glTranslatef。

glClear(GL_DEPTH_BUFFER_BIT); 
glPushMatrix(); 
glMatrixMode(GL_MODELVIEW); 
glLoadIdentity(); 
glTranslatef(delta_x, delta_y, -100.f); 
//draw here 
glPopMatrix(); 
1

在OpenGL中,通常有两种方式来移动一个对象:glMatrices或直接操作变量。

OpenGL提供了功能glTranslatef()。如果您了解矩阵,那么在3D空间中做的是将tx or ty or tz添加到您的向量中的相应组件。在OpenGL中,这种情况发生在幕后所以为了使用glTranslate对象,你会做以下几点:

glPushMatrix(); 
glTranslatef(1.0, 0, 0); 

//drawing code 

glPopMatrix(); 

你画将由矩阵相乘来执行转换顶点的每一个。第二种方法是直接操作对象的组件。为了做到这一点,你需要使用你的绘制代码的变量,如:

glVertex3f(vx, vy, vz); 
glVertex3f(vx + 1.0, vy - 1.0, vz); // not a real example, just get the idea 

然后,当你想要移动在正x轴的顶点,只需将量添加到VX:

vx+=0.5; 

下一次绘制对象时,它将使用vx的新值。

一个简单的谷歌搜索可以让你为如何对按键输入响应的答案: http://www.opengl.org/documentation/specs/glut/spec3/node54.html 但不管怎么说,这是它如何工作的一个想法:

switch(key) 
{ 
case GLUT_KEY_RIGHT: 
vx++; 
break; 
}