A* Pathfinding Project  4.1.11
The A* Pathfinding Project for Unity 3D
MultiTargetPath Class Reference

A path which searches from one point to a number of different targets in one search or from a number of different start points to a single target. More...

Detailed Description

A path which searches from one point to a number of different targets in one search or from a number of different start points to a single target.

This is faster than searching with an ABPath for each target if pathsForAll is true. This path type can be used for example when you want an agent to find the closest target of a few different options.

When pathsForAll is true, it will calculate a path to each target point, but it can share a lot of calculations for the different paths so it is faster than requesting them separately.

When pathsForAll is false, it will perform a search using the heuristic set to None and stop as soon as it finds the first target. This may be faster or slower than requesting each path separately. It will run a Dijkstra search where it searches all nodes around the start point until the closest target is found. Note that this is usually faster if some target points are very close to the start point and some are very far away, but it can be slower if all target points are relatively far away because then it will have to search a much larger region since it will not use any heuristics.

A* Pro Feature:
This is an A* Pathfinding Project Pro feature only. This function/class/variable might not exist in the Free version of the A* Pathfinding Project or the functionality might be limited
The Pro version can be bought here

See also
Seeker.StartMultiTargetPath
Example of how to use multi-target-paths
Version
Since 3.7.1 the vectorPath and path fields are always set to the shortest path even when pathsForAll is true.

Public Types

enum  HeuristicMode {
  None, Average, MovingAverage, Midpoint,
  MovingMidpoint, Sequential
}
 

Public Member Functions

 MultiTargetPath ()
 Default constructor. More...
 
- Public Member Functions inherited from ABPath
 ABPath ()
 Default constructor. More...
 
- Public Member Functions inherited from Path
void BlockUntilCalculated ()
 Blocks until this path has been calculated and returned. More...
 
void Claim (System.Object o)
 Claim this path (pooling). More...
 
void Error ()
 Aborts the path because of an error. More...
 
PathState GetState ()
 Returns the state of the path in the pathfinding pipeline. More...
 
float GetTotalLength ()
 Total Length of the path. More...
 
bool IsDone ()
 Returns if this path is done calculating. More...
 
void Release (System.Object o, bool silent=false)
 Releases a path claim (pooling). More...
 
IEnumerator WaitForPath ()
 Waits until this path has been calculated and returned. More...
 

Static Public Member Functions

static MultiTargetPath Construct (Vector3[] startPoints, Vector3 target, OnPathDelegate[] callbackDelegates, OnPathDelegate callback=null)
 
static MultiTargetPath Construct (Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callback=null)
 
- Static Public Member Functions inherited from ABPath
static ABPath Construct (Vector3 start, Vector3 end, OnPathDelegate callback=null)
 Construct a path with a start and end point. More...
 

Public Attributes

OnPathDelegate [] callbacks
 Callbacks to call for each individual path. More...
 
int chosenTarget = -1
 The closest target index (if any target was found) More...
 
HeuristicMode heuristicMode = HeuristicMode.Sequential
 How to calculate the heuristic. More...
 
List< GraphNode > [] nodePaths
 Stores all paths to the targets. More...
 
Vector3 [] originalTargetPoints
 Target points specified when creating the path. More...
 
bool pathsForAll = true
 If true, a path to all targets will be returned, otherwise just the one to the closest one. More...
 
GraphNode [] targetNodes
 Nearest nodes to the targetPoints. More...
 
Vector3 [] targetPoints
 Target points specified when creating the path. More...
 
bool [] targetsFound
 Indicates if the target has been found. More...
 
List< Vector3 > [] vectorPaths
 Stores all vector paths to the targets. More...
 
- Public Attributes inherited from ABPath
bool calculatePartial
 Calculate partial path if the target node cannot be reached. More...
 
GraphNode endNode
 End node of the path. More...
 
Vector3 endPoint
 End point of the path. More...
 
Vector3 originalEndPoint
 End Point exactly as in the path request. More...
 
Vector3 originalStartPoint
 Start Point exactly as in the path request. More...
 
Int3 startIntPoint
 Start point in integer coordinates. More...
 
GraphNode startNode
 Start node of the path. More...
 
Vector3 startPoint
 Start point of the path. More...
 
- Public Attributes inherited from Path
OnPathDelegate callback
 Callback to call when the path is complete. More...
 
int enabledTags = -1
 Which graph tags are traversable. More...
 
Heuristic heuristic
 Determines which heuristic to use. More...
 
float heuristicScale = 1F
 Scale of the heuristic values. More...
 
OnPathDelegate immediateCallback
 Immediate callback to call when the path is complete. More...
 
NNConstraint nnConstraint = PathNNConstraint.Default
 Constraint for how to search for nodes. More...
 
List< GraphNodepath
 Holds the path as a Node array. More...
 
ITraversalProvider traversalProvider
 Provides additional traversal information to a path request. More...
 
List< Vector3 > vectorPath
 Holds the (possibly post processed) path as a Vector3 list. More...
 

Protected Member Functions

override void CalculateStep (long targetTick)
 Calculates the path until completed or until the time has passed targetTick. More...
 
override void Cleanup ()
 Always called after the path has been calculated. More...
 
void FoundTarget (PathNode nodeR, int i)
 
override void Initialize ()
 Initializes the path. More...
 
override void OnEnterPool ()
 Called when the path enters the pool. More...
 
override void Prepare ()
 Prepares the path. More...
 
void RebuildOpenList ()
 
override void Reset ()
 Reset all values to their default values. More...
 
override void ReturnPath ()
 Calls callback to return the calculated path. More...
 
void Setup (Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callback)
 
override void Trace (PathNode node)
 Traces the calculated path from the end node to the start. More...
 
- Protected Member Functions inherited from ABPath
virtual void CompletePathIfStartIsValidTarget ()
 Checks if the start node is the target and complete the path if that is the case. More...
 
virtual bool EndPointGridGraphSpecialCase (GraphNode closestWalkableEndNode)
 Applies a special case for grid nodes. More...
 
void UpdateStartEnd (Vector3 start, Vector3 end)
 Sets the start and end points. More...
 
void Setup (Vector3 start, Vector3 end, OnPathDelegate callbackDelegate)
 
- Protected Member Functions inherited from Path
void DebugStringPrefix (PathLog logMode, System.Text.StringBuilder text)
 Writes text shared for all overrides of DebugString to the string builder. More...
 
void DebugStringSuffix (PathLog logMode, System.Text.StringBuilder text)
 Writes text shared for all overrides of DebugString to the string builder. More...
 
void PrepareBase (PathHandler pathHandler)
 Prepares low level path variables for calculation. More...
 

Protected Attributes

int targetNodeCount
 Number of target nodes left to find. More...
 
- Protected Attributes inherited from ABPath
int [] endNodeCosts
 Saved original costs for the end node. More...
 
PathNode partialBestTarget
 Current best target for the partial path. More...
 
- Protected Attributes inherited from Path
PathCompleteState completeState
 Backing field for CompleteState. More...
 
PathNode currentR
 The node currently being processed. More...
 
bool hasBeenReset
 True if the Reset function has been called. More...
 
Int3 hTarget
 Target to use for H score calculations. More...
 
GraphNode hTargetNode
 Target to use for H score calculation. More...
 
int [] internalTagPenalties
 The tag penalties that are actually used. More...
 
int [] manualTagPenalties
 Tag penalties set by other scripts. More...
 
PathHandler pathHandler
 Data for the thread calculating this path. More...
 

Package Functions

override string DebugString (PathLog logMode)
 Returns a debug string for this path. More...
 
- Package Functions inherited from ABPath
override uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost)
 May be called by graph nodes to get a special cost for some connections. More...
 
- Package Functions inherited from Path
uint CalculateHScore (GraphNode node)
 Estimated cost from the specified node to the target. More...
 
bool CanTraverse (GraphNode node)
 Returns if the node can be traversed. More...
 
void FailWithError (string msg)
 Causes the path to fail and sets errorLog to msg. More...
 
Int3 GetHTarget ()
 
uint GetTagPenalty (int tag)
 Returns penalty for the given tag. More...
 
uint GetTraversalCost (GraphNode node)
 
void Log (string msg)
 Appends a message to the errorLog. More...
 
void LogError (string msg)
 Logs an error. More...
 
void ReleaseSilent (System.Object o)
 Releases the path silently (pooling). More...
 

Properties

bool inverted [get, protected set]
 False if the path goes from one point to multiple targets. More...
 
- Properties inherited from ABPath
virtual bool hasEndPoint [get]
 Determines if a search for an end node should be done. More...
 
- Properties inherited from Path
PathCompleteState CompleteState [get, protected set]
 Current state of the path. More...
 
bool error [get]
 If the path failed, this is true. More...
 
string errorLog [get, private set]
 Additional info on why a path failed. More...
 
virtual bool FloodingPath [get]
 True for paths that want to search all nodes and not jump over nodes as optimizations. More...
 
PathHandler IPathInternals. PathHandler [get]
 
ushort pathID [get, private set]
 ID of this path. More...
 
PathState PipelineState [get, private set]
 Returns the state of the path in the pathfinding pipeline. More...
 
bool IPathInternals. Pooled [get, set]
 True if the path is currently pooled. More...
 
bool recycled [get]
 True if the path is currently recycled (i.e in the path pool). More...
 
int [] tagPenalties [get, set]
 Penalties for each tag. More...
 
- Properties inherited from IPathInternals
PathHandler PathHandler [get]
 
bool Pooled [get, set]
 

Private Member Functions

void ChooseShortestPath ()
 Set chosenTarget to the index of the shortest path. More...
 
void RecalculateHTarget (bool firstTime)
 
void ResetFlags ()
 Reset flag1 on all nodes after the pathfinding has completed (no matter if an error occurs or if the path is canceled) More...
 
void SetPathParametersForReturn (int target)
 

Private Attributes

int sequentialTarget
 Current target for Sequential heuristicMode. More...
 

Additional Inherited Members

- Package Attributes inherited from Path
float duration
 How long it took to calculate this path in milliseconds. More...
 
Path next
 Internal linked list implementation. More...
 
int searchedNodes
 Number of nodes this path has searched. More...
 

Member Enumeration Documentation

◆ HeuristicMode

enum HeuristicMode
strong
Enumerator
None 
Average 
MovingAverage 
Midpoint 
MovingMidpoint 
Sequential 

Constructor & Destructor Documentation

◆ MultiTargetPath()

Default constructor.

Do not use this. Instead use the static Construct method which can handle path pooling.

Member Function Documentation

◆ CalculateStep()

override void CalculateStep ( long  targetTick)
protectedvirtual

Calculates the path until completed or until the time has passed targetTick.

Usually a check is only done every 500 nodes if the time has passed targetTick. Time/Ticks are got from System.DateTime.UtcNow.Ticks.

Basic outline of what the function does for the standard path (Pathfinding.ABPath).

while the end has not been found and no error has occurred
check if we have reached the end
if so, exit and return the path
open the current node, i.e loop through its neighbours, mark them as visited and put them on a heap
check if there are still nodes left to process (or have we searched the whole graph)
if there are none, flag error and exit
pop the next node of the heap and set it as current
check if the function has exceeded the time limit
if so, return and wait for the function to get called again

Reimplemented from ABPath.

◆ ChooseShortestPath()

void ChooseShortestPath ( )
private

Set chosenTarget to the index of the shortest path.

◆ Cleanup()

override void Cleanup ( )
protectedvirtual

Always called after the path has been calculated.

Guaranteed to be called before other paths have been calculated on the same thread. Use for cleaning up things like node tagging and similar.

Reimplemented from ABPath.

◆ Construct() [1/2]

static MultiTargetPath Construct ( Vector3 []  startPoints,
Vector3  target,
OnPathDelegate []  callbackDelegates,
OnPathDelegate  callback = null 
)
static

◆ Construct() [2/2]

static MultiTargetPath Construct ( Vector3  start,
Vector3 []  targets,
OnPathDelegate []  callbackDelegates,
OnPathDelegate  callback = null 
)
static

◆ DebugString()

override string DebugString ( PathLog  logMode)
packagevirtual

Returns a debug string for this path.

Reimplemented from ABPath.

◆ FoundTarget()

void FoundTarget ( PathNode  nodeR,
int  i 
)
protected

◆ Initialize()

override void Initialize ( )
protectedvirtual

Initializes the path.

Sets up the open list and adds the first node to it

Reimplemented from ABPath.

◆ OnEnterPool()

override void OnEnterPool ( )
protectedvirtual

Called when the path enters the pool.

This method should release e.g pooled lists and other pooled resources The base version of this method releases vectorPath and path lists. Reset() will be called after this function, not before.

Warning
Do not call this function manually.

Reimplemented from Path.

◆ Prepare()

override void Prepare ( )
protectedvirtual

Prepares the path.

Searches for start and end nodes and does some simple checking if a path is at all possible

Reimplemented from ABPath.

◆ RebuildOpenList()

void RebuildOpenList ( )
protected

◆ RecalculateHTarget()

void RecalculateHTarget ( bool  firstTime)
private

◆ Reset()

override void Reset ( )
protectedvirtual

Reset all values to their default values.

All inheriting path types must implement this function, resetting ALL their variables to enable recycling of paths. Call this base function in inheriting types with base.Reset ();

Reimplemented from ABPath.

◆ ResetFlags()

void ResetFlags ( )
private

Reset flag1 on all nodes after the pathfinding has completed (no matter if an error occurs or if the path is canceled)

◆ ReturnPath()

override void ReturnPath ( )
protectedvirtual

Calls callback to return the calculated path.

See also
callback

Reimplemented from Path.

◆ SetPathParametersForReturn()

void SetPathParametersForReturn ( int  target)
private

◆ Setup()

void Setup ( Vector3  start,
Vector3 []  targets,
OnPathDelegate []  callbackDelegates,
OnPathDelegate  callback 
)
protected

◆ Trace()

override void Trace ( PathNode  from)
protectedvirtual

Traces the calculated path from the end node to the start.

This will build an array (path) of the nodes this path will pass through and also set the vectorPath array to the path arrays positions. Assumes the vectorPath and path are empty and not null (which will be the case for a correctly initialized path).

Reimplemented from Path.

Member Data Documentation

◆ callbacks

OnPathDelegate [] callbacks

Callbacks to call for each individual path.

◆ chosenTarget

int chosenTarget = -1

The closest target index (if any target was found)

◆ heuristicMode

How to calculate the heuristic.

The heuristic target point can be calculated in different ways, by taking the Average position of all targets, or taking the mid point of them (i.e center of the AABB encapsulating all targets).

The one which works best seems to be Sequential, it sets hTarget to the target furthest away, and when that target is found, it moves on to the next one.
Some modes have the option to be 'moving' (e.g 'MovingAverage'), that means that it is updated every time a target is found.
The H score is calculated according to AstarPath.heuristic

Note
If pathsForAll is false then this option is ignored and it is always treated as being set to None

◆ nodePaths

List<GraphNode> [] nodePaths

Stores all paths to the targets.

Elements are null if no path was found

◆ originalTargetPoints

Vector3 [] originalTargetPoints

Target points specified when creating the path.

These are not snapped to the nearest nodes

◆ pathsForAll

bool pathsForAll = true

If true, a path to all targets will be returned, otherwise just the one to the closest one.

◆ sequentialTarget

int sequentialTarget
private

Current target for Sequential heuristicMode.

Refers to an item in the targetPoints array

◆ targetNodeCount

int targetNodeCount
protected

Number of target nodes left to find.

◆ targetNodes

GraphNode [] targetNodes

Nearest nodes to the targetPoints.

◆ targetPoints

Vector3 [] targetPoints

Target points specified when creating the path.

These are snapped to the nearest nodes

◆ targetsFound

bool [] targetsFound

Indicates if the target has been found.

Also true if the target cannot be reached (is in another area)

◆ vectorPaths

List<Vector3> [] vectorPaths

Stores all vector paths to the targets.

Elements are null if no path was found

Property Documentation

◆ inverted

bool inverted
getprotected set

False if the path goes from one point to multiple targets.

True if it goes from multiple start points to one target point


The documentation for this class was generated from the following file: