Updating walkable areas at runtime

I’m making 2d game and using grid graph. Is it possible to make agent follow moving target from behind?
I have enemy target, and i added to him UpdateGraphScene script and added point in front of enemy and put hit penalty. So when agent try to follow enemy, it will try to get from behind because in front of him there are point with high penalty. But it’s not working, the problem is enemy is always moving and those points are not updating in game. I tried putting GetComponent().Apply() in enemy’s update method, but everything is working very poorly and with huge delay.
Is the any other ways of implementing this following moving target from behind mechanic?

Hi

I would not do that using graph updates, instead I would just set the destination to a point a few units behind the agent. Or perhaps you could store the position of the enemy every second or so and then make the character first move to where the enemy was a few seconds ago.

Then agent will choose shortest way and in situations like this will go straightly towards enemy’s facing direction.
Is there any way to add invisible obstackles in front of enemy which updates let’s say twice per second?

Ah, I see.

For this use case I would recommend using the ITraversalProvider.

For example:

public class AvoidanceProvider : ITraversalProvider {
    public Vector3 pointToAvoid;
    public float radius;
    public uint penalty;

    // True if the given node can be traversed
    bool CanTraverse(Path path, GraphNode node) {
        return DefaultITraversalProvider.CanTraverse(path, node);
    }

    // Cost of traversing a given node
    // This is in addition to the cost of going between two nodes, which is 1000 times the world space distance between the nodes
    uint GetTraversalCost(Path path, GraphNode node) {
        uint currentPenalty = DefaultITraversalProvider.GetTraversalCost(path, node);
        if (((Vector3)node.position - pointToAvoid).sqrMagnitude < radius*radius) {
            currentPenalty += this.penalty;
        }
        return currentPenalty;
    }
}


void Start () {
    // Disable the AI's own path recalculation code
    ai.canSearch = false;
    // Create a new path instance with a traversal provider
    var path = ABPath.Construct(ai.position, ai.destination, null);
    path.traversalProvider = new AvoidanceProvider {
        pointToAvoid = new Vector3(1, 0, 0),
        radius=5,
        penalty=10000,
    };
    // Make the agent calculate the path
    ai.SetPath(path);
}

You can read more about the ITraversalProvider at the bottom of this page: https://arongranberg.com/astar/docs/turnbased.html#ITraversalProvider

You can also of course write more sophisticated penalty code than just adding a fixed cost when inside a given radius from a point.

Note also that this code will be called from a separate thread if you have multithreading enabled.