objective-ccocoadistancenspoint

What is the best way to find which NSPoint another NSPoint is closest to?


I have 4 NSPoints, which are 4 corners of a rectangle

Now I have another NSPoint, which is where the mouse goes down (mousedown_nsp).

What is the best way for me to find the closest NSPoint (out of the 4 rectangle corner NSPoints) in relation to mousedown_nsp?

I was thinking of just doing a comparison to find the distance between mousedown_nsp and the other 4 NSPoints, then choosing the smallest distance, but I feel like there has got to be a better way.

Any ideas?

Thanks in advance!


Solution

  • Perhaps something like this (this assumes a non-rotated rectangle):

    NSPoint tl = ... // top-left corner
    NSPoint tr = ... // top-right corner
    NSPoint bl = ... // bottom-left corner
    NSPoint br = ... // bottom-right corner
    NSPoint pt = ... // the point
    
    NSPoint center = NSMakePoint((tl.x + tr.x) / 2.0, (tl.y + bl.y) / 2.0);
    NSPoint closest;
    if (pt.x < center.x) {
        if (pt.y < center.y) {
            closest = tl; // point is in upper-left quadrant
        } else {
            closest = bl; // point is in lower-left quadrant
        }
    } else {
        if (pt.y < center.y) {
            closest = tr; // point is in upper-right quadrant
        } else {
            closest = br; // point is in lower-right quadrant
        }
    }