/*
* THIS IS A C PROGRAM THAT ANIMATES THE MOTION OF A CIRCULAR BALL ACROSS A SINE WAVE.
* THE BALL REMAINS IN CONTACT WITH THE SINE CURVE AT EVERY INSTANT AND TRAVELS FROM
* X = -π TO X = π ONCE
*/
#include<stdlib.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>
#include<dos.h>
void drawsinewave();
void drawaxes();
void linejoin(double, double, double, double);
void drawball(double);
void animateball(void);
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
/* clear screen */
clrscr();
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
/* terminate with an error code */
exit(1);
}
animateball();
getch();
return 0;
}
/* following function draws the X and Y axes */
void drawaxes()
{
setcolor(WHITE);
line(getmaxx()/2, 0, getmaxx()/2, getmaxy()); /* drawing Y axis */
line(0, getmaxy()/2, getmaxx(), getmaxy()/2); /* drawing X axis */
}
/* following function performs the animation */
void animateball()
{
double x;
for(x=-M_PI;x<=M_PI;x+=0.01)
{
drawaxes();
drawsinewave();
setcolor(WHITE);
drawball(x); /* draw the ball */
delay(50); /* give a delay before next movement */
setcolor(BLACK); /* remove traces of the drawn ball */
drawball(x);
}
}
/* following function draws the sine wave across the screen */
void drawsinewave()
{
double oldx = -M_PI, oldy=sin(oldx), x, y;
setcolor(WHITE);
do
{
x=oldx+0.01;
y=sin(x);
linejoin(x,y,oldx,oldy);
oldx=x;
oldy=y;
}while(x<=M_PI);
}
/* following function joins two points given in rectangular Cartesian co-ordinate systems */
void linejoin(double x1, double y1, double x2, double y2)
{
double xscale = 100, yscale = getmaxy()/2.5 ;
int newx1 = x1*xscale + getmaxx()/2 ;
int newy1 = -y1*yscale + getmaxy()/2 ;
int newx2 = x2*xscale + getmaxx()/2 ;
int newy2 = -y2*yscale + getmaxy()/2 ;
line(newx1, newy1, newx2, newy2);
}
/* following function draws the ball at a given abscissa */
void drawball(double x)
{
double y = sin(x), xscale = 100, yscale = getmaxy()/2.5, xshift = getmaxx()/2, yshift = getmaxy()/2;
double Xknown = x*xscale + xshift, Yknown = -y*yscale + yshift;
double R = 10;
double deno = sqrt(yscale*yscale*cos(x)*cos(x)+xscale*xscale);
double Xcentre = Xknown - R*yscale*cos(x)/deno;
double Ycentre = Yknown - R*xscale*cos(x)/(deno*cos(x));
circle(Xcentre,Ycentre,R);
}
No comments:
Post a Comment
Do you think this information useful or was not up to the mark? Comment if you have any advices or suggestions about the post.