package KinematicSimulator; import java.util.Vector; /** * This is the basic Physics Strategy. It implements gravity, friction, * and elasticity. * * @author Steve */ public class NewtonianPhysicsStrategy extends PhysicsStrategy { double m_gravity = 60; double m_elastic = 0; double m_friction = 3; int m_radius = 20; double m_width = 500; double m_height = 500; public NewtonianPhysicsStrategy( int gravity, int elastic, int friction, int radius) { m_gravity = gravity; m_elastic = elastic; m_friction = friction; m_radius = radius; } public NewtonianPhysicsStrategy() { this(60, 0, 3, 20); } public void setSize(int w, int h) { m_width = (double) w; m_height = (double) h; } public int getRadius() { return m_radius; } public void applyPhysics(Vector balls) { double d = m_gravity * 0.01D; double d1 = m_friction / 500D; double d2 = 0.01D * (double) (100F - m_elastic); double d3 = 0.01D * (double) (100F - m_elastic / 4F); for (int i = 0; i < balls.size(); i++) { Ball ball = (Ball) balls.elementAt(i); ball.move(); ball.accelerate(0.0D, d); ball.accelerate(d1 * -ball.momentum_x(), d1 * -ball.momentum_y()); if (ball.pos_y() > m_height - ball.radius() || ball.pos_y() < ball.radius()) ball.accelerate(0.0D, -2D * ball.momentum_y() * d2); if (ball.pos_x() < ball.radius() || ball.pos_x() > m_width - ball.radius()) ball.accelerate(-2D * ball.momentum_x() * d2, 0.0D); for (int j = i + 1; j < balls.size(); j++) { Ball ball1 = (Ball) balls.elementAt(j); if (ball.collision(ball1)) { Vector2D vector2d = new Vector2D( ball1.pos_x() - ball.pos_x(), ball1.pos_y() - ball.pos_y()); Vector2D vector2d1 = new Vector2D(ball.momentum_x(), ball.momentum_y()); Vector2D vector2d2 = vector2d.projection(vector2d1); Vector2D vector2d3 = new Vector2D(ball1.momentum_x(), ball1.momentum_y()); Vector2D vector2d4 = vector2d.projection(vector2d3); Vector2D vector2d5 = vector2d4.add(vector2d2.negative()); vector2d = new Vector2D( ball.pos_x() - ball1.pos_x(), ball.pos_y() - ball1.pos_y()); vector2d4 = vector2d.projection(vector2d1); vector2d2 = vector2d.projection(vector2d3); Vector2D vector2d6 = vector2d4.add(vector2d2.negative()); ball.accelerate( vector2d5.get_x() * d3, vector2d5.get_y() * d3); ball1.accelerate( vector2d6.get_x() * d3, vector2d6.get_y() * d3); double d4 = vector2d.length() * 0.5D; double d5 = d4 - ball.radius(); double d6 = d4 - ball1.radius(); d4 = d5 + d6; double d7 = d4 / 2D; double d8 = vector2d.length(); Vector2D vector2d7 = vector2d.scale(d7 / d8); ball.setPos( ball.pos_x() - vector2d7.get_x(), ball.pos_y() - vector2d7.get_y()); ball1.setPos( ball1.pos_x() + vector2d7.get_x(), ball1.pos_y() + vector2d7.get_y()); } } if (ball.pos_y() > m_height - ball.radius()) ball.setPos(ball.pos_x(), m_height - ball.radius()); if (ball.pos_y() < ball.radius()) ball.setPos(ball.pos_x(), ball.radius()); if (ball.pos_x() > m_width - ball.radius()) ball.setPos(m_width - ball.radius(), ball.pos_y()); if (ball.pos_x() < ball.radius()) ball.setPos(ball.radius(), ball.pos_y()); } } }