NetOctree icon indicating copy to clipboard operation
NetOctree copied to clipboard

NearestPoint

Open tsukasa1989 opened this issue 1 year ago • 0 comments

I am trying to implement a NearestPoint in the PointOctree, but running into an issue that it not always find the right closest point. Any suggestions?


private Vector3 _cache = new Vector3();

public void GetClosest(ref Vector3 position, ref T closest, ref float closestDistanceSq)
{
    // Check if the current node's bounds are closer than the closest distance found so far
    // Check the distance from the position to the current node's bounds
    float distanceToNodeSq = Vector3.DistanceSquared(_bounds.ClosestPointOnBounds(position, _cache), position);

    // If this distance is greater than the closest distance found so far, no need to search this node
    if (distanceToNodeSq >= closestDistanceSq)
    {
        return;
    }

    // Check against any objects in this node
    foreach (var obj in _objects)
    {
        float distanceToObjectSq = Vector3.DistanceSquared(position, obj.Pos);
        if (distanceToObjectSq < closestDistanceSq)
        {
            closestDistanceSq = distanceToObjectSq;
            closest = obj.Obj; // Update the closest object
        }
    }

    // Check children, if any
    if (_children != null)
    {
        for (int i = 0; i < 8; i++)
        {
            float distanceToChildSq = Vector3.DistanceSquared(_children[i]._bounds.ClosestPointOnBounds(position, _cache), position);
            if (distanceToChildSq < closestDistanceSq)
            {
                _children[i].GetClosest(ref position, ref closest, ref closestDistanceSq);
            }
        }
    }
}

tsukasa1989 avatar Mar 02 '24 12:03 tsukasa1989