/* * File: BouncingBall.java * Author: Peter Torpey * For: MAS.864 The Nature of Mathematical Modeling - PS1 * * Host: Java Applet; Processing * * * Dependencies: * Processing, NOC Vector3D * * * Description: * A two-dimensional simulation of a ball bounces across the frame. * */ import java.util.*; import noc.*; import processing.core.*; public class BouncingBall extends PApplet { public static final int FRAME_RATE = 30; public static final Vector3D GRAVITY = new Vector3D(0.0f, -0.8f); private ArrayList myBalls; public void setup() { size(800, 480); smooth(); frameRate(FRAME_RATE); background(255); fill(220, 0, 32); myBalls = new ArrayList(); myBalls.add(makeBall()); } public void draw() { background(255); for (Ball ball : myBalls) { ball.updateTick(GRAVITY); Vector3D p = ball.getPosition(); int d = 2 * ball.getRadius(); noStroke(); ellipse((int)p.x, height - (int)p.y, d, d); stroke(0); line(0, height - 1, width, height - 1); } } public void mouseClicked() { myBalls.clear(); myBalls.add(makeBall()); } private Ball makeBall() { return new Ball(new Vector3D(10f, height - 10), new Vector3D(random(0, 24), random(-10, 30)), (int)random(8, 60), 0.6f, 0.9f); } } class Ball { private int myRadius; private float myElasticity; private Vector3D myPosition; private Vector3D myVelocity; private float myFriction; int myTime; public Ball(Vector3D p0, Vector3D v0, int r, float e, float f) { myPosition = p0; myVelocity = v0; myRadius = r; myElasticity = e; myFriction = f; myTime = 0; } public void setInitialPosition(Vector3D p0) { myPosition = p0; } public void setInitialVelocity(Vector3D v0) { myVelocity = v0; } public void setRadius(int r) { myRadius = r; } public void setElasticity(float e) { myElasticity = e; } public void updateTick(Vector3D g) { myVelocity.add(Vector3D.mult(g, myTime)); myPosition.add(myVelocity); if (myPosition.y < myRadius) { myPosition.y += myRadius - myPosition.y; myVelocity.y = -myVelocity.y; myVelocity.y -= myElasticity; myVelocity.x *= myFriction; } myTime++; } public Vector3D getPosition() { return myPosition; } public int getRadius() { return myRadius; } }