Search code examples
openglgraphicsglut

gluLookAt with cone not showing expected result


I am trying to look at a cone in 3D, for which I used gluLookAt. I draw a cone in the middle of the screen at pos (250, 250, 0) and then look at it with a camera above the origin looking at the middle. The output is a circle, contrary to the cone I expected to see. It seems the camera is instead at point (250,250,0) also, but it is specified in gluLookAt it should be above the origin. What am I overlooking here?

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

    glTranslatef(250, 250, 0);
    glutSolidCone(30, 10, 20, 20);
    glTranslatef(-250, -250, 0);

    gluLookAt(0, 0, 100, 250, 250, 0, 0, 0, 1);

    glFlush();
    glutSwapBuffers();

}


int main(int argc, char **argv)
{
    float x, y;
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(500, 500);
    glutCreateWindow("Cone");
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutKeyboardFunc(keyboard);
    glutMotionFunc(drag);
    glutMouseFunc(click);
    glutSpecialFunc(catchKey);



    glEnable(GL_DEPTH_TEST);

    glutMainLoop();         //calls do_one_simulation_step, keyboard, display, drag, reshape
    return 0;
}

Solution

  • A few issues:

    • Set your camera matrix, then draw. The way you have it now your gluLookAt() does nothing useful.
    • The default identity projection matrix probably isn't what you want. Set a real perspective transform using gluPerspective() or glFrustum().
    • Your gluLookAt() eye/center coords were a bit wonky; I've put the eye at (50, 50, 50) and set it to look at the origin.

    All together:

    cone screenshot

    #include <GL/glut.h>
    #include <GL/GLU.h>
    
    void display( void )
    {
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    
        glMatrixMode( GL_PROJECTION );
        glLoadIdentity();
        double w = glutGet( GLUT_WINDOW_WIDTH );
        double h = glutGet( GLUT_WINDOW_HEIGHT );
        gluPerspective( 60.0, w / h, 1.0, 1000.0 );
    
        glMatrixMode( GL_MODELVIEW );
        glLoadIdentity();
        gluLookAt( 50, 50, 50, 0, 0, 0, 0, 0, 1 );
    
        glutWireCone( 10, 30, 20, 20 );
    
        glutSwapBuffers();
    }
    
    int main( int argc, char **argv )
    {
        glutInit( &argc, argv );
        glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
        glutInitWindowSize( 500, 500 );
        glutCreateWindow( "Cone" );
        glutDisplayFunc( display );
        glEnable( GL_DEPTH_TEST );
        glutMainLoop();
        return 0;
    }