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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Let's assume we have a taxi and an obstacle variable // Both objects have anchorpoints at the center // Calculate the deltaX var deltaX = taxi.x - obstacle.x; deltaX = Math.pow(deltaX, 2); // Calculate the deltaY var deltaY = taxi.y - obstacle.y; deltaY = Math.pow(deltaY, 2); // Calculate the distance var distance = Math.sqrt(deltaX + deltaY); |
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).
1 2 3 4 |
if (distance < 25) { taxi.tint = 0xff0000; // Or decrease lives or score } |
And there we have it, a simple implementation of the distance formula.