Find nearest child Component

I don’t see any method in Component for finding the closest child Component to a Point. Has anyone done this before? I was thinking of either:

  1. Iterating through the array of children, calculating their distances, and finding the smallest one; or
  2. Starting at the given point, using getComponentAt() to see if it matches a child, and if not pick a new point, spiraling outwards.

1 seems easier; 2 seems more efficient. I have no problems cobbling together one of these methods, but I thought I’d check here for advice first, as it seems like the sort of thing that must have been done before.

Eventually you will have to check every component, so version 1 seems plausible.

And I guess you won’t find that method, since it is not defined, what “closest Component” means. Distance from the origin? from the centre? or from any point on the rectangle’s edges?

Once you know, how to determine the distance, it should be trivial.

I’m calculating the distance between some Point given in the argument and the center of any child Component. I agree that it should be pretty simple. I just wanted to check that I wasn’t missing something in Component or some related class, because many times I’ve written something “simple” only to find that it’s already implemented somewhere in the JUCE library.

I’ve made a mock-up of version 1 already; as @daniel says, it’s pretty simple.

Component* findClosestComponent (Point<int> point)
    auto currentClosestDistance = std::numeric_limits<int>::max();

    Component* currentClosestComponent = nullptr;

    for (auto child : getChildren())
        auto distanceFromPoint = point.getDistanceFrom(child->getBounds().getCentre());

        if (distanceFromPoint < currentClosestDistance)
            currentClosestDistance = distanceFromPoint;

            currentClosestComponent = child;
    return currentClosestComponent;

EDIT: I intend to add to this function so that it first checks whether there is a child Component sitting at the point, because in my scenario 9 times out of 10 there will be and I can then skip a lot of iterations.

Again, the only thing I’m really looking for here it to see whether there is some function like this already built into JUCE.

Well, considering that there will always be considerable more pixels than components, I don’t think it is worth pursuing the second option, unless you do that on graphics hardware. This approach was actually used in complex 3-D scenes, when you shoot a ray through the scene and check for collisions.