# Get node closest to given vector3.

I need to modify a GetNode method to return the closest node to the vector3 specified. At the moment, it returns the node at the given vector. For example, if I was to call GetNode(new Vector3(300,0,50)), and there is no node at that point, it will return the closest node, like (200,0,30). Can anyone tell me how to do this? The things I’ve tried haven’t worked.

``````public Node GetNode(Vector3 pos)
{
//Searches for a node with a specific vector.
Vector3 roundedPos = new Vector3(Mathf.FloorToInt(pos.x), Mathf.FloorToInt(pos.y), Mathf.FloorToInt(pos.z));

for(int i = 0; i < gridLength; i++)
{
for(int j = 0; j < gridWidth; j++)
{
if(grid[i,j].pos == roundedPos)
return grid[i,j];
}
}
return new Node(pos, true, new Vector2(pos.x, pos.z));
}
``````

Searching for the closest position / smallest value has been asked several times here. It’ss really not difficult:

``````public Node GetNode(Vector3 pos)
{
Vector3 roundedPos = new Vector3(Mathf.FloorToInt(pos.x), Mathf.FloorToInt(pos.y), Mathf.FloorToInt(pos.z));
float minDist = float.PositiveInfinity;
Node closestNode = null;
for(int i = 0; i < gridLength; i++)
{
for(int j = 0; j < gridWidth; j++)
{
float sqrDist = (grid[i,j].pos - roundedPos).sqrMagnitude;
if (sqrDist < minDist)
{
minDist = sqrDist;
closestNode = grid[i,j];
}
}
}
return closestNode;
}
``````