PDA

View Full Version : Trying to move one object keeping the environment still



Beginner3452
05-01-2015, 01:13 AM
Hello guys,
I am trying to move the car(The rectangle at the bottom) keeping the nearby environment(the roads) still.But the result i am getting is that the whole window is moving.I just want the car to move.I searched on google and have gone through many similar threads but i still cant seem to get it to work.Help is appreciated.Here is my code:


#include<stdio.h>
#include<glut.h>

int i,j;

void init()
{
glClearColor(1.0,1.0,1.0,1.0);
glPointSize(5.0);
gluOrtho2D(0.0,600.0,0.0,600.0);
}

void draw_env()
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_LINES); //Drawing the Roads
glVertex2f(250.0,0.0);
glVertex2f(250.0,250.0);

glVertex2f(350.0,0.0);
glVertex2f(350.0,250.0);

glVertex2f(0.0,250.0);
glVertex2f(250.0,250.0);

glVertex2f(0.0,350.0);
glVertex2f(250.0,350.0);

glVertex2f(600.0,250.0);
glVertex2f(350.0,250.0);

glVertex2f(600.0,350.0);
glVertex2f(350.0,350.0);

glVertex2f(350.0,600.0);
glVertex2f(350.0,350.0);

glVertex2f(250.0,350.0);
glVertex2f(250.0,600.0);
glEnd();

glFlush();
}

void draw_car()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(270.0,0.0);
glVertex2f(270.0,60.0);
glVertex2f(310.0,60.0);
glVertex2f(310.0,0.0);
glEnd();

glutPostRedisplay();
glFlush();
}

void display(void)
{
draw_env();
for(j=0;j<8000000;j++) {} //loop to cause delay
glTranslatef(0.0,1.0,0.0);
draw_car();
}

void main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowPosition(50,50);
glutInitWindowSize(600,600);
glutCreateWindow("Traffic Signal Demonstration");
glutDisplayFunc(display);
init();
glutMainLoop();
}

IonutCava
05-01-2015, 05:20 AM
Hint: There's a famous expression floating everywhere: "OpenGL is a huge state machine".
Answer: You are modifying your modelview matrix with translate, but not resetting it every frame. So your environment will have the same transforms applied but with a 1 frame delay. Plenty of tutorials out there explaining this.