Search Projects

Friday, September 30, 2016

Rolling Blocks Simple Opengl Program

Rolling blocks is an simple opengl program in c written with the help of OpenGL API. It used the primitive function of OpenGL like for creating blocks in shape of rectangle GL_POLYGON is used. This is very basic program and meant manily for the beginners who want to learn and understand the concept of OpenGL. With the code snippet of this program you will be alble to use the very basic operation like how to draw a rectangle as well as use of translate and  push & pop matrix functions.

The Rolling blocks  is written in c and used the structure in it hence you must know about the structure in prior as well as have knowledge of Array. Structure with Array able to generate the program.


Now time for description of the program - this simple program will rolls out blocks from bottom of screen to upward and in random x directions. blocks will appear in x axis of the display while for moving we will make use of y coordinate. This 2D program so no use of Z axis. You are advice to make this program more attractive by converting the same into a 3D version. We have also put random color to blocks so it look nice and realistic.

Here is berif descrption of program
Define the structure

typedef struct rec
{
GLfloat x0,y0,x1,y1;
int color;
}block;
block

Now create the blocks and draw the same on screen

void createblocks()
{int i=0,y=-1000;
for(i=0;i<10;i++)
{
blocks[i].x0=rand()%500;
blocks[i].x1=blocks[i].x0+50;
blocks[i].y0=y;
blocks[i].y1=y+20;
blocks[i].color=rand()%3;
y+=100;
}
mode=1;
}
void drawblocks()
{int i=0;
for(i=0;i<10;i++)
{
glColor3fv(color[blocks[i].color]);
glBegin(GL_POLYGON);
glVertex2f(blocks[i].x0,blocks[i].y0);
glVertex2f(blocks[i].x0,blocks[i].y1);
glVertex2f(blocks[i].x1,blocks[i].y1);
glVertex2f(blocks[i].x1,blocks[i].y0);
glEnd();
}
}

Now the concept involving the program is over, just have to add the regular snippits like display function, init function and main function in the program which you might have done in many other opengl c programs.
There is twist that you need to use either mouse function or keyboard function to make rolling of blocks more interactive. In this program we have used the mouse function, while youare free to use keyboardrd program or modify the mouse function the way you want it to work.

The Source Code of whole program in C can be downloaded from Google Drive.