public class Spring extends PhysicsElement { private static int id=0; // Spring identification private float restLength; private final float stiffness; private Block leftBlock, rightBlock; private Spring(){ // nobody can create a block without state super(id++); stiffness=0; } public Spring(float restLength, float stiffness){ super(id++); this.restLength = restLength; this.stiffness = stiffness; leftBlock = rightBlock = null; } public Spring(float restLength, float stiffness, Block lBlock, Block rBlock){ this(restLength, stiffness); leftBlock = lBlock; rightBlock = rBlock; } public void attachLeftBlock (Block lBlock) { leftBlock = lBlock; } public void attachRightBlock (Block rBlock) { rightBlock = rBlock; } public double getLength() { if (rightBlock == null || leftBlock == null) return restLength; return (rightBlock.getPosition() - leftBlock.getPosition()); } public double getForce(Block block) { double force = (getLength()-restLength)*stiffness; if (block == leftBlock) return force; if (block == rightBlock) return (-1)*force; else return 0.0; } public void computeNextState(double delta_t) { } public void updateState(){ } public String getDescription() { return "Spring_"+ getId()+": x0,x1"; } public String getState() { String s; if (leftBlock != null) s = leftBlock.getPosition()+","; else if (rightBlock != null) s = (rightBlock.getPosition()-restLength)+","; else s = "0,"; // up to here left end is determined if (rightBlock != null) s += rightBlock.getPosition(); else if (leftBlock != null) s += (leftBlock.getPosition()+restLength); else s += "0"; return s; } }