nearestTo method

T? nearestTo(
  1. Vector2 position, {
  2. Node? excluded,
})

The element nearest to position, or null if this is empty.

position is in scene space, so the elements need not share a parent.

If excluded is provided, skips that node during traversal.

Implementation

T? nearestTo(Vector2 position, {Node? excluded}) {
  T? closest;
  var closestDistance2 = double.infinity;

  for (final element in this) {
    if (identical(element, excluded)) continue;

    final distance2 = element.absoluteCenter.distance2(position);

    if (distance2 < closestDistance2) {
      closest = element;
      closestDistance2 = distance2;
    }
  }

  return closest;
}