PVector calculateSpringForce(Orb other) { //Get the pixel offset from this, to other, as a vector PVector toOther = PVector.sub(other.pos, this.pos); //PVector.sub(...) creates a new PVector //We CANT USE other.pos.sub(this.pos), as that would modify // the other's position, which is not what we want float distToOther = toOther.mag(); // or: distToOther = PVector.dist(this, other); // positive is stretched > len, negative is compressed < len float stringStretch = distToOther - SPRING_LEN; //hooke's law //stretch positive -> stretched -> spring is pulling TOWARDS other -> pos force //stretch negative -> compressed -> pushing AWAY from other -> reversed force float forceTowardsOther = SPRING_CONST * stringStretch; //need to turn that into a vector //toOther should now have correct magnitude //if forceTowards is negative, setMag will flip the vector toOther.setMag(forceTowardsOther); //toOther now points in the right direction, and has //magnitude equal to the amount of force we calculated return toOther; }//calculateSpringForce //Same thing, but done explicitly (math done directly on components) PVector calculateSpringForce2(Orb other) { float xDiff = (other.pos.x - pos.x); float yDiff = (other.pos.y - pos.y); //Euclidean distance float dist = sqrt(xDiff * xDiff + yDiff * yDiff); float displacement = dist - SPRING_LEN; float springforce = displacement * SPRING_CONST; //positive force is TOWARDS other //xDiff and yDiff are already in the right ratio //to point towards other. If we divide both by the same //quantity, the direction doesn't change float xDiffUnitVec = xDiff/dist; float yDiffUnitVec = yDiff/dist; //if we divide both by the distance, it will give us a unit //vector (length 1). If we then multiply both by our desired force, //Its length becomes that force. float xForce = xDiffUnitVec * springforce; float yForce = yDiffUnitVec * springforce; //This force vector is pointing towards other, since its components //are in the same ratio as xDiff,yDiff, //but we've changed its length to be == springforce return new PVector(xForce, yForce); }//calculateSpringForce