Basic Animation using C

The following program will move a car horizontally in a predefined viewport and will change its color for each move. It was developed using the graphics header file present in the Standard C Library under Windows.

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>

void box(int,int);

void main()
{
int i,j,gd=DETECT,gm;
clrscr();
initgraph(&amp;gd, &amp;gm, "C:\\TurboC3\\BGI");
setviewport(0,0,1000,1000,0);
outtextxy(170,200,"Press any key to watch the moving box");
getch();
for( i = 0 ; i <= 420 ; i = i + 10, j++ )
{
box(i,j);
clearviewport();
if(i==420)
break;
}
closegraph();
getch();
}

void box(int a,int col)
{
line(100+a,150,250+a,150);
line(250+a,150,250+a,250);
line(100+a,150,100+a,250);
line(100+a,250,250+a,250);
line(250+a,175,295+a,200);
line(295+a,200,295+a,250);
line(250+a,250,295+a,250);
circle(130+a,275,25);
circle(220+a,275,25);
setcolor(col);
delay(200);
}

The basic concept behind this code is that we draw the outline of a car using line function available in graphics header file and since it moves horizontally we gradually change the x-coordinates, keeping the y-coordinates constant. Also, for the tires of the car, we use the pre-defined circle function in the same header file and also shift the x-coordinate of its center position along with the rest of the structure. Here, i have used the setcolor function to change the color of the car for each move, but its optional! Another important point worth mentioning is that the viewport must be initialized before (defining the car structure and moving it) implementing the car and must be cleared after every move of the car, skipping which can result in undesirable graphical results!

Don’t forget to change the BGI folder path, else the program won’t compile successfully. Enjoy the very basics of Computer Graphics using C if you haven’t tried it before, and for those who are experienced graphics programmer, i would love suggestions for the betterment of this program!

Happy Coding! 🙂

Leave a comment