1

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!

A O
  • 5,516
  • 3
  • 33
  • 68
  • 2
    In order to find a minimum, you have to compare against all other values. There's no way around it. (You can try to refactor the loop into a functional-style something if that's your taste, but you can't really do it faster than `O(n)`.) – The Paramagnetic Croissant Jul 07 '14 at 19:30
  • 3
    Think of it this way - take your rectangle and split it into four equal quadrants. Which ever of the 4 quadrants your point lies in, the point will be closest to that corner. No need to calculate actual distances. It's fairly simple if the rectangle is not rotated at all. – rmaddy Jul 07 '14 at 19:33
  • @rmaddy , so I should create 4 smaller rectangles around the 4 corners, and find which rectangle the mouse is in? Is there a method I could call that finds whether or not a point lies within a rectangle? – A O Jul 07 '14 at 19:39
  • @MattyAyOh Please **use Google.** `NSRectContainsPoint()` is your friend. – The Paramagnetic Croissant Jul 07 '14 at 19:43
  • 1
    @user3477950 Such function does not exist. `NSPointInRect` is the correct name. – hamstergene Jul 07 '14 at 19:51
  • 1
    How would you define "better way"? I see no problem with taking the point whose squared distance to mousedown_nsp is least. –  Jul 07 '14 at 20:54
  • @Jessy, I just wanted to use the best practice because I'm new and want to learn. That was what I originally had, but it felt too easy and I wasn't sure if there was a more efficient way – A O Jul 07 '14 at 21:04

1 Answers1

2

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
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579