UpdateGraphsNoBlock lags behind


I’m trying to set up a simple tower defense game and I want to stop the player from blocking the enemy path. I know there are functions to figure this out, like PathUtilities.IsPathPossible and UpdateGraphsNoBlock, the one I decided to go with. But I can’t for the life of me get them to work like how I want them to work.

To start with, here’s the code I’m using.
Here’s from the actual tower placer:

gridPosition = lastPlacementArea.WorldToGrid(placeLocation.position, Vector2Int.one);
worldPosition = lastPlacementArea.GridToWorld(gridPosition, Vector2Int.one);

if (gridPosition != previousGridPosition)
    ghosts[selectedTower].transform.position = worldPosition;
    gridObstacle.transform.position = worldPosition;

    previousGridPosition = gridPosition;
    Debug.Log("GRID CHANGED: " + PathController.Instance.IsPathPossible(ghosts[selectedTower].GetComponent<Collider>().bounds));

(the WorldToGrid/GridToWorld functions are not important in this matter)

And here’s the code from the PathController that is referenced in the code above:

public bool IsPathPossible(Bounds bounds)
    GraphNode node1 = AstarPath.active.GetNearest(startPoint.position, NNConstraint.Default).node;
    GraphNode node2 = AstarPath.active.GetNearest(endPoint.position, NNConstraint.Default).node;

    return GraphUpdateUtilities.UpdateGraphsNoBlock(new GraphUpdateObject(bounds), node1, node2, true);

I have a grid where the player can place towers. I only want to do a “can place check” every time the “grid position” changes since I believe that’s the most performant. No need to check every frame if nothing is changing. When placing a tower, there’s a ghost for said tower. The tower has a collider and is on a layer the Grid Graph can detect.

Now here’s where it gets annoying. If I place a tower in a position that is blocking, it thinks it’s fine. There’s no blocking path, according to the graph. But if I move it to any other position, so be a blocking position to non-blocking, it will say it is blocked. It’s like it’s always a step behind. What am I doing wrong?

I’ve partially solved this by just using PathUtilities.IsPathPossible and having a delay between when the tower moved due to the update time on DynamicGridObstacle (not used in the issue above) and when the player can place it, but the delay, even if very small, is still noticeable during gameplay. So I would like to have something more instant.



It is possible that the physics engine is lagging behind. Try to run

// Make sure the physics engine data is up to date

Before you run UpdateGraphsNoBlock. Let me know how it goes.

That seems to have done the trick. Thank you!

I will add some code to do this automatically in the next version.

1 Like