Search code examples
openglglut

OpenGl scale + translate not working


I have the following problem in Opengl (Glut). I have set the camera posistion to (posx,posy,posz) with gluLookAt, and I need to display an scaled cube in the position (posx+offsetx,posy+offsety,posz+offsetz). I'm doing the following:

glPushMatrix(); 
glColor3f(0.6f,0.6f,0.6f);
glTranslatef( posx+offsetx, posy+offsety, posz+offsetz );
glScalef(20,20,60);
glutSolidCube(1.0);
glPopMatrix(); 

However the cube does not appear at the right location. I have tried this also by shifting the order of glScalef and glTranslatef (I read this in a similar question). But it did not work either.


Solution

  • A few things - are you switching between modes via glMatrixMode?

    Are you calling glLoadIdentity() after switching?

    I assume you're clearing the depth (if enabled) and color buffers each render?

    I don't personally tend to push/pop the matrix unless I'm calling into something third party and I want to maintain my current state... but no harm done.

    gluLookAt is really just a transformation itself so it may not be doing what you expect. I assume you have a rendering function that looks like this:

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(posx, posy, posz, // where the eye is located
            0.0, 0.0, 0.0, // where the eye is looking
            0.0, 1.0, 0.0); // which direction is "up"
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    
    glPushMatrix(); 
    glColor3f(0.6f,0.6f,0.6f);
    glTranslatef( posx+offsetx, posy+offsety, posz+offsetz );
    glScalef(20,20,60);
    glutSolidCube(1.0);
    glPopMatrix();
    
    glutSwapBuffers();
    

    And that you started up using something like this:

    glutInit(&argc, argv);                                    
    glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH );
    glutInitWindowSize(600,400);                  
    glutCreateWindow("Test");                              
    glutDisplayFunc(displayFunctionName);
    glutKeyboardFunc(keyboardFunctionName);
    glutMainLoop();
    

    This is all using older-style OpenGL direct calls (sometimes called fixed function pipeline) mode which is fine (especially when starting out) but you may want to read up on shaders (GLSL) and how the pipeline works now since this stuff was deprecated in 2004.

    Otherwise a more complete code example including your camera positioning code and values plus a screenshot and expected result could be helpful.