Saturday, March 7, 2009

Dissecting Distance Logic

This is something I wanted to do. The logic is not incredibly complex, but I know it is something I will need in numerous programming projects, especially game-oriented. Working to dissect the logic will help me bash the logic in my head.

Here's the situation. I have two objects on a grid, or on screen. I need the distance between both objects, but there is no direct way to get it since the only information I have access to is the horizontal and vertical position (coordinates).

Both objects and the distance I need to get

On paper it would be an easy task. I would only have to take a ruler and measure from Object A to Object B. But since I only have access to the coordinates (the horizontal and vertical position), I have to use another method. Let's start by drawing a horizontal and vertical line that intersects.

Magically, a right-angle appears!

So, with the distance line, I get a rectangle-triangle. The distance is the hypotenuse. So Pythagore's Theorem could be used to find the distance... but, how wide are the two other sides. Well, since we have the coordinates of both objects, we can calculate the number of grid units for each.
Object A x - Object B x (8 - 2) = 6
Object A y - Object B y (7 - 2) = 5

The width of the two smallest sides...

...with the hypotenuse.

a² + b² = c²
6² + 5² = c²
36 + 25 = c²
sqrt(61) = c
7.81 = c
The distance is the length of the hypotenuse, which is 7.81 (rounded).

So, using Pythagore's Theorem, we can find the distance between two points/objects when we only have their vertical and horizontal positions.

Simple, I know, but it's a pretty original way in finding the information needed when the information available is restricted.