The first method below is suppose to calculate the distance between two objects. The second method is suppose to return true if the 'playerObject' (a single circle) and the 'barriers' (an array of circles) object collide. I have tried to sum the radius of the objects and compared that to being less than the distance being calculated in the first method. At this time the collision is being detected but roughly 50% of the time the playerObject doesn't quite touch a barrier, stopping roughly 5 pixels from the edge of a barrier circle at times. When I ran a Junit test it failed. The result was suppose to be 6.884 but I was getting 9.884.
Please help me to improve my code.
public class Submission { /** * Compute the distance between two objects. The distance may be negative if * the two objects overlap. * @param object1 first object * @param object2 second object * @return the distance between the two objects */ public static double distance(GameObject object1, GameObject object2) { float x1 = object1.getX(); float y1 = object1.getY(); float x2 = object2.getX(); float y2 = object2.getY(); return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)); } /** * Determine if the object collides with a barrier * @param object the player object * @param barriers array of barriers * @return true if the player collides with a barrier */ public static boolean collision(GameObject object, GameObject[] barriers) { float palyerRadius = object.getWidth()/2; float barrierRadius = 0; for (int i = 0; i < barriers.length; i++) { barrierRadius = barriers[i].getWidth()/2; float sumOfRadius = barrierRadius + palyerRadius; if (Submission.distance(object, barriers[i]) < sumOfRadius) return true; } return false; }