package physics2D; import java.util.Vector; public class Plane2D { protected double g = 20; protected Vector objects; public Plane2D() { objects = new Vector(); } public void add(Object2D o) { objects.add(o); } public void advanceTime(int increment) { Object2D x; Object2D y; Vector2D[] acceleration = new Vector2D[objects.size()]; Vector2D[] velocity = new Vector2D[objects.size()]; Vector2D distance; Vector2D force; for (int i = 0; i < objects.size(); i++) { x = (Object2D) objects.get(i); acceleration[i] = x.getAcceleration(); velocity[i] = x.getVelocity(); } for (int i = 0; i < objects.size(); i++) { x = (Object2D) objects.get(i); for (int j = i + 1; j < objects.size(); j++) { y = (Object2D) objects.get(j); distance = y.getPosition().subtract(x.getPosition()); if (distance.getMagnitude() < x.getRadius() + y.getRadius()) { Vector2D[] vf = compute2DCollision(velocity[i], velocity[j], distance.getAngle(), x.getMass(), y.getMass()); velocity[i] = vf[0]; velocity[j] = vf[1]; } else { double forceMag = g * x.getMass() * y.getMass() / Math.pow(distance.getMagnitude(),2); force = new Vector2D(forceMag, distance.getAngle()); acceleration[i] = acceleration[i].add(force.divide(x.getMass())); acceleration[j] = acceleration[j].add(force.divide(-y.getMass())); } } } for (int i = 0; i < objects.size(); i++) { x = (Object2D) objects.get(i); x.setVelocity(velocity[i]); x.setVelocity(x.getVelocity().add(acceleration[i].multiply(increment / 2000.0))); x.move(x.getVelocity().multiply(increment / 1000.0)); x.setVelocity(x.getVelocity().add(acceleration[i].multiply(increment / 2000.0))); if (x.getAngularVelocity() != 0.0 || x.getAngularAcceleration() != 0.0) { x.setAngularVelocity(x.getAngularVelocity() + x.getAngularAcceleration() * increment / 1000.0); x.rotate(x.getAngularVelocity() * increment / 1000.0); } } } protected Vector2D[] compute2DCollision(Vector2D v1, Vector2D v2, double angle, double m1, double m2) { v1 = v1.rotate(-angle); v2 = v2.rotate(-angle); double[] vf; vf = compute1DCollision(v1.getYComponent(), v2.getYComponent(), m1, m2); v1 = new Vector2D(v1.getXComponent(), vf[0], true).rotate(angle); v2 = new Vector2D(v2.getXComponent(), vf[1], true).rotate(angle); return new Vector2D[] {v1, v2}; } protected double[] compute1DCollision(double v1, double v2, double m1, double m2) { if (v1 > 0 || v2 < 0) { double v1f = v2 * (2 * m2) / (m1 + m2) + v1 * (m1 - m2) / (m1 + m2); double v2f = v1 - v2 + v1f; return new double[] {v1f, v2f}; } return new double[] {v1, v2}; } }