Skip to content

NearestPoint #15

@tsukasa1989

Description

@tsukasa1989

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);
            }
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions