Hittest using the distance formula

  • 1 Min. Read.

Sometimes using a built-in hittest functionality isn’t sufficient for checking if 2 objects collide. In these cases the distance formula will come in handy.

The distance formula looks a little something like this: \(d=\sqrt{(\Delta x)^2+(\Delta y)^2}\) And can be further broken down into: \(d=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}\,\)

Fear not though, implementation is not hard at all. Take a look at the following example.

We have a taxi sprite and an obstacle on the road. When you move the slider and the taxi collides with the obstacle, it turns red. Let’s get coding. The example above was written using the PhaserJS framework, but the distance formula can be applied in every scenario where you have 2 points in a coordinate system.

Now that we have the distance between our 2 objects, we can turn our taxi red when the distance is lower than a specific value (25 in the example above).

And there we have it, a simple implementation of the distance formula.