在OpenGL中移动一个简单的形状(形状在数据结构中)



当我按下向左箭头键时,我想让身体(正方形)向左移动。不幸的是,它在数据结构中,我不知道该在void SpecialKeys(int key, int x, int y)部分放什么来移动它。

#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)
{
}
}**

您只需要调用glTranslatef。

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

在OpenGL中,通常有两种移动对象的方法:glMatrix或直接操作变量。

OpenGL提供了函数CCD_ 2。如果你知道矩阵,它在三维空间中的作用是将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;
}

最新更新