import java.util.*; public class Ball extends PhysicsElement { private static int id=0; // Ball identification number private final double mass; private final double radius; private double pos_t; // current position at time t private double pos_tPlusDelta; // next position at t + delta private double speed_t; // speed at time t private double speed_tPlusDelta; // speed at t + delta private Ball(){ // nobody can create a ball without state super(id++); mass=0; radius=0; } public Ball(double mass, double r, double position, double speed){ super(id++); this.mass = mass; radius = r; pos_t = position; speed_t = speed; } public double getMass() { return mass; } public double getRadius() { return radius; } public double getPosition() { return pos_t; } public double getSpeed() { return speed_t; } public boolean collide(Ball b){ return Math.abs(b.getPosition()-pos_t)<(b.getRadius()+radius); } public void computeNextState(double delta_t, MyWorld w) { double speed=speed_t; PhysicsElement pe; if ((pe=w.getCollidingElement(this))!= null){ /* elastic collision */ if (pe instanceof Ball) { Ball b =(Ball) pe; speed=(speed_t*(mass-b.getMass())+2*b.getMass()*b.getSpeed())/(mass+b.getMass()); } else { // case Container } } speed_tPlusDelta = speed; pos_tPlusDelta = pos_t + speed*delta_t; } public void updateState(){ pos_t = pos_tPlusDelta; speed_t = speed_tPlusDelta; } public String getDescription() { return "Ball_" + getId()+": x "; } public String getState() { return getPosition()+" "; } }