Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the distance between two CGPoints

Tags:

iphone

box2d

i need to calculate the distance between two CGPoints. I refered this and this, but I don't get it.

like image 232
iCoder86 Avatar asked Jun 20 '11 19:06

iCoder86


People also ask

How do you find the distance between 2 points?

Learn how to find the distance between two points by using the distance formula, which is an application of the Pythagorean theorem. We can rewrite the Pythagorean theorem as d=√((x_2-x_1)²+(y_2-y_1)²) to find the distance between any two points.

How do you find the distance between two diagonals?

This means that you will square the x-axis distance (x2 - x1), and that you will separately square the y-axis distance (y2 - y1). Add the squared values together. This will give you the square of the diagonal, linear distance between your two points.


1 Answers

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.

like image 69
Dair Avatar answered Oct 17 '22 20:10

Dair