i need to calculate the distance between two CGPoint
s. I refered this and this, but I don't get it.
-
3Distance is a scalar value, not a point. – Jim Buck Jun 20 '11 at 19:14
-
What do you mean by "distance in CGPoint"? A point represents an infinitely small location. A distance can not be measured in points. There are infinite points between two points. – albertamg Jun 20 '11 at 19:17
11 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:
- So first off we make two points...
- Then we find the distance between x coordinates of the points.
- Now we find the distance between the y coordinates.
- 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.

- 15,910
- 9
- 62
- 107
-
the distance between two points in math is : d = sqrt ( (x2-x1)^2 + (y2-y1)^2 ); and ; in math we have : ( x - y )^2 = x*x - 2*x*y + y*y ; and not x*x - y*y . so your calcule is wrong !! or am i wrong ? – Houcine Jul 05 '12 at 09:14
-
2@Houcine: (x-y)^2 =/= (x^2 - y^2). They aren't the same. Posting the Wolfram Alpha links didn't work, but if you go to Wolfram alpha and type the two equations in you will see there is a difference. – Dair Jul 05 '12 at 19:43
-
2My math teacher always taught me to do simple test with 2's and 1's to double check your math. Make X 2 and Y 1: 2^2 - 1^2 = 4-1 = 3. (2-1)^2 = 1^2 = 1. 1 != 3, so (x-y)^2 != (x^2 - y^2) – redux Jun 14 '13 at 11:16
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)
I've had to do this by hand 10,000 times so I wrote a function for it and stuck it in my personal library that I always dump in at the beginning of a new program so I forget it's not cannon.
- (float)distanceBetween:(CGPoint)p1 and:(CGPoint)p2
{
return sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2));
}
so you call it like this (say you want to know how far you moved your finger):
float moveDistance = [self distanceBetween:touchStart and:touchEnd];
This is useful in movement functions as well for spot checking in a scrolling menu:
if([self distanceBetween:touchStart and:touchAt] > 20*scalePoints)
isItATap = FALSE;
Set "isItATap" true in touchesBegan, put the above in touchesMoved, then you know the player moved their finger too far for the touch to be a "tap", so you can have it NOT select the object the player touched and instead scroll the object around.
As for scale, that should be based on whether or not you have retina display and what size of a device you're on (divide by 2 for retina display since a physical distance of 5 "points" on a regular screen as the user's finger feels it will come up as 10 "pixels" on a retina display screen, since each point is 4 pixels, so you'll wind up with a situation where the player has a very hard time tapping on retina display (which is a common oversight)

- 1,172
- 1
- 13
- 35

- 1,157
- 10
- 21
-
1Regardless the case, redux, your code will not work correctly. `return sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p2.y,2));` I m sure this should have been; `return sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2));` – Yucel_K Aug 27 '13 at 14:01
-
And the return type ought to be CGFloat, to work nicely with ARM64. – Graham Perks Oct 18 '13 at 11:38
-
1in swift `func distanceBetween(point p1:CGPoint, andPoint p2:CGPoint) -> CGFloat { return sqrt(pow((p2.x - p1.x), 2) + pow((p2.y - p1.y), 2)) }` – NSRover Oct 07 '14 at 04:52
-
Compiler may optimize for you, but generally multiplying is much more efficient than calling `pow`. Since this is a small pure function which is used frequently you will also do much better making it a C function instead of an objective-C message. – Justin Meiners Nov 09 '21 at 20:24
In Swift, you can add an extension to CGPoint:
extension CGPoint {
func distance(to point: CGPoint) -> CGFloat {
return sqrt(pow((point.x - x), 2) + pow((point.y - y), 2))
}
}
and use it like this:
let distance = p1.distance(to: p2)

- 11,672
- 4
- 59
- 73

- 13,064
- 4
- 46
- 49
-
-
1Except that the question was asked before Swift was available. So the ObjC answer should be the accepted one. – koen Feb 22 '20 at 16:25
Sounds like you probably want the vector from p1 to p2 (or difference) rather than the distance.
const CGPoint p1 = {10, 10};
const CGPoint p2 = {510, 310};
const CGPoint diff = {p2.x - p1.x, p2.y - p1.y} // == (CGPoint){500, 300}

- 5,423
- 1
- 30
- 34
In Apple's sample projects, they use hypot. This returns hypothenuse (distance) between two points as explained in this answer.
extension CGPoint {
func distance(from point: CGPoint) -> CGFloat {
return hypot(point.x - x, point.y - y)
}
}

- 1,305
- 16
- 24
only this...
float distance = ccpLength(ccpSub(p1,p2));
where p1 and p2 are objects of CGPoint

- 166
- 10
-
1
-
2question was about Box2d..so basically app integrate with cocos2d :P – mohitdream4u May 06 '15 at 05:23
extension CGPoint {
func magnitude() -> CGFloat {
return sqrt(x * x + y * y)
}
func distance(to: CGPoint) -> CGFloat {
return CGPoint(x: to.x - x, y: to.y - y).magnitude()
}
}

- 10,754
- 6
- 50
- 92
Swift 4, Swift 3 solution
extension CGPoint {
static func distanceBetween(point p1: CGPoint,
andPoint p2: CGPoint) -> CGFloat {
return sqrt(pow((p2.x - p1.x), 2) + pow((p2.y - p1.y), 2))
}
}

- 26,359
- 19
- 112
- 194
Euclidean distance to another point with Vision api.
Starting from iOS 14.
import Vision
extension CGPoint {
public func distance(to point: CGPoint) -> Double {
VNPoint(location: self).distance(VNPoint(location: point))
}
}
print(CGPoint(x: 1, y: 1).distance(to: .zero)) // 1.4142135623730951

- 530
- 1
- 7
- 16
I extended above function to count distance between two CGRects. I count it by counting distance between coners of both CGRects and then returning the smallest distance. I copied function counting intersection point between two lines from:
func distanceBetweenRectangles(r1: CGRect, r2: CGRect) -> CGFloat { // returns distance between boundaries of two rectangles or -1 if they intersect
let cornerPointsR1: [CGPoint] = [
CGPoint(x: r1.minX, y: r1.minY),CGPoint(x: r1.minX, y: r1.maxY),CGPoint(x: r1.maxX, y: r1.minY),CGPoint(x: r1.maxX, y: r1.maxY)]
let cornerPointsR2: [CGPoint] = [
CGPoint(x: r2.minX, y: r2.minY),CGPoint(x: r2.minX, y: r2.maxY),CGPoint(x: r2.maxX, y: r2.minY),CGPoint(x: r2.maxX, y: r2.maxY)]
for i in 0..<cornerPointsR1.count {
if (r2.contains(cornerPointsR1[i])) {
return -1
}
}
var distances: [CGFloat] = []
for i in 0..<cornerPointsR1.count {
for j in 0..<cornerPointsR2.count {
distances.append(distanceBetweenPoints(p1: cornerPointsR1[i], p2: cornerPointsR2[j]))
}
}
distances.sort()
return distances[0]
}

- 317
- 1
- 13