2014-02-09 49 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; 
}