This method is also checking to see if two shapes intersect with each other, but as the title suggests, it does so using circles. There are advantages and disadvantages compared to other methods.
Here is some pseudo code to show how we can implement this method. The code assumes that the ship and enemy objects have initialized centerX, centerY and radius member variables. It also assumes that distanceX, distanceY have been declared as an appropriate type, possibly float or similar.
The code below doesn’t mention the types as they will vary depending upon your platform and requirements.
// Get the distance of the two objects from // the edges of the circles on the x axis distanceX = (ship.centerX + ship.radius) - (enemy.centerX + enemy.radius; // Get the distance of the two objects from // the edges of the circles on the y axis distanceY = (ship.centerY + ship.radius) - (enemy.centerY + enemy.radius; // Calculate the distance between the center of each circle // Math.sqrt is from Java. All modern languages have an equivalent distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY); // Finally see if the two circles overlap if (distance < ship.radius + enemy.radius) { // bump }
The key to the whole thing is the way we initialize distance:
Math.sqrt(distanceX * distanceX + distanceY * distanceY);
If the previous line of code looks a little confusing, it is simply using Pythagoras’ theorem to get the length of the hypotenuse of a triangle which is equal in length to a straight line drawn between the centers of the two circles. In the last line of our solution, we test if distance is greater than the ship.radius + enemy.radius, then we can be certain that we must have a collision. That is because if the center points of two circles are closer than the combined length of their radii, therefore they must be overlapping.
Leave A Comment