Question

here is my code.

#include "stdafx.h"
#include <GL/glut.h>
#include <gl/GL.h>
#include <gl/GLU.h>
#include <math.h>
#define pi 3.14;
float x=.05; //translation parameter
float angle=3;
void reshape(int w, int h)
{
    if(h==0) h=1;
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,w,0,h,-1,1);

}
void display(void)
{
    glDepthMask(GL_TRUE);
    glClear(GL_COLOR_BUFFER_BIT);
    glTranslatef(x,0.0f,0.0f);  
    glBegin(GL_POLYGON);
    glVertex2f(10,10);
    glVertex2f(30,20);
    glVertex2f(30,30);
    glVertex2f(10,30);
    glEnd();    

        x=x+.0000005;
        if(x>600)
        x=0;

    glFlush();
    glutSwapBuffers();
}

int main(int argc, char** argv)
{
    glutInit(&argc , argv);
    glutInitDisplayMode(GLUT_DEPTH|GLUT_RGB|GLUT_DOUBLE);
    glutInitWindowSize(640,480);
    glutCreateWindow("my window");
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutIdleFunc(display);
    glutMainLoop();
    return(0);
}

the problem with this code is, the rectangle is translated to infinity. I want it translated to maximum window size and again return to starting of window.In this code I am checking x>600 (assumes 600 as maximum) ,if so x is changed to 0. But it wont working.

Was it helpful?

Solution

You need to call glPushMatrix before glTranslatef and glPopMatrix after glEnd.

glTranslatef doesn't set the transformation, it appends it to the existing transformation. What you need to do is push the existing matrix on the matrix stack, apply the transformation, then restore the original. That way the translations don't accumulate.

OTHER TIPS

You are not resetting the ModelView matrix. The GL transformation functions multiply the current modelview matrix by the transformation matrix, so that the transformations accumulate. Every time your display function is called, you move the rectanlge by the amout of x - relative to where it was lats frame -. Thus, your logic of changing x is actually only modulating the speed with wich the object moves.

Put a glLoadIdentiy() at the start of display(). It will reset the matrix to identity, undoing all former transformations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top