supri
supri

Reputation: 45

Distance between two points on circle in specific direction

I have two points on my circle, (x1y1) and (x2y2). How do I calculate distance between them in counter and clock wise direction. Currently, I am using following formula to calculate the distance between 2 points on circle. Please suggest.

- (CGFloat)calculateDistanceBetween:(CGPoint)point1 point2:(CGPoint)point2
{
    CGFloat dx = point2.x - point1.x;
    CGFloat dy = point2.y - point1.y;
    return sqrt(dx*dx + dy*dy );
}

Upvotes: 0

Views: 1891

Answers (1)

Dave
Dave

Reputation: 46249

This is a maths question really. You're looking for arc length (which equals angle in radians multiplied by radius)

Your function as it stands can't calculate an arc length, because it doesn't know where the circle is (it takes 3 points to define a circle).

- (CGFloat)calculateShortestArcDistanceBetween:(CGPoint)point1 point2:(CGPoint)point2 center:(CGPoint)center
{
    CGFloat dx1 = point1.x - center.x;
    CGFloat dy1 = point1.y - center.y;
    CGFloat dx2 = point2.x - center.x;
    CGFloat dy2 = point2.y - center.y;
    CGFloat angle1 = atan2f( dy1, dx1 );
    CGFloat angle2 = atan2f( dy2, dx2 );
    CGFloat angle = angle1 - angle2;
    if(      angle >  M_PI ) angle -= M_PI * 2;
    else if( angle < -M_PI ) angle += M_PI * 2;
    return fabs( angle ) * sqrtf( dx1 * dx1 + dy1 * dy1 );
}

- (CGFloat)calculateDirectedArcDistanceBetween:(CGPoint)point1 point2:(CGPoint)point2 center:(CGPoint)center
{
    CGFloat dx1 = point1.x - center.x;
    CGFloat dy1 = point1.y - center.y;
    CGFloat dx2 = point2.x - center.x;
    CGFloat dy2 = point2.y - center.y;
    CGFloat angle1 = atan2f( dy1, dx1 );
    CGFloat angle2 = atan2f( dy2, dx2 );
    CGFloat angle = angle1 - angle2;
    if( angle < 0 ) angle += M_PI * 2;
    return angle * sqrtf( dx1 * dx1 + dy1 * dy1 );
}

Most of the tricky bit is making sure the ranges are correct (atan2 gives values from -pi to +pi, so after getting the difference between two angles we must re-normalise them)

Upvotes: 2

Related Questions