// implementation of boids class...handles flocking // Date: 23 Oct 2008 // Author: Don Allison #include "boids.h" #include #define _USE_MATH_DEFINES #include #include "glut.h" #include // default constructor...sets critter at random position between (-1.0, -1.0) and (1.0, 1.0) boids::boids() { x = newx = 2.0*rand()/RAND_MAX - 1.0; y = newy = 2.0*rand()/RAND_MAX - 1.0; vx = vy = 0.05; time = ntime = (double)clock()/CLOCKS_PER_SEC; return; } // destructor boids::~boids() { return; } // sets current x value of critter in world coordinates void boids::setx(double u) { x = u; return; } // sets current y value of critter in world coordinates void boids::sety(double v) { y = v; return; } // gets current x value of critter in world coordinates double boids::getnextx(void) { return newx; } // gets current y value of critter in world coordinates double boids::getnexty(void) { return newy; } // draws single flocking critter at current origin location void boids::draw(void) { double theta; // handle orientation theta = atan2(vx, vy); if (vx*vy < 0) theta += M_PI; glRotatef(theta*180.0/M_PI, 0.0, 0.0, 1.0); // set body color glColor3f(0.7, 0.0, 0.0); // draw body glBegin(GL_POLYGON); glVertex2d(-0.03, 0.03); glVertex2d(-0.03, -0.03); glVertex2d(0.05, 0.0); glEnd(); // set eye color glColor3f(0.0, 0.0, 0.0); // draw eye glTranslated(0.02, 0.0, 0.0); glutSolidSphere(0.01, 50, 50); return; } void boids::nextPosition() { double t; time = ntime; ntime = (double)clock() / CLOCKS_PER_SEC; t = ntime - time; newx = x + vx*t; newy = y + vy*t; if (newx > 1.0) { newx = 1.0; vx = -vx; } else if (newx < -1.0) { newx = -1.0; vx = -vx; } if (newy > 1.0) { newy = 1.0; vy = -vy; } else if (y < -1.0) { newy = -1.0; vy = -vy; } return; }