简体   繁体   中英

Rotate the vertexes of a cube using a rotation matrix

I'm trying to rotate a cube's vertexes with a rotation matrix but whenever I run the program the cube just disappears.

I'm using a rotation matrix that was given to us in a lecture that rotates the cube's x coordinates.

double moveCubeX = 0;
float xRotationMatrix[9] = {1, 0, 0,
                            0, cos(moveCubeX), sin(moveCubeX),
                            0, -sin(moveCubeX), cos(moveCubeX) 
};

I'm adding to the moveCubeX variable with the 't' key on my keyboard

case 't':
    moveCubeX += 5;
    break;

And to do the matrix multiplication I'm using

glMultMatrixf();

However when I add this into my code when running it the cube has just disappeared. This is where I add in the glMultMatrixf() function.

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    gluLookAt(pan, 0, -g_fViewDistance, 
              pan, 0, -1,
              0, 1, 0);

    glRotatef(rotate_x, 1.0f, 0.0f, 0.0f);   //Rotate the camera
    glRotatef(rotate_y, 0.0f, 1.0f, 0.0f);   //Rotate the camera

    glMultMatrixf(xRotationMatrix);

I'm struggling to see where it is I have gone wrong.

OpenGL uses matrices of size 4x4. Therefore, your rotation matrix needs to be expanded to 4 rows and 4 columns, for a total of 16 elements:

float xRotationMatrix[16] = {1.0f, 0.0f, 0.0f, 0.0f,
                             0.0f, cos(moveCubeX), sin(moveCubeX), 0.0f,
                             0.0f, -sin(moveCubeX), cos(moveCubeX), 0.0f,
                             0.0f, 0.0f, 0.0f, 1.0f};

You will also need to be careful about the units for your angles. Since you add 5 to your angle every time the user presses a key, it looks like you're thinking in degrees. The standard cos() and sin() functions in C/C++ libraries expect the angle to be in radians.

In addition, it looks like your matrix is defined at a global level. If you do this, the elements will only be evaluated once at program startup. You will either have to make the matrix definition local to the display() , so that the matrix is re-evaluated each time you draw, or update the matrix every time the angle changes.

For the second option, you can update only the matrix elements that depend on the angle every time the angle changes. In the function that modifies moveCubeX , add:

xRotationMatrix[5] = cos(moveCubeX);
xRotationMatrix[6] = sin(moveCubeX);
xRotationMatrix[9] = -sin(moveCubeX);
xRotationMatrix[10] = cos(moveCubeX);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM