Vahid Hallaji
Vahid Hallaji

Reputation: 7447

How can I translate only one object of the scene in an OpenGL?

I have a wall pattern DrawWall and an airplane DrawAirplane in my OpenGL game. How can I push and pop the current matrix and translate only the wall in the scene?

I expect the airplane to be fixed.

private: void DrawWall(){
    glPushMatrix(); 
    glBegin(GL_POLYGON); 
    LeftWallPattern();
    glEnd();
    glBegin(GL_POLYGON);
    RightWallPattern();
    glEnd();
    glPopMatrix();
}

private: void DrawAirplane(){ 
    glPushMatrix(); 
    glBegin(GL_LINE_LOOP);
    //...
    glEnd();
    glPopMatrix();
}

public: void Display(){
    glClear(GL_COLOR_BUFFER_BIT);
    glTranslatef(0, -0.02, 0);
    DrawWall();
    DrawAirplane();
    glFlush();
}

Upvotes: 0

Views: 6454

Answers (2)

beaker
beaker

Reputation: 16791

A few things to expand on what Jesus was saying.

When drawing the airplane you don't want to apply any transformations to it, so you need to have the identity matrix loaded:

Push the current modelview matrix
Load the identity matrix <=== this is the step you're missing
Draw the airplane
Pop the modelview matrix

When drawing the wall you want the current transformations to apply, so you do not push the current matrix or else you've wiped out all of the translations you've built up.

Remove the Push/Pop operations from DrawWall()

At some point in your initialization, before Display is called for the first time, you need to set the modelview matrix to the identity matrix. For each subsequent call to Display, -0.02 will then be added to your translation in the y-direction.

Upvotes: 1

Jesus Ramos
Jesus Ramos

Reputation: 23268

Use glPushMatrix() to push the current matrix, do glTranslate and draw the wall, then glPopMatrix() and draw the plane. This should only translate the wall. The problem is you seem to be doing the translate in display instead of in DrawWall where it should be.

Upvotes: 2

Related Questions