我试图在不使用glTranslate()的情况下翻译对象。我通过网络搜索并找到了一个函数glMultMatrixf()。我想用这个函数乘以我的翻译矩阵,但我无法完成它。我觉得我在逻辑上走的是正确的路径,但是这种方式甚至可以翻译一个对象吗?
我使用opengl和c ++编写了代码。这是代码:
#include <iostream>
#include <stdlib.h>
#include <math.h>
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
using namespace std;
float _angle = 0;
typedef GLfloat Matrix4x4 [4][4];
Matrix4x4 matTransl3D;
/* Construct the 4 x 4 identity matrix. */
void matrix4x4SetIdentity (Matrix4x4 matIdent4x4)
{
GLint row, col;
for (row = 0; row < 4; row++)
for (col = 0; col < 4 ; col++)
matIdent4x4 [row][col] = (row == col);
}
void translate3D (GLfloat tx, GLfloat ty, GLfloat tz)
{
/* Initialize translation matrix to identity. */
matrix4x4SetIdentity (matTransl3D);
matTransl3D [0][3] = tx;
matTransl3D [1][3] = ty;
matTransl3D [2][3] = tz;
}
void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 27: //Escape key
exit(0);
}
}
void initRendering()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
}
void handleResize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (float)w / (float)h, 1.0, 200.0);
}
void drawScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
translate3D(0.0f, 0.0f, -50.0f);
glMultMatrixf(*matTransl3D);
glBegin(GL_TRIANGLE_FAN); // draw triangle
glColor3f(1.0f,0.0f,0.0f); // set color to red
glVertex3f( 0.0f, 3.0f, 0.0f);
glColor3f(0.0f,1.0f,0.0f); // set color to green
glVertex3f(-5.0f, -5.0f, 5.0f);
glColor3f(1.0f,1.0f,0.0f); // set color to yellow
glVertex3f( 5.0f, -5.0f, 5.0f);
glColor3f(0.0f,0.0f,1.0f); // set color to blue
glVertex3f( 5.0f, -5.0f, -5.0f);
glColor3f(1.0f,1.0f,1.0f); // set color to white
glVertex3f( -5.0f, -5.0f, -5.0f);
glColor3f(0.0f,1.0f,0.0f); // set color to green
glVertex3f(-5.0f, -5.0f, 5.0f);
glEnd();
glBegin(GL_QUADS);
glColor3f(0.0f,1.0f,0.0f); // set color to green
glVertex3f(-5.0f, -5.0f, 5.0f);
glColor3f(1.0f,1.0f,1.0f); // set color to white
glVertex3f( -5.0f, -5.0f, -5.0f);
glColor3f(0.0f,0.0f,1.0f); // set color to blue
glVertex3f( 5.0f, -5.0f, -5.0f);
glColor3f(1.0f,1.0f,0.0f); // set color to yellow
glVertex3f( 5.0f, -5.0f, 5.0f);
glEnd();
glutSwapBuffers();
}
//Called every 25 milliseconds
void update(int value) {
_angle += 1.0f;
if (_angle > 360) {
_angle -= 360;
}
glutPostRedisplay();
glutTimerFunc(25, update, 0);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(400, 400);
glutCreateWindow("Translation 3d");
initRendering();
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutReshapeFunc(handleResize);
glutTimerFunc(25, update, 0);
glutMainLoop();
return 0;
}
答案 0 :(得分:11)
OpenGL将矩阵作为列主要,即索引是
0 4 8 c
1 5 9 d
2 6 a e
3 7 b f
但是,您要按照
的顺序索引翻译矩阵0 1 2 3
4 5 6 7
8 9 a b
c d e f