Rotating a spaceship with glRotatef() and glTranslatef()

I am having trouble simplifying my rotations and translations. The spaceship motion code is below:

glPushMatrix();
glLoadIdentity();
glRotatef(angle.z, 0.0, 0.0, 1.0);
glTranslatef( 0.0, velocity.y, 0.0);
glGetFloatv(GL_MODELVIEW_MATRIX, matrix);
glPopMatrix();

translate.x += matrix[12] * timeStep;
translate.y += matrix[13] * timeStep;
translate.z += matrix[14] * timeStep;

glPushMatrix();
glTranslatef( translate.x, translate.y,-1.0);
glRotatef(angle.z, 0.0, 0.0, 1.0);
drawPolygons();
glPopMatrix();

Is it possible to do this with just glRotate and glTranslate and no Matrix[]? I have tried a different way with the code below but it does not rotate correctly.

glTranslatef(2.0, 0.0, 0.0);
glRotatef(angleDegreesRight.z, 0.0, 0.0, 1.0);
glTranslatef(-2.0, 0.0, 0.0);
glTranslatef(-2.0, 0.0, 0.0);
glRotatef(angleDegreesLeft.z, 0.0, 0.0, 1.0);
glTranslatef(2.0, 0.0, 0.0);

Any help is appreciated.

1 Like

Realistically, no. I mean, you could just remove the glLoadIdentity(), glPushMatrix() and glPopMatrix() calls, so the model-view matrix always contains the spaceship transformation.But you’re better off either using GLM or writing your own matrix code.

E.g. in this case, you can update translate with

    double a = angle.z * M_PI/180; // radians
    double d = velocity * timeStep;
    translate.x += -sin(a) * d;
    translate.y +=  cos(a) * d;
1 Like

That is so cool! I have seen other algorithms on the SIGGRAPH website but this is better. I never thought to use a scalar velocity that always works on the linear y axis. Okay I have one more question. How do I keep the spaceship stationary while the world moves around it?

1 Like

Invert the transformation and apply it to everything except the spaceship.

If you want to use the legacy OpenGL matrix functions, all of the primitive matrix operations are trivial to invert.

glTranslate(x,y,z) -> glTranslate(-x,-y,-z)
glRotate(a,x,y,z) -> glRotate(-a,x,y,z)
glScale(x,y,z) -> glScale(1/x,1/y,1/z)

For composition, (A.B)^-1 = (B^-1).(A^-1), i.e. invert the individual matrices and apply them in the opposite order.

Awesome I got it working! I have been using OpenGL for a while now and I never understood how the motion algorithms worked. Now it makes sense. Thanks for the kind answers.