Calculating a path's traversal cost

As the title indicates I want to calculate a path’s traversal cost.

`public float LocationCost(Vector3 location)
	{
		ABPath path = ABPath.Construct(gameObject.transform.position, location, null);
		float cost = 0;
		for (int i = 0; i < path.path.Count; i++) {
			cost += path.GetTraversalCost(path.path[i]);
		}
		return cost;
	}`

This returns 0 no matter what. What am I doing wrong?

Thanks

Hi

  1. That path is not calculated yet, you have to do
    `
    ABPath path = …
    seeker.StartPath ( path, … );

// This blocks until the path is completed, if you are not so patient to wait a few frames
AstarPath.WaitForPath ( path );

// calculate cost
`

The traversal cost that is returned from that method is only the cost for actually walking on the node, not moving between two nodes. So it will return the penalty of the node basically.

What you want is basically the length of the path added to the value you calculated above because the length of the edges between the nodes is used as the cost.

`
ABPath path = …
seeker.StartPath ( path, … );

// This blocks until the path is completed, if you are not so patient to wait a few frames
AstarPath.WaitForPath ( path );

// calculate length scaled by the same factor as is used in the rest of the system
float approximateCost = path.GetTotalLength () * Int3.Precision;

// add penalties
for (int i = 0; i < path.path.Count; i++) {
approximateCost += path.GetTraversalCost(path.path[i]);
}
`

Hi @aron_granberg,

I realize this is a rather old thread. I need a way of costing the path to each target so I can factor it into my target selection algorithm (which considers other things too, such as health for example).

The code you posted above looks simple enough but I just noticed that the GetTraversalCost method isn’t public anymore. Is there an alternative approach which is preferable these days?

Thanks for your help.

1 Like

Would be interested in this too - need to calculate path costs to find lowest cost from different starting points…