/** * Detect if two bodies are crashing into each other If they are, then create and return the * resultant body, if they aren't, then return a null value. * */ private static Body crash(Body m1, Body m2) { // Distance formula to determine if two bodies are touching if (StrictMath.sqrt( StrictMath.pow((m2.getposx() - m1.getposx()), 2) + StrictMath.pow((m2.getposy() - m1.getposy()), 2)) < (m1.getSize() + m2.getSize())) { int mass, size; double vX, vY, pX, pY; Color color; mass = (m1.getMass() + m2.getMass()); size = ((m1.getSize() + m2.getSize())); color = combineColor(m1, m2); // Get the resultant velocities with the inelastic collisions equation: // V = (M1*V1 + M2*V2)/(M1+M2) vX = ((m1.getvelx() * m1.getMass() + m2.getvelx() * m2.getMass()) / (m1.getMass() + m2.getMass())); vY = ((m1.getvely() * m1.getMass() + m2.getvely() * m2.getMass()) / (m1.getMass() + m2.getMass())); // Whichever body is bigger absorbs the other body if (m1.getMass() > m2.getMass()) { pX = m1.getposx(); pY = m1.getposy(); } else { pX = m2.getposx(); pY = m2.getposy(); } return (new Body(mass, size, color, vX, vY, pX, pY)); } else return null; }
/** Change the velocity with the force calculations * */ private static void velChanges(Body b, ArrayList<Body> system) { double xAccel = 0; double yAccel = 0; for (Body body : system) { if (body.getSize() > 500) deletions.add(body); if (b != body) { /** * Check the entire system for collisions and make the necessary changes. This way will * prevent the ConcurrentModificationExceptions I've been fighting * */ Body test = crash(b, body); if (test != null) { if (!body.getLocked()) // Bodies get added to the list twice because a crashes // into b and b also crashes into a. // Added if statements to make sure that things aren't being // double counted. if (!deletions.contains(body)) deletions.add(body); if (!b.getLocked()) if (!deletions.contains(b)) deletions.add(b); if (!b.getLocked() || !body.getLocked()) { boolean add = true; for (int i = 0; i < additions.size(); i++) { if (test.equals(additions.get(i))) add = false; } if (add) additions.add(test); } } // If there's no collision, then just do the calculations. else { xAccel += calculateAcceleration(calculateGravity(b, body, true), b); yAccel += calculateAcceleration(calculateGravity(b, body, false), b); } } } xAccel = Multiplier * xAccel; // Static Multipliers to yAccel = Multiplier * yAccel; // make things play nicer b.setvelx(b.getvelx() + xAccel); b.setvely(b.getvely() + yAccel); }
/** Change the position to the new position * */ private static void posChanges(Body b) { b.setposx(b.getposx() + b.getvelx()); b.setposy(b.getposy() + b.getvely()); }