Write a glut program to implement animation of squashing and rotating ball



CODE:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <MATH.h>

#if defined(__APPLE__)
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#define PI 3.1415926535898

double xpos, ypos, ydir, xdir;        
double sx, sy, squash;         
double rot;            

#define PI 3.1415926535898
GLint circle_points = 100;
void MyCircle2f(GLfloat centerx, GLfloat centery, GLfloat radius){
  GLint i;
  GLdouble angle;
  glBegin(GL_POLYGON);
  for (i = 0; i < circle_points; i++) {   
    angle = 2*PI*i/circle_points;
    glVertex2f(centerx+radius*cos(angle), centery+radius*sin(angle));
  }
  glEnd();
}


GLfloat RadiusOfBall = 15.;

void draw_ball() {
  glColor3f(0.6,0.3,0.);
  glScalef(1.3,1.,1.);
  MyCircle2f(0.,0.,RadiusOfBall);
}

void Display(void)
{
  glutSwapBuffers();
  glClear(GL_COLOR_BUFFER_BIT);
  xpos = 80.;
       if (ypos == RadiusOfBall && ydir == -1  ) {
              sy = sy*squash ;
              if (sy < 0.8)
                     squash = 1.1;
              else if (sy > 1.) {
                     sy = 1.;
                     squash = 0.9;
                     ydir = 1;
              }
              sx = 1./sy;
       }
       else {
       ypos = ypos+ydir *1.5 - (1.-sy)*RadiusOfBall;
       if (ypos == 120-RadiusOfBall)
              ydir = -1;
       else if (ypos <RadiusOfBall)
              ydir = 1;
       }
       rot = rot+2.;
       if (rot >= 360)
    rot = 0;
  glLoadIdentity();
  glTranslatef(xpos,ypos, 0.);
  glScalef(sx,sy, 1.);
  glRotatef(rot, 0.,0.,1.);
  draw_ball();
 glutPostRedisplay();
  }


void reshape (int w, int h)
{
   glViewport (0, 0, (GLsizei) w, (GLsizei) h);
   glMatrixMode (GL_PROJECTION);
   glLoadIdentity ();
   gluOrtho2D(0.0, 160.0, 0.0, 120.0);
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity ();
}

void init(void){
  glClearColor(0.0,0.8,0.0,1.0);
  xpos = 60; ypos = RadiusOfBall; xdir = 1; ydir = 1;
  sx = 1.; sy = 1.; squash = 0.9;
  rot = 0;
}

void main(int argc, char* argv[])
{
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
  glutInitWindowSize (320, 240);  
  glutCreateWindow("Bouncing Ball");
  init();
  glutDisplayFunc(Display);
  glutReshapeFunc(reshape);
  glutMainLoop();
}




OUTPUT:


0 comments:

Post a Comment