从另一个点计算最近点的最佳方法?

时间:2014-03-06 17:17:48

标签: ios iphone objective-c xcode drawing

我有四点说_pointA _pointB _pointC _pointD。我想从当前点找到最近的点。我有类似的东西,但它有时会产生错误的结果。

问题:当我靠近pointA时,它会pointC

 CGPoint neastPoint=CGPointZero;
for (int i=0; i<3; i++) {
    CGFloat x;
    CGFloat y;
    CGFloat currntDistance;
    if (i==0){
        x=(pointA.x-currentPoint.x) *(pointA.x-currentPoint.x);
        y=(pointA.y-currentPoint.y)*(pointA.y-currentPoint.y);
        currntDistance =sqrtf(x+y);
        distance=currntDistance;
        neastPoint=pointA;

    }
    else if (i==1){
        x=(pointB.x-currentPoint.x) *(pointB.x-currentPoint.x);
        y=(pointB.y-currentPoint.y)*(pointB.y-currentPoint.y);
        currntDistance =sqrtf(x+y);
        if (distance>currntDistance) {
            distance=currntDistance;
            neastPoint=pointB;
        }
    }
    else  if (i==2){
        x=(pointC.x-currentPoint.x) *(pointC.x-currentPoint.x);
        y=(pointC.y-currentPoint.y)*(pointC.y-currentPoint.y);
        currntDistance =sqrtf(x+y);
        if (distance>currntDistance) {
            distance=currntDistance;
            neastPoint=pointC;
        }
    }
    else {
        x=(pointD.x-currentPoint.x) *(pointD.x-currentPoint.x);
        y=(pointD.y-currentPoint.y)*(pointD.y-currentPoint.y);
        currntDistance =sqrtf(x+y);
        if (distance>currntDistance) {
            distance=currntDistance;
            neastPoint=pointD;
        }

    }



 CurrentPoint : {44, 33.140846}
Point A : {71, 178}
Point B : {134, 178}
Point C : {133, 71}
Point D : {75, 67}
Nearast Point  : {133, 71}

2 个答案:

答案 0 :(得分:3)

根据您提供的积分,pointD最接近currentPoint。 您的代码找不到它,因为

for (int i=0; i<3; i++) {

应该是

for (int i=0; i<4; i++) {

检查所有4分。正如其他人注意到的那样,您可以简化代码, 例如

CGFloat distance = FLT_MAX; // start with some large value 
CGPoint nearestPoint;

CGPoint points[] = { pointA, pointB, pointC, pointD };
for (int i = 0; i < 4; i++) {
    CGFloat currentDistance = hypotf(points[i].x - currentPoint.x, points[i].y - currentPoint.y);
    if (currentDistance < distance) {
        distance = currentDistance;
        nearestPoint = points[i];
    }
}

答案 1 :(得分:1)

伪:

Point[] allPoints = {poinA,pontB,pointC,....,pointN}

int distance = Int.MAX_VALUE;
Point nearestPoint = null;

for(int i = 0 ; i < allPoints.count;i++){
     if(pointA != allPoints[i]){
      int currentDistance = getDistance(pointA,allPoints[i]);
       if(currentDistance < distance){
          distance = currentDistance;
          nearestPoint = allPoints[i];
       }
     }
   }

print("Nearest point is " + nearestPoint);