private final double DAMPENING_FACTOR = 0.88; /** * This method modifies this Particle object's velocities based on its * collision with the given target particle. It modifies both the magnitude * and the direction of the velocities based on the interacting magnitude * and direction of particles. It only changes the velocities of this * object; an additional call to bounce() on the other particle is required * to implement a complete bounce interaction. * * The collision algorithm is based on a similar algorithm published by K. * Terzidis, Algorithms for Visual Design. * * @param target * the other particle */ public void bounce(Particle target) { if (hits(target)) { double angle = Math.atan2(target.getY() - myY, target.getX() - myX); double targetX = myX + Math.cos(angle) * (myDiameter / 2 + target.getDiameter() / 2); double targetY = myY + Math.sin(angle) * (myDiameter / 2 + target.getDiameter() / 2); double ax = (targetX - target.getX()); double ay = (targetY - target.getY()); myVelocityX = (int) ((myVelocityX - ax) * DAMPENING_FACTOR); myVelocityY = (int) ((myVelocityY - ay) * DAMPENING_FACTOR); } } /** * This method determines if the given this particle overlaps with the given * target particle. * * @param target * the other particle to check * @return true if the particles overlap; false otherwise */ public boolean hits(Particle target) { if (this == target) { // I can't collide with myself. return false; } else { // Determine if I overlap with the target particle. return (myDiameter / 2 + target.getDiameter() / 2) >= computeDistance(myX, myY, target.getX(), target.getY()); } } /** * This method computes the Euclidean distance between to given points. * * @param x1 * @param y1 * @param x2 * @param y2 * @return the distance between the points (x1, y1) and (x2, y2) */ public static double computeDistance(double x1, double y1, double x2, double y2) { double dx = x1 - x2; double dy = y1 - y2; return Math.sqrt(dx * dx + dy * dy); }