Modify a text file: $/bumping-energy.java
$/bumping-energy.java
//// bumping-energy.java (bam CST112): Use an array of objects. Zoog[] z= new Zoog[10]; // Make room for (up to) ten Zoogs. int many=10; int debug=0; boolean energyShow=false; float sayX=500, sayY=50, sayN=0; void setup() { size( 800,600); smooth(); z= new Zoog[10]; populate( many ); //-- frameRate(5); } void populate( int m) // Populate the array with a random number of (up to ten) Zoogs. { many= m; for (int i=0; i
=0 && k
0) { text( counter, x+w/4, 12 + y+h/2); // Display hit count, underneath } // (Debugging: display coords.) if (debug>0) { fill(0,0,255); text( x, x+30+w/4, 12 + y+h/2); text( y, x+30+w/4, 24 + y+h/2); } } float mass() // Calculate the mass of this Zoog. { return 0.001 * (w+counter) * (h+counter); // Kilograms = width * height } float velocity() // Calculate the velocity of this Zoog { return sqrt( sq(dx) + sq(dy) ); } float energy() // Caclulate the kinetic energy = (1/2) m v^2 { return 0.5 * mass() * sq( velocity() ); } void move() // Move to new (x,y) { x += dx; // Move one unit. y += dy; // Check for walls. if (x>width-10 || x<20) // Reverse direction, if off sides. { dx = -dx; x += 3*dx; // Bounce (to avoid jiggle at edge). } if (y>height-10 || y<10) // Reverse direction, if beyond top or bottom. { dy = -dy; y += 3*dy; // Bounce (to avoid jiggle at edge). } //// Keep Zoogs from fluttering on the walls! if (x < 0) x=10; if (x > width) x=width-10; if (y < 0) y=10; if (y > height) y=height-10; } void collide( Zoog other) // Return true iff collision with other. { if ( hit( 50, other.x, other.y, this.x, this.y) ) { // Flash two circles! stroke(255,0,0); strokeWeight(2); fill(this.c); ellipse(x-2*dx, y-2*dy, 30,30); fill(other.c); ellipse(other.x, other.y, 30,30); strokeWeight(1); stroke(0); // exchange velocities & bounce apart. float tmp; tmp= other.dx; other.dx= this.dx; this.dx= tmp; x += 10*dx; tmp= other.dy; other.dy= this.dy; this.dy= tmp; y += 10*dy; // Also bump both counters. if (this.x < other.x) { this.counter++; other.counter--; } else { this.counter--; other.counter++; } } } }