// Attraction // Daniel Shiffman // A class to describe a Food in our world, has vectors for location, velocity, and acceleration // Also includes scalar values for mass, maximum velocity, and elasticity class Food { Vector3D loc; Vector3D vel; Vector3D acc; float mass; float max_vel; float bounce = 5.0f; // How "elastic" is the object float G; // Universal gravitational constant int timer; boolean eaten = false; boolean dead = false; Food(Vector3D a, Vector3D v, Vector3D l, float m_) { acc = a.copy(); vel = v.copy(); loc = l.copy(); mass = m_; max_vel = 3.0f; G = 0.1f; } // Main method to operate object void run() { update(); render(); } Vector3D getLoc() { return loc; } Vector3D getVel() { return vel; } float getMass() { return mass; } Vector3D calcGravForce(Food f) { Vector3D dir = Vector3D.sub(f.getLoc(), loc); // Calculate direction of force float d = dir.magnitude(); // Distance between objects d = constrain(d,100.0f,200.0f); // Limiting the distance to eliminate "extreme" results for very close or very far objects dir.normalize(); // Normalize vector (distance doesn't matter here, we just want this vector for direction) float force = (G * mass * f.getMass()) / (d * d); // Calculate gravitional force magnitude dir.mult(force); // Get force vector --> magnitude * direction return dir; } void add_force(Vector3D force) { force.div(mass); acc.add(force); if (showVectors) { drawVector(force,loc,1000); } } float getX(){ return loc.x; } float getY(){ return loc.y; } void setAcc(Vector3D v) { acc = v.copy(); } // Method to update location void update() { px = loc.x; py = loc.y; vel.add(acc); vel.limit(max_vel); loc.add(vel); acc.setXYZ(0.0,0.0,0.0); } // Method to display void render() { ellipseMode(CENTER); noStroke(); float nw; float nh ; xoff += 0.5; yoff += 0.5; noStroke(); nw = noise(xoff) * 3 + 3/3; nh = noise(yoff) * 3 + 3/2; if (eaten) { fill(noise(xoff)*5+200,noise(xoff)*5+180,noise(xoff)); //ellipse(loc.x + nw/2, loc.y,nw,nh); if (timer%10 == 0){ dead = true; } } else{ //Center ellipse fill(noise(xoff)*10+250,noise(xoff)*10+250,noise(xoff)); ellipse(loc.x,loc.y,nw/2,nh); //wings ellipse(loc.x + nw/2, loc.y,nw/3,nh*2); ellipse(loc.x - nw/2, loc.y,nw/3,nh*2); eaten = false; dead = false; } timer++; } void die(){ eaten = true; } boolean dead(){ return dead; } }