Previous Section  < Day Day Up >  Next Section

Distance Between Points

Often in programming, you want to know the distance between two points on the screen. It could be two objects about to collide or two characters about to interact. Or maybe the artificial intelligence is waiting for the player to come within a certain distance of the enemy before it attacks. Whatever the situation, it's important to be able to quickly calculate that distance between two points on those objects. The easiest way to do that is to use the Pythagorean theorem.

The Pythagorean Theorem

a2 + b2 = c2

where a and b are the legs of a right triangle and c is the hypotenuse.


The Pythagorean theorem is illustrated in Figure 2.1.

Figure 2.1. a2 + b2 = c2.

graphics/02fig01.gif

NOTE

The Pythagorean theorem works only for right triangles, not just any triangle. The small box inside the triangle indicates that sides a and b intersect at a 90° angle, which means that the triangle is a right triangle.


The converse of this theorem is also true.

The Converse of the Pythagorean Theorem

If a, b, and c are the lengths of the three sides of a triangle, and a2 + b2 = c2, the triangle is a right triangle with a hypotenuse of length c.


You'll see that the Pythagorean theorem is used extensively in Chapter 4, "Vector Operations," but for now you can use it to investigate the distance between two points on the screen. Suppose you have two points, P1(x1,y1) and P2(x2,y2), as shown in Figure 2.2.

Figure 2.2. The distance between points p1 and p2.

graphics/02fig02.gif

You can draw a right triangle with line segment P1P2 as its hypotenuse. The third vertex of this triangle has the coordinates T(x2,y1). As you can see, side P1T has length (x2x1), and side P2T has length (y2y1). Now you can use the Pythagorean theorem:

(P1P2)2 = (P1T)2 + (P2T)2

= (x2x1)2 + (y2y1)2

This can be summarized in a simple formula, the distance formula.

The Distance Formula in 2D

graphics/02equ01.gif


where P1(x1,y1) and P2(x2,y2) are points on the line.

The following function takes in two arrays of floats, each size 2, which represent points in 2D space and returns the distance between them. Notice the use of the sqrt() function that exists in the <cmath> header file and returns the square root of whatever number is passed into it. Also note the use of the pow() function which takes in two parameters. It returns the first parameter raised to the power of the second. While the pow function is quite useful, it is a bit slower than simply multiplying the numbers manually in the code. For instance, pow(x, 2) is not as fast as x * x. However, if using a Microsoft compiler, using the #pragma intrinsic command in the preprocessor section of your code will greatly increase the speed of most math function calls:


#pragma intrinsic(sqrt, pow)

This allows most math function calls to be sent directly to the math co-processor rather than being sent to the function stack. (For more information on the intrinsic command, do a search for intrinsic in your MSDN library.) Also notice that we are type-casting our answer to a float before it is returned. This is to avoid a truncation compiler warning due to possible loss of information when changing from a double to a float. This can also be avoided by using the less common sqrtf() and powf() which take input and return output as floats rather than doubles.


// purpose: to calculate the distance between two points

// input: P1- an array of 2 floats representing point 1

//        P2- an array of 2 floats representing point 2

// output: the distance between the two points

float distance2D(float *P1, float *P2)

{

     // Calculate our distance and return it

     return (float)sqrt(pow(P2[0] – P1[0], 2) + pow(P2[1] –

graphics/ccc.gif P1[1], 2);

}


Example 2.1: The Distance Between Two Screen Points

If one object is centered at (25,80), and another is centered at (55,40), what is the distance between their two centers?

Solution

graphics/02equ02.gif


Let's combine the distance formula with the Pythagorean theorem in another example.

Example 2.2: Checking for a Right Triangle

A triangle is defined by the following three vertices: A(20,50), B(100,90), and C(70,150). Check to see if it's a right triangle.

Solution

The three points are graphed in Figure 2.3, but you can't tell for sure just by looking at the figure; you need numerical proof.

Figure 2.3. Triangle ABC.

graphics/02fig03.gif

According to the converse of the Pythagorean theorem, if the lengths of the three sides fit a2 + b2 = c2, it's a right triangle. First, find the lengths by using the distance formula three times, once for each side.

For side AB:

graphics/02equ03.gif


For side BC:

graphics/02equ04.gif


For side CA:

graphics/02equ05.gif


Now, plug these three lengths into the Pythagorean theorem to see if it fits:

a2 + b2 = c2

graphics/02equ06.gif


8000 + 4500 = 12,500

12500 = 12500

Therefore, it is a right triangle.

The distance formula can also be extended to three dimensions. All you have to do is take the z-coordinates into account as well.

The Distance Formula in 3D

graphics/02equ07.gif


where P1(x1,y1,z1) and P2(x2,y2,z2) are points on the line.


Example 2.3: The Distance Between Two 3D Points

If one object is centered at (25,80,30) and another is centered at (55,40,100), what is the distance between their two centers?

Solution

graphics/02equ08.gif


Another very helpful formula related to the distance formula is the midpoint formula. There might be times when you'll need the point exactly halfway between two objects on the screen. When that happens, just look up the following formula.

The Midpoint Formula in 2D

graphics/02equ09.gif


is the midpoint between P1(x1,y1) and P2(x2,y2).

The following function takes two points, P1 and P2, as input and returns the midpoint. Notice in this function that we are using the new keyword to allocate memory to our temp variable. Make sure to clean up this memory when it is no longer needed by using the delete keyword. Also remember to use brackets when freeing the memory because we are using brackets to create the memory:


        delete [] temp;



// purpose: calculate the midpoint of a line segment

// input: P1- an array of 2 floats representing point 1

//        P2- an array of 2 floats representing point 2

// output: the midpoint between the two points

float *find2DMidPoint(float *P1, float *P2)

{

    // Allocate enough memory to our pointer

float *temp = new float[2];

    // Calculate our midpoint

    temp[0] = (P1[0] + P2[0]) / 2.0f;

    temp[1] = (P1[1] + P2[1]) / 2.0f;

    // Return our answer

    return temp;

}


Example 2.4: The Midpoint Between Two Screen Points

If one object is centered at (25,80) and another is centered at (55,40), what is the midpoint between them?

Solution

The midpoint is really just the average of the two xs and the two ys:

graphics/02equ10.gif


NOTE

Be careful with the plus and minus signs. Notice that the distance formula subtracts the xs and the ys, but the midpoint formula adds them.


Just like with the distance formula, the midpoint formula can be extended to 3D by simply adding a z component.

The Midpoint Formula in 3D

graphics/ap01equ05.gif


is the midpoint between P1(x1,y1,z1) and P2(x2,y2,z2).

Our 3D midpoint function in code is not much different from our 2D function, differing only in the addition of a third point. Once again, be sure to use delete to clean up the memory that is allocated before the program ends:


// purpose: calculate the midpoint of a line segment in 3D

// input: P1- an array of 3 floats representing point 1

//        P2- an array of 3 floats representing point 2

// output: the midpoint between the two points

float *find3DMidPoint(float *P1, float *P2)

{

    // Allocate enough memory to our pointer

float *temp = new float[3];

    // Calculate our midpoint

    temp[0] = (P1[0] + P2[0]) / 2.0f;

    temp[1] = (P1[1] + P2[1]) / 2.0f;

    temp[2] = (P1[2] + P2[2]) / 2.0f;

    // Return our answer

    return temp;

}


Example 2.5: The Midpoint Between Two 3D Points

If one object is centered at (25,80,30) and another is centered at (55,40,100), what is the midpoint between them?

Solution

Use the 3D extension of the midpoint formula:

graphics/02equ12.gif


At this point, you should be able to

  • Find the length of one side of a right triangle if given the other two

  • Test for a right triangle using the converse of the Pythagorean theorem

  • Find the distance between two points in 2D and 3D

  • Compute the midpoint between two points in 2D or 3D

These topics are revisited in future chapters, so stay tuned!

Self-Assessment

1.

Find the length of side b, as shown in Figure 2.4.

Figure 2.4. Find side b.

graphics/02fig04.gif

2.

A triangle is defined by the following vertices: (30,75), (25,0), and (–50,45). Is it a right triangle?

3.

Find the distance between points (30,80) and (150,130).

4.

Find the distance between points (20,50,10) and (100,120,40).

5.

Find the midpoint between points (30,80) and (150,130).

6.

Find the midpoint between points (20,50,10) and (100,120,40).


    Previous Section  < Day Day Up >  Next Section