Learning and Applying Mathematics using Computing

Shooting Rocks

The very first example on this blog looked at moving a spaceship around. In this post we’ll return to our spaceship, and get it shooting asteroids. Firing a bullet is quite straightforward: you add the bullet, make it point in the same direction as the spaceship, then let it continue in a straight line. But how can you know when the bullet has hit an asteroid?

If you want to perform collision detection with a mathematical approach, you must model the two entities involved as geometric items: a point, a line, a circle, a rectangle, or some other polygon. Our bullet can be modelled as a point, and our asteroid can be modelled as a circle (the red outline below):

So to find out if our bullet has hit an asteroid, we need to check if a point has intersected a circle. A circle is defined as being a particular distance (the radius) from a given point (the centre). So to find out if a point intersects a circle, find out how far the point is from the centre. If this distance is less than the radius, the point must be inside the circle; if the distance is greater than the radius, if must be outside the circle. For example, below, the distance from the centre to the blue point is less than the radius, which means it is inside the circle, whereas the distance from the centre to the purple point is greater than the radius, which means it is outside the circle:

Finding out the distance between the point and the centre of the circle is done with Pythagoras, making the overall code very simple — check the Pythagorean distance against the radius to see if the bullet is touching the asteroid:

```    private boolean touching(Asteroid asteroid)
{
double distX = asteroid.getX() - getX();
double distY = asteroid.getY() - getY();
double dist = Math.sqrt(distX * distX + distY * distY);