在opengl中将一个形状转换为另一个形状

translating a shape inside another one in opengl

本文关键字:一个 转换 另一个 opengl      更新时间:2023-10-16

我希望能够通过按下键盘上的一些键将较小的立方体转换为较大的立方体。

以下是我完成这项工作的尝试:

initiary x=0,y=0,z=0,origin=0,并且在范围内是全局的

void key_board(unsigned char key, int xx, int yy){//call back func for the glutKeyboardFunc
      switch (key){
        case 'x':
          if(origin >= 0 && opposite >= 0 ){
            opposite = 1 - size -origin;
            x +=opposite; 
            break;
          }
        case 'y':
          if(origin >= 0 && opposite >= 0 ){
            opposite = 1 - size -origin;
            y +=opposite; 
            break;
          }
        case 'z':
          if(origin >= 0 && opposite >= 0 ){
            opposite = 1 - size -origin;
            z +=opposite; 
            break;
          }
      }
}
void solid_cube(double size){//this is the cube i would like to translate within the larger one,only perpendicular translation to the wall of bigger box are allowed
    glPushMatrix();
    glLineWidth(1.7f);
    glShadeModel(GL_SMOOTH);
    glColor3f(1.0f,0.0f,1.0f);
    glTranslatef(x, y, z);
    glutSolidCube(size);
  }
void display(){//display call back func
    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glShadeModel(GL_SMOOTH);
    gluPerspective(30.0, 4.0/3.0, 0.1f, 10.0);
    glFrustum(3.0, 5.0, 3.0, 3.0, 5.0, 10.0);
    gluLookAt(2.0,0,2.0,0.0,0.0,0.0,1.0,1.0,1.0);
    glLineWidth(1.7f);
    glColor3f(0.0f,0.0f,1.0f);
    glutWireCube(1.0); 
    solid_cube(0.3);//smaller cube to be moved around
    glutSwapBuffers();

}

此代码中存在许多问题:

  1. 在没有相应的CCD_ 2的情况下调用CCD_。顾名思义,这些调用管理一个矩阵堆栈。每个push操作都必须与pop运算相匹配,否则堆栈将快速溢出。要解决此问题,请在solid_cube()函数末尾添加丢失的调用:

    ...
    glutSolidCube(size);
    glPopMatrix();
    
  2. gluPerspective()glFrustum()都被调用。这两个呼吁都有相同的目的。glFrustum()支持设置一个通用的视锥。gluPerspective()glFrustum()的简化便利接口,仅支持对称视锥。这两个调用都将新指定的投影矩阵与当前矩阵相乘。所以,如果你两者都有,你会得到一个投影的投影,这……不是你想要的。您可以简单地删除此代码中的glFrustum()调用。

  3. 投影矩阵通常应设置为glPushMatrix()0矩阵模式。因此转换设置调用的顺序应该是:

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(30.0, 4.0/3.0, 0.1f, 10.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(2.0,0,2.0,0.0,0.0,0.0,1.0,1.0,1.0);
    

    这只需要一次,所以您也可以将其移动到设置代码中,而不是在每次重新显示时重复。

gluLookAt()的参数看起来也有些不同寻常。它们并不违法,但您可能仍然需要仔细检查文档,以验证它是否真的是您想要的。

相关文章: