AStar Pathfinding, find nearest node to target

I am working with the Aron Granberg AStar Pathfinding asset, using the grid graph. Right now when I click on a target (like a monster) my player moves to the same node as the target, thus being on top on the target. What I want is to stop the player moving 1 node before the target, the adjacent node that would be closest to the player. The code that I have found looks something like this:

if (Physics.Raycast(ray, out hit))
{
    Interactable interactable = hit.collider.GetComponent<Interactable>();
     if (interactable != null)
     {
         GraphNode nearestNode = AstarPath.active.GetNearest(gameObject.transform.position, NNConstraint.Default).node;
         if (nearestNode.Walkable)
         {
              Int3 a = new Int3();
              Vector3 b = (Vector3)a;
                           
               ai.destination = b;
           }
       }
}

the whole GraphNode line gets the node (I think) but I am not sure how to translate that into the code just below that. I am not even sure if this is the right code to be using. Does anyone know how to make this work?

Nvm, figured it out for the most part.

Int3 a = new Int3(focus.transform.position);
Vector3 b = (Vector3)a;
                           
ai.destination = b;

only small issue I have now, this code pulls all 8 nodes around the target. The 4 nodes up, down, left, and right, as well as the 4 nodes in a diagonal line. So now the question becomes, how do I just get the 4 nodes in the up, down, left, right?

I think if I can find all nodes within a range of 1 then I can find the ones I want since the 4 corner nodes would be somewhere around 1.5. Does anyone know how I could add in a distance check for the nodes?

1 Like