Lesson8
Posted: Thu Sep 03, 2020 9:10 am
Create the project BouncingBallApp.
Easy English Study
https://easy-english-study.com/forum/
Code: Select all
package bouncingballapp;
import org.opensourcephysics.controls.*;
import org.opensourcephysics.frames.*;
public class BouncingBallApp extends AbstractSimulation {
// declares and instantiates a window to draw balls
DisplayFrame frame = new DisplayFrame("x", "y", "Bouncing Balls");
BouncingBall[] ball; // declares an array of BouncingBall objects
double time, dt;
public void initialize() {
// sets boundaries of window in world coordinates
frame.setPreferredMinMax(-10.0, 10.0, 0, 10);
time = 0;
frame.clearDrawables(); // removes old particles
int n = control.getInt("number of balls");
int v = control.getInt("speed");
ball = new BouncingBall[n]; // instantiates array of n BouncingBall objects
for(int i = 0;i<n;i++) {
double theta = Math.PI*Math.random(); // random angle
// instantiates the ith BouncingBall object
ball[i] = new BouncingBall(0, v*Math.cos(theta), 0, v*Math.sin(theta));
frame.addDrawable(ball[i]); // adds ball to frame so that it will be displayed
}
// decimalFormat instantiated in superclass and used to format numbers conveniently
frame.setMessage("t = "+decimalFormat.format(time)); // appears in lower right hand corner
}
public void doStep() { // invoked every 1/10 second by timer in AbstractSimulation superclass
for(int i = 0;i<ball.length;i++) {
ball[i].step(dt);
}
time += dt;
frame.setMessage("t="+decimalFormat.format(time));
}
public void startRunning() { // invoked when start or step button is pressed
dt = control.getDouble("dt");
} // gets time step
public void reset() { // invoked when reset button is pressed
control.setAdjustableValue("dt", 0.1); // allows dt to be changed after initializaton
control.setValue("number of balls", 40);
control.setValue("speed", 10);
}
public static void main(String[] args) { // sets up animation control structure using this class
SimulationControl.createApp(new BouncingBallApp());
}
}
Code: Select all
package bouncingballapp;
import org.opensourcephysics.display.Circle;
public class BouncingBall extends Circle { // Circle is a class that can draw itself
final static double g = 9.8; // constant
final static double WALL = 10;
private double x, y, vx, vy; // initial position and velocity
public BouncingBall(double x, double vx, double y, double vy) { // constructor
this.x = x; // sets instance value equal to passed value
this.vx = vx; // sets instance value equal to passed value
this.y = y;
this.vy = vy;
setXY(x, y); // sets the position using setXY in Circle superclass
}
public void step(double dt) {
x = x+vx*dt; // Euler algorithm for numerical solution
y = y+vy*dt;
vy = vy-g*dt;
if(x>WALL) {
vx = -Math.abs(vx); // bounce off right wall
} else if(x<-WALL) {
vx = Math.abs(vx); // bounce off left wall
}
if(y<0) {
vy = Math.abs(vy); // bounce off floor
}
setXY(x, y);
}
}