# How to move the generated polygon horizontally in openGL?

I am trying to develop a small ball game in OpenGL where rectangular bars of random height is generated and moved towards left and there is a ball which should be moved up and down(like jump action) whenever mouse left button is pressed. I am generating the polygon pattern but the problem is the movement

What is the best way to move the rectangles(of random height) horizontally? (or any generated pattern preferably polygon from right to left.)

I tried code below for movement of a single rectangle but i am getting a blank screen

void move_polygon()
{
int px,py;
px=randr(50,100);
py=randr(100,600);
float r,g,b;
r=(float)(rand()%10);
g=(float)(rand()%10);
b=(float)(rand()%10);
float rf=r/10,gf=g/10,bf=b/10;
glColor3f(rf,gf,bf);
for(int pos=800;pos<=0;pos-=10)
{
Sleep(200);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f(pos,0);
glVertex2f(pos,py);
glVertex2f(px+pos,py);
glVertex2f(px+pos,0);
glEnd();
glFlush();
Sleep(100);
}
}


Lets say you have your rectangles at a certain coordinate to the right (x,y). Then, an easy way is that on each rendering call you reduce the x coordinate of the rectangles by some dx.

#define dx 0.1

render(){
draw_rectangle(xrec, yrec, zrec);
xrec -= dx;
}


If you have a logic loop separated from the rendering loop, then it is better to do the decrement in the logic loop.

EDIT: For the example you have added, it would be something like this

// global variable
int pos = somevalue;

// move function
void move_polygon(int pos){
int px,py;
px=randr(50,100);
py=randr(100,600);
float r,g,b;
r=(float)(rand()%10);
g=(float)(rand()%10);
b=(float)(rand()%10);
float rf=r/10,gf=g/10,bf=b/10;
glColor3f(rf,gf,bf);
Sleep(200);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f(pos,0);
glVertex2f(pos,py);
glVertex2f(px+pos,py);
glVertex2f(px+pos,0);
glEnd();
glFlush();
Sleep(100);
}

// render function, decrement position here
void render_loop(){
// ... other code
move_polygons(pos--);
// ... other code
}


The reason why you were getting a blank screen is because you are updating all the rectangle positions in one draw call, therefore the rectangle passes before you can even see it. You have to draw it once for each new position, try the code I showed you.

• please check the code now added, i tried to move single rectangle from left to right but i am getting a blank screen – snk Jul 16 '15 at 13:44
• I have seen the updated code. Are you using single or double render buffer ? If you put a full compilable code I could test it. – Cristobal Navarro Jul 20 '15 at 19:17