Calculate the distance between two CGPoints

Short Answer

CGPoint p1, p2; // Having two points
CGFloat distance = hypotf((p1.x-p2.x), (p1.y-p2.y));

Longer Explination

If you have two points p1 and p2 it is obviously easy to find the difference between their height and width (e.g. ABS(p1.x - p2.x)) but to find a true representation of their distance you really want the hypothenuse (H below).

 p1
  |\  
  | \  
  |  \ H
  |   \
  |    \
  |_ _ _\
         p2

Thankfully there is a built in macro for this: hypotf (or hypot for doubles):

// Returns the hypothenuse (the distance between p1 & p2)
CGFloat dist = hypotf((p1.x-p2.x), (p1.y-p2.y));

(original reference)


Well, with stuff your refering too where is the full code:

CGPoint p2; //[1]
CGPoint p1;
//Assign the coord of p2 and p1...
//End Assign...
CGFloat xDist = (p2.x - p1.x); //[2]
CGFloat yDist = (p2.y - p1.y); //[3]
CGFloat distance = sqrt((xDist * xDist) + (yDist * yDist)); //[4]

The distance is the variable distance.

What is going on here:

  1. So first off we make two points...
  2. Then we find the distance between x coordinates of the points.
  3. Now we find the distance between the y coordinates.
  4. These lengths are two sides of the triangle, infact they are the legs, time to find the hypotenuse which means after doing some math to rearragne c^2 = a^2 + b^2 we get the hypotenuse to equal sqrt((xDist^2) + (yDist^2)). xDist^2 = (xDist * xDist). And likewise: yDist^2 = (yDist * yDist)

You can't really make a CGPoint be the distance, distance doesn't have an x and y component. It is just 1 number.

If you think CGPoint is a unit of measurement (for example feet is a unit of measurement) it is not.

Tags:

Iphone

Box2D