A* Pathfinding Project  3.6.6
The A* Pathfinding Project for Unity 3D
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Properties Events Macros Groups Pages
RecastGraph Class Reference

Automatically generates navmesh graphs based on world geometry. More...

Detailed Description

Automatically generates navmesh graphs based on world geometry.

The recast graph is based on Recast (http://code.google.com/p/recastnavigation/).
I have translated a good portion of it to C# to run it natively in Unity. The Recast process is described as follows:

  • The voxel mold is build from the input triangle mesh by rasterizing the triangles into a multi-layer heightfield. Some simple filters are then applied to the mold to prune out locations where the character would not be able to move.
  • The walkable areas described by the mold are divided into simple overlayed 2D regions. The resulting regions have only one non-overlapping contour, which simplifies the final step of the process tremendously.
  • The navigation polygons are peeled off from the regions by first tracing the boundaries and then simplifying them. The resulting polygons are finally converted to convex polygons which makes them perfect for pathfinding and spatial reasoning about the level.

It works exactly like that in the C# version as well, except that everything is triangulated to triangles instead of n-gons. The recast generation process usually works directly on the visiable geometry in the world, this is usually a good thing, because world geometry is usually more detailed than the colliders. You can however specify that colliders should be rasterized, if you have very detailed world geometry, this can speed up the scan.

Check out the second part of the Get Started Tutorial which discusses recast graphs.

In the editor there is a button for exporting the generated graph to a .obj file. Usually the generation process is good enough for the game directly, but in some cases you might want to edit some minor details. So you can export the graph to a .obj file, open it in your favourite 3D application, edit it, and export it to a mesh which Unity can import. You can then use that mesh in a navmesh graph.

Since many 3D modelling programs use different axis systems (unity uses X=right, Y=up, Z=forward), it can be a bit tricky to get the rotation and scaling right. For blender for example, what you have to do is to first import the mesh using the .obj importer. Don't change anything related to axes in the settings. Then select the mesh, open the transform tab (usually the thin toolbar to the right of the 3D view) and set Scale -> Z to -1. If you transform it using the S (scale) hotkey, it seems to set both Z and Y to -1 of some reason. Then make the edits you need and export it as an .obj file to somewhere in the Unity project. But this time, edit the setting named "Forward" to "Z forward" (not -Z as it is per default).

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

Classes

class  CapsuleCache
 
class  NavmeshTile
 
struct  SceneMesh
 Represents a unity mesh. More...
 

Public Types

enum  RelevantGraphSurfaceMode { DoNotRequire, OnlyForCompletelyInsideTile, RequireForAll }
 

Public Member Functions

void AddPortal (GraphNode n1, GraphNode n2, List< Vector3 > left, List< Vector3 > right)
 
void BuildFunnelCorridor (List< GraphNode > path, int startIndex, int endIndex, List< Vector3 > left, List< Vector3 > right)
 
GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o)
 
Vector3 ClosestPointOnNode (TriangleMeshNode node, Vector3 pos)
 Returns the closest point of the node.
 
void ConnectTileWithNeighbours (NavmeshTile tile)
 
bool ContainsPoint (TriangleMeshNode node, Vector3 pos)
 Returns if the point is inside the node in XZ space.
 
override void DeserializeExtraInfo (GraphSerializationContext ctx)
 Deserializes graph type specific node data.
 
void EndBatchTileUpdate ()
 End batch updating of tiles.
 
override NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint)
 Returns the nearest node to a position using the specified NNConstraint.
 
override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint)
 Returns the nearest node to a position using the specified constraint.
 
override void GetNodes (GraphNodeDelegateCancelable del)
 Calls a delegate with all nodes in the graph.
 
void GetRecastMeshObjs (Bounds bounds, List< ExtraMesh > buffer)
 Find all relevant RecastMeshObj components and create ExtraMeshes for them.
 
Bounds GetTileBounds (IntRect rect)
 Returns an XZ bounds object with the bounds of a group of tiles.
 
Bounds GetTileBounds (int x, int z, int width=1, int depth=1)
 Returns an XZ bounds object with the bounds of a group of tiles.
 
void GetTileCoordinates (int tileIndex, out int x, out int z)
 Returns tile coordinates from a tile index.
 
Int2 GetTileCoordinates (Vector3 p)
 Returns the tile coordinate which contains the point p.
 
int GetTileIndex (int index)
 Returns a tile index from a vertex index.
 
NavmeshTile[] GetTiles ()
 Get all tiles.
 
IntRect GetTouchingTiles (Bounds b)
 Returns a rect containing the indices of all tiles touching the specified bounds.
 
IntRect GetTouchingTilesRound (Bounds b)
 Returns a rect containing the indices of all tiles by rounding the specified bounds to tile borders.
 
Int3 GetVertex (int index)
 Gets the vertex coordinate for the specified index.
 
int GetVertexArrayIndex (int index)
 
bool Linecast (Vector3 origin, Vector3 end)
 
bool Linecast (Vector3 origin, Vector3 end, GraphNode hint, out GraphHitInfo hit)
 
bool Linecast (Vector3 origin, Vector3 end, GraphNode hint)
 
bool Linecast (Vector3 tmp_origin, Vector3 tmp_end, GraphNode hint, out GraphHitInfo hit, List< GraphNode > trace)
 Returns if there is an obstacle between origin and end on the graph.
 
override void OnDestroy ()
 Function for cleaning up references.
 
override void OnDrawGizmos (bool drawNodes)
 Draw gizmos for the graph.
 
GraphNode PointOnNavmesh (Vector3 position, NNConstraint constraint)
 Finds the first node which contains position.
 
override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix)
 Relocates the nodes in this graph.
 
void RemoveConnectionsFromTile (NavmeshTile tile)
 
void RemoveConnectionsFromTo (NavmeshTile a, NavmeshTile b)
 
void ReplaceTile (int x, int z, Int3[] verts, int[] tris, bool worldSpace)
 Replace tile at index with nodes created from specified navmesh.
 
void ReplaceTile (int x, int z, int w, int d, Int3[] verts, int[] tris, bool worldSpace)
 
override void ScanInternal (OnScanStatus statusCallback)
 Scans the graph, called from AstarPath.ScanInternal Override this function to implement custom scanning logic The statusCallback may be optionally called to show progress info in the editor
 
override void SerializeExtraInfo (GraphSerializationContext ctx)
 Serializes Node Info.
 
void SnapForceBoundsToScene ()
 
void StartBatchTileUpdate ()
 Start batch updating of tiles.
 
void UpdateArea (GraphUpdateObject guo)
 
void UpdateAreaInit (GraphUpdateObject o)
 
- Public Member Functions inherited from NavGraph
virtual void Awake ()
 This will be called on the same time as Awake on the gameObject which the AstarPath script is attached to.
 
virtual int CountNodes ()
 Count nodes in the graph.
 
NNInfo GetNearest (Vector3 position)
 Returns the nearest node to a position using the default NNConstraint.
 
NNInfo GetNearest (Vector3 position, NNConstraint constraint)
 Returns the nearest node to a position using the specified NNConstraint.
 
virtual Color NodeColor (GraphNode node, PathHandler data)
 
virtual void PostDeserialization ()
 Called after all deserialization has been done for all graphs.
 
void Scan ()
 
void ScanGraph ()
 Consider using AstarPath.Scan () instead since this function might screw things up if there is more than one graph.
 
void ScanInternal ()
 Internal method for scanning graphs.
 
void SetMatrix (Matrix4x4 m)
 Use to set both matrix and inverseMatrix at the same time.
 
- Public Member Functions inherited from INavmesh
void GetNodes (GraphNodeDelegateCancelable del)
 
- Public Member Functions inherited from IRaycastableGraph
bool Linecast (Vector3 start, Vector3 end)
 
bool Linecast (Vector3 start, Vector3 end, GraphNode hint)
 
bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit)
 
bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit, List< GraphNode > trace)
 
- Public Member Functions inherited from IFunnelGraph
void AddPortal (GraphNode n1, GraphNode n2, List< Vector3 > left, List< Vector3 > right)
 Add the portal between node n1 and n2 to the funnel corridor.
 
void BuildFunnelCorridor (List< GraphNode > path, int sIndex, int eIndex, List< Vector3 > left, List< Vector3 > right)
 
- Public Member Functions inherited from IUpdatableGraph
GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o)
 
void UpdateArea (GraphUpdateObject o)
 Updates an area using the specified GraphUpdateObject.
 
void UpdateAreaInit (GraphUpdateObject o)
 
- Public Member Functions inherited from INavmeshHolder
void GetTileCoordinates (int tileIndex, out int x, out int z)
 
Int3 GetVertex (int i)
 
int GetVertexArrayIndex (int index)
 

Static Public Member Functions

static string GetRecastPath ()
 
- Static Public Member Functions inherited from NavGraph
static bool InSearchTree (GraphNode node, Path path)
 Returns if the node is in the search tree of the path.
 

Public Attributes

const int BorderVertexMask = 1
 
const int BorderVertexOffset = 31
 
float cellHeight = 0.01F
 Voxel sample size (y)
 
float cellSize = 0.5F
 Voxel sample size (x,z)
 
float characterRadius = 0.5F
 Radius of the agent which will traverse the navmesh.
 
float colliderRasterizeDetail = 10
 Controls detail on rasterization of sphere and capsule colliders.
 
float contourMaxError = 2F
 Max distance from simplified edge to real edge.
 
bool dynamic = true
 Enables graph updating.
 
int editorTileSize = 128
 Size in voxels of a single tile.
 
Vector3 forcedBoundsCenter
 Center of the bounding box.
 
Vector3 forcedBoundsSize = new Vector3 (100,40,100)
 Size of the bounding box.
 
LayerMask mask = -1
 Layer mask which filters which objects to include.
 
float maxEdgeLength = 20
 Longer edges will be subdivided.
 
float maxSlope = 30
 Max slope in degrees the character can traverse.
 
float minRegionSize = 3
 Minumum region size.
 
bool nearestSearchOnlyXZ = false
 Perform nearest node searches in XZ space only.
 
bool rasterizeColliders = false
 Use colliders to calculate the navmesh.
 
bool rasterizeMeshes = true
 Use scene meshes to calculate the navmesh.
 
bool rasterizeTerrain = true
 Include the Terrain in the scene.
 
bool rasterizeTrees = true
 Rasterize tree colliders on terrains.
 
RelevantGraphSurfaceMode relevantGraphSurfaceMode = RelevantGraphSurfaceMode.DoNotRequire
 Require every region to have a RelevantGraphSurface component inside it.
 
bool scanEmptyGraph = false
 If true, scanning the graph will yield a completely empty graph.
 
bool showMeshOutline = true
 Show an outline of the polygons in the Unity Editor.
 
bool showNodeConnections = false
 Show the connections between the polygons in the Unity Editor.
 
List< string > tagMask = new List<string>()
 Objects tagged with any of these tags will be rasterized.
 
int terrainSampleSize = 3
 Controls how large the sample size for the terrain is.
 
const int TileIndexMask = 0x7FFFF
 
const int TileIndexOffset = 12
 
int tileSizeX = 128
 Size of a tile along the X axis in voxels.
 
int tileSizeZ = 128
 Size of a tile along the Z axis in voxels.
 
int tileXCount
 Number of tiles along the X-axis.
 
int tileZCount
 Number of tiles along the Z-axis.
 
bool useTiles = false
 If true, divide the graph into tiles, otherwise use a single tile covering the whole graph.
 
const int VertexIndexMask = 0xFFF
 
float walkableClimb = 0.5F
 Height the character can climb.
 
float walkableHeight = 2F
 Character height.
 
- Public Attributes inherited from NavGraph
byte[] _sguid
 Used to store the guid value.
 
AstarPath active
 Reference to the AstarPath object in the scene.
 
bool drawGizmos = true
 
uint graphIndex
 Index of the graph, used for identification purposes.
 
bool infoScreenOpen
 Used in the editor to check if the info screen is open.
 
uint initialPenalty = 0
 Default penalty to apply to all nodes.
 
Matrix4x4 inverseMatrix = Matrix4x4.identity
 Inverse of matrix.
 
Matrix4x4 matrix = Matrix4x4.identity
 A matrix for translating/rotating/scaling the graph.
 
string name
 Name of the graph.
 
bool open
 Is the graph open in the editor.
 

Protected Member Functions

void BuildTileMesh (Voxelize vox, int x, int z)
 
void ScanAllTiles (OnScanStatus statusCallback)
 
void ScanCRecast ()
 
void ScanTiledNavmesh (OnScanStatus statusCallback)
 

Properties

BBTree bbTree [get, set]
 
Bounds forcedBounds [get]
 World bounds for the graph.
 
- Properties inherited from NavGraph
Guid guid [get, set]
 Used as an ID of the graph, considered to be unique.
 

Private Member Functions

void CollectColliderMeshes (Bounds bounds, List< ExtraMesh > extraMeshes)
 
bool CollectMeshes (out List< ExtraMesh > extraMeshes, Bounds bounds)
 
void CollectTerrainMeshes (Bounds bounds, bool rasterizeTrees, List< ExtraMesh > extraMeshes)
 
void CollectTreeMeshes (Terrain terrain, List< ExtraMesh > extraMeshes)
 
void ConnectTiles (NavmeshTile tile1, NavmeshTile tile2)
 Generate connections between the two tiles.
 
void CreateNodeConnections (TriangleMeshNode[] nodes)
 Create connections between all nodes.
 
NavmeshTile CreateTile (Voxelize vox, VoxelMesh mesh, int x, int z)
 Create a tile at tile index x , z from the mesh.
 
ExtraMesh RasterizeCollider (Collider col)
 Rasterizes a collider to a mesh.
 
ExtraMesh RasterizeCollider (Collider col, Matrix4x4 localToWorldMatrix)
 Rasterizes a collider to a mesh assuming it's vertices should be multiplied with the matrix.
 

Static Private Member Functions

static void GetSceneMeshes (Bounds bounds, List< string > tagMask, LayerMask layerMask, List< ExtraMesh > meshes)
 
static NavmeshTile NewEmptyTile (int x, int z)
 Creates a single new empty tile.
 

Private Attributes

BBTree _bbTree
 Bounding Box Tree.
 
bool batchTileUpdate = false
 Currently updating tiles in a batch.
 
List< int > batchUpdatedTiles = new List<int>()
 List of tiles updating during batch.
 
readonly int[] BoxColliderTris
 Box Collider triangle indices can be reused for multiple instances.
 
readonly Vector3[] BoxColliderVerts
 Box Collider vertices can be reused for multiple instances.
 
Dictionary< Int2, int > cachedInt2_int_dict = new Dictionary<Int2 , int> ()
 
Dictionary< Int3, int > cachedInt3_int_dict = new Dictionary<Int3 , int> ()
 
List< CapsuleCachecapsuleCache = new List<CapsuleCache>()
 
Voxelize globalVox
 
NavmeshTile[] tiles
 All tiles.
 

Member Enumeration Documentation

Enumerator:
DoNotRequire 
OnlyForCompletelyInsideTile 
RequireForAll 

Member Function Documentation

void AddPortal ( GraphNode  n1,
GraphNode  n2,
List< Vector3 >  left,
List< Vector3 >  right 
)
void BuildFunnelCorridor ( List< GraphNode path,
int  startIndex,
int  endIndex,
List< Vector3 >  left,
List< Vector3 >  right 
)
void BuildTileMesh ( Voxelize  vox,
int  x,
int  z 
)
protected
GraphUpdateThreading CanUpdateAsync ( GraphUpdateObject  o)
Vector3 ClosestPointOnNode ( TriangleMeshNode  node,
Vector3  pos 
)

Returns the closest point of the node.

void CollectColliderMeshes ( Bounds  bounds,
List< ExtraMesh extraMeshes 
)
private
bool CollectMeshes ( out List< ExtraMesh extraMeshes,
Bounds  bounds 
)
private
void CollectTerrainMeshes ( Bounds  bounds,
bool  rasterizeTrees,
List< ExtraMesh extraMeshes 
)
private
void CollectTreeMeshes ( Terrain  terrain,
List< ExtraMesh extraMeshes 
)
private
void ConnectTiles ( NavmeshTile  tile1,
NavmeshTile  tile2 
)
private

Generate connections between the two tiles.

The tiles must be adjacent.

void ConnectTileWithNeighbours ( NavmeshTile  tile)
bool ContainsPoint ( TriangleMeshNode  node,
Vector3  pos 
)

Returns if the point is inside the node in XZ space.

void CreateNodeConnections ( TriangleMeshNode[]  nodes)
private

Create connections between all nodes.

Warning
This implementation is not thread safe. It uses cached variables to improve performance
NavmeshTile CreateTile ( Voxelize  vox,
VoxelMesh  mesh,
int  x,
int  z 
)
private

Create a tile at tile index x , z from the mesh.

Warning
This implementation is not thread safe. It uses cached variables to improve performance
override void DeserializeExtraInfo ( GraphSerializationContext  ctx)
virtual

Deserializes graph type specific node data.

See Also
SerializeExtraInfo

Reimplemented from NavGraph.

void EndBatchTileUpdate ( )

End batch updating of tiles.

During batch updating, tiles will not be connected if they are updating with ReplaceTile. When ending batching, all affected tiles will be connected. This is faster than not using batching.

override NNInfo GetNearest ( Vector3  position,
NNConstraint  constraint,
GraphNode  hint 
)
virtual

Returns the nearest node to a position using the specified NNConstraint.

Parameters
positionThe position to try to find a close node to
hintCan be passed to enable some graph generators to find the nearest node faster.
constraintCan for example tell the function to try to return a walkable node. If you do not get a good node back, consider calling GetNearestForce.

Reimplemented from NavGraph.

override NNInfo GetNearestForce ( Vector3  position,
NNConstraint  constraint 
)
virtual

Returns the nearest node to a position using the specified constraint.

Parameters
positionA Vector3
constraintA NNConstraint
Returns
A NNInfo. This function will only return an empty NNInfo if there are no nodes which comply with the specified constraint.

Reimplemented from NavGraph.

override void GetNodes ( GraphNodeDelegateCancelable  del)
virtual

Calls a delegate with all nodes in the graph.

This is the primary way of "looping" through all nodes in a graph.

This function should not change anything in the graph structure.

myGraph.GetNodes ((node) => {
Debug.Log ("I found a node at position " + (Vector3)node.Position);
return true;
});

Implements NavGraph.

void GetRecastMeshObjs ( Bounds  bounds,
List< ExtraMesh buffer 
)

Find all relevant RecastMeshObj components and create ExtraMeshes for them.

static string GetRecastPath ( )
static
static void GetSceneMeshes ( Bounds  bounds,
List< string >  tagMask,
LayerMask  layerMask,
List< ExtraMesh meshes 
)
staticprivate
Bounds GetTileBounds ( IntRect  rect)

Returns an XZ bounds object with the bounds of a group of tiles.

The bounds object is defined in world units.

Bounds GetTileBounds ( int  x,
int  z,
int  width = 1,
int  depth = 1 
)

Returns an XZ bounds object with the bounds of a group of tiles.

The bounds object is defined in world units.

void GetTileCoordinates ( int  tileIndex,
out int  x,
out int  z 
)

Returns tile coordinates from a tile index.

Int2 GetTileCoordinates ( Vector3  p)

Returns the tile coordinate which contains the point p.

Is not necessarily a valid tile (i.e, it could be out of bounds).

int GetTileIndex ( int  index)

Returns a tile index from a vertex index.

NavmeshTile [] GetTiles ( )

Get all tiles.

Warning
Do not modify this array
IntRect GetTouchingTiles ( Bounds  b)

Returns a rect containing the indices of all tiles touching the specified bounds.

IntRect GetTouchingTilesRound ( Bounds  b)

Returns a rect containing the indices of all tiles by rounding the specified bounds to tile borders.

Int3 GetVertex ( int  index)

Gets the vertex coordinate for the specified index.

Exceptions
IndexOutOfRangeExceptionif the vertex index is invalid.
NullReferenceExceptionif the tile the vertex is in is not calculated.
See Also
NavmeshTile.GetVertex
int GetVertexArrayIndex ( int  index)
bool Linecast ( Vector3  origin,
Vector3  end 
)
bool Linecast ( Vector3  origin,
Vector3  end,
GraphNode  hint,
out GraphHitInfo  hit 
)
bool Linecast ( Vector3  origin,
Vector3  end,
GraphNode  hint 
)
bool Linecast ( Vector3  tmp_origin,
Vector3  tmp_end,
GraphNode  hint,
out GraphHitInfo  hit,
List< GraphNode trace 
)

Returns if there is an obstacle between origin and end on the graph.

Parameters
[in]graphThe graph to perform the search on
[in]tmp_originPoint to start from
[in]tmp_endPoint to linecast to
[out]hitContains info on what was hit, see GraphHitInfo
[in]hintYou need to pass the node closest to the start point, if null, a search for the closest node will be done
traceIf a list is passed, then it will be filled with all nodes the linecast traverses This is not the same as Physics.Linecast, this function traverses the graph and looks for collisions instead of checking for collider intersection.
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
static NavmeshTile NewEmptyTile ( int  x,
int  z 
)
staticprivate

Creates a single new empty tile.

override void OnDestroy ( )
virtual

Function for cleaning up references.

This will be called on the same time as OnDisable on the gameObject which the AstarPath script is attached to (remember, not in the editor). Use for any cleanup code such as cleaning up static variables which otherwise might prevent resources from being collected. Use by creating a function overriding this one in a graph class, but always call base.OnDestroy () in that function. All nodes should be destroyed in this function otherwise a memory leak will arise.

Reimplemented from NavGraph.

override void OnDrawGizmos ( bool  drawNodes)
virtual

Draw gizmos for the graph.

Reimplemented from NavGraph.

GraphNode PointOnNavmesh ( Vector3  position,
NNConstraint  constraint 
)

Finds the first node which contains position.

"Contains" is defined as position is inside the triangle node when seen from above. So only XZ space matters. In case of a multilayered environment, which node of the possibly several nodes containing the point is undefined.

Returns null if there was no node containing the point. This serves as a quick check for "is this point on the navmesh or not".

Note that the behaviour of this method is distinct from the GetNearest method. The GetNearest method will return the closest node to a point, which is not necessarily the one which contains it in XZ space.

See Also
GetNearest
ExtraMesh RasterizeCollider ( Collider  col)
private

Rasterizes a collider to a mesh.

This will pass the col.transform.localToWorldMatrix to the other overload of this function.

ExtraMesh RasterizeCollider ( Collider  col,
Matrix4x4  localToWorldMatrix 
)
private

Rasterizes a collider to a mesh assuming it's vertices should be multiplied with the matrix.

Note that the bounds of the returned ExtraMesh is based on collider.bounds. So you might want to call myExtraMesh.RecalculateBounds on the returned mesh to recalculate it if the collider.bounds would not give the correct value.

override void RelocateNodes ( Matrix4x4  oldMatrix,
Matrix4x4  newMatrix 
)
virtual

Relocates the nodes in this graph.

Assumes the nodes are already transformed using the "oldMatrix", then transforms them such that it will look like they have only been transformed using the "newMatrix".

The matrix the graph is transformed with is typically stored in the matrix field, so the typical usage for this method is

var myNewMatrix = Matrix4x4.TRS (...);
myGraph.RelocateNodes (myGraph.matrix, myNewMatrix);

So for example if you want to move all your nodes in e.g a recast graph 10 units along the X axis from the initial position

var graph = AstarPath.astarData.recastGraph;
var m = Matrix4x4.TRS (new Vector3(10,0,0), Quaternion.identity, Vector3.one);
graph.RelocateNodes (graph.matrix, m);
Warning
Cannot be used on tiled recast graphs.
This method is lossy, so calling it many times may cause node positions to loose precision. For example if you set the scale to 0 in one call, and then to 1 in the next call, it will not be able to recover the correct positions since when the scale was 0, all nodes were scaled/moved to the same point. The same thing happens for other - less extreme - values as well, but to a lesser degree.
Version
Prior to version 3.6.1 the oldMatrix and newMatrix parameters were reversed by mistake.

Reimplemented from NavGraph.

void RemoveConnectionsFromTile ( NavmeshTile  tile)
void RemoveConnectionsFromTo ( NavmeshTile  a,
NavmeshTile  b 
)
void ReplaceTile ( int  x,
int  z,
Int3[]  verts,
int[]  tris,
bool  worldSpace 
)

Replace tile at index with nodes created from specified navmesh.

See Also
StartBatchTileUpdating
void ReplaceTile ( int  x,
int  z,
int  w,
int  d,
Int3[]  verts,
int[]  tris,
bool  worldSpace 
)
void ScanAllTiles ( OnScanStatus  statusCallback)
protected
void ScanCRecast ( )
protected
override void ScanInternal ( OnScanStatus  statusCallback)
virtual

Scans the graph, called from AstarPath.ScanInternal Override this function to implement custom scanning logic The statusCallback may be optionally called to show progress info in the editor

Implements NavGraph.

void ScanTiledNavmesh ( OnScanStatus  statusCallback)
protected
override void SerializeExtraInfo ( GraphSerializationContext  ctx)
virtual

Serializes Node Info.

Should serialize:

  • Base
  • Node Positions (if applicable)
  • Any other information necessary to load the graph in-game All settings marked with json attributes (e.g JsonMember) have already been saved as graph settings and do not need to be handled here.

It is not necessary for this implementation to be forward or backwards compatible.

See Also

Reimplemented from NavGraph.

void SnapForceBoundsToScene ( )
void StartBatchTileUpdate ( )

Start batch updating of tiles.

During batch updating, tiles will not be connected if they are updating with ReplaceTile. When ending batching, all affected tiles will be connected. This is faster than not using batching.

void UpdateArea ( GraphUpdateObject  guo)
void UpdateAreaInit ( GraphUpdateObject  o)

Member Data Documentation

BBTree _bbTree
private

Bounding Box Tree.

Enables really fast lookups of nodes.

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
bool batchTileUpdate = false
private

Currently updating tiles in a batch.

List<int> batchUpdatedTiles = new List<int>()
private

List of tiles updating during batch.

const int BorderVertexMask = 1
const int BorderVertexOffset = 31
readonly int [] BoxColliderTris
private
Initial value:
= {
0, 1, 2,
0, 2, 3,
6, 5, 4,
7, 6, 4,
0, 5, 1,
0, 4, 5,
1, 6, 2,
1, 5, 6,
2, 7, 3,
2, 6, 7,
3, 4, 0,
3, 7, 4
}

Box Collider triangle indices can be reused for multiple instances.

Warning
This array should never be changed
readonly Vector3 [] BoxColliderVerts
private
Initial value:
= {
new Vector3(-1,-1,-1),
new Vector3( 1,-1,-1),
new Vector3( 1,-1, 1),
new Vector3(-1,-1, 1),
new Vector3(-1, 1,-1),
new Vector3( 1, 1,-1),
new Vector3( 1, 1, 1),
new Vector3(-1, 1, 1),
}

Box Collider vertices can be reused for multiple instances.

Warning
This array should never be changed
Dictionary<Int2, int> cachedInt2_int_dict = new Dictionary<Int2 , int> ()
private
Dictionary<Int3, int> cachedInt3_int_dict = new Dictionary<Int3 , int> ()
private
List<CapsuleCache> capsuleCache = new List<CapsuleCache>()
private
float cellHeight = 0.01F

Voxel sample size (y)

float cellSize = 0.5F

Voxel sample size (x,z)

float characterRadius = 0.5F

Radius of the agent which will traverse the navmesh.

The navmesh will be eroded with this radius.

float colliderRasterizeDetail = 10

Controls detail on rasterization of sphere and capsule colliders.

This controls the number of rows and columns on the generated meshes. A higher value does not necessarily increase quality of the mesh, but a lower value will often speed it up.

You should try to keep this value as low as possible without affecting the mesh quality since that will yield the fastest scan times.

See Also
rasterizeColliders
float contourMaxError = 2F

Max distance from simplified edge to real edge.

bool dynamic = true

Enables graph updating.

Uses more memory if enabled.

int editorTileSize = 128

Size in voxels of a single tile.

This is the width of the tile.

A large tile size can be faster to initially scan (but beware of out of memory issues if you try with a too large tile size in a large world) smaller tile sizes are (much) faster to update.

Different tile sizes can affect the quality of paths. It is often good to split up huge open areas into several tiles for better quality paths, but too small tiles can lead to effects looking like invisible obstacles.

Vector3 forcedBoundsCenter

Center of the bounding box.

Scanning will only be done inside the bounding box

Vector3 forcedBoundsSize = new Vector3 (100,40,100)

Size of the bounding box.

Voxelize globalVox
private
LayerMask mask = -1

Layer mask which filters which objects to include.

See Also
tagMask
float maxEdgeLength = 20

Longer edges will be subdivided.

Reducing this value can improve path quality since similarly sized polygons yield better paths than really large and really small next to each other

float maxSlope = 30

Max slope in degrees the character can traverse.

float minRegionSize = 3

Minumum region size.

Small regions will be removed from the navmesh. Measured in square world units (square meters in most games).

If a region is adjacent to a tile border, it will not be removed even though it is small since the adjacent tile might join it to form a larger region.

bool nearestSearchOnlyXZ = false

Perform nearest node searches in XZ space only.

bool rasterizeColliders = false

Use colliders to calculate the navmesh.

bool rasterizeMeshes = true

Use scene meshes to calculate the navmesh.

bool rasterizeTerrain = true

Include the Terrain in the scene.

bool rasterizeTrees = true

Rasterize tree colliders on terrains.

If the tree prefab has a collider, that collider will be rasterized. Otherwise a simple box collider will be used and the script will try to adjust it to the tree's scale, it might not do a very good job though so an attached collider is preferable.

See Also
rasterizeTerrain
colliderRasterizeDetail
RelevantGraphSurfaceMode relevantGraphSurfaceMode = RelevantGraphSurfaceMode.DoNotRequire

Require every region to have a RelevantGraphSurface component inside it.

A RelevantGraphSurface component placed in the scene specifies that the navmesh region it is inside should be included in the navmesh.

If this is set to OnlyForCompletelyInsideTile a navmesh region is included in the navmesh if it has a RelevantGraphSurface inside it, or if it is adjacent to a tile border. This can leave some small regions which you didn't want to have included because they are adjacent to tile borders, but it removes the need to place a component in every single tile, which can be tedious (see below).

If this is set to RequireForAll a navmesh region is included only if it has a RelevantGraphSurface inside it. Note that even though the navmesh looks continous between tiles, the tiles are computed individually and therefore you need a RelevantGraphSurface component for each region and for each tile.

In the above image, the mode OnlyForCompletelyInsideTile was used. Tile borders are highlighted in black. Note that since all regions are adjacent to a tile border, this mode didn't remove anything in this case and would give the same result as DoNotRequire. The RelevantGraphSurface component is shown using the green gizmo in the top-right of the blue plane.

In the above image, the mode RequireForAll was used. No tiles were used. Note that the small region at the top of the orange cube is now gone, since it was not the in the same region as the relevant graph surface component. The result would have been identical with OnlyForCompletelyInsideTile since there are no tiles (or a single tile, depending on how you look at it).

The mode RequireForAll was used here. Since there is only a single RelevantGraphSurface component, only the region it was in, in the tile it is placed in, will be enabled. If there would have been several RelevantGraphSurface in other tiles, those regions could have been enabled as well.

Here another tile size was used along with the OnlyForCompletelyInsideTile. Note that the region on top of the orange cube is gone now since the region borders do not intersect that region (and there is no RelevantGraphSurface component inside it).

Note
When not using tiles. OnlyForCompletelyInsideTile is equivalent to RequireForAll.
bool scanEmptyGraph = false

If true, scanning the graph will yield a completely empty graph.

Useful if you want to replace the graph with a custom navmesh for example

bool showMeshOutline = true

Show an outline of the polygons in the Unity Editor.

bool showNodeConnections = false

Show the connections between the polygons in the Unity Editor.

List<string> tagMask = new List<string>()

Objects tagged with any of these tags will be rasterized.

Note that this extends the layer mask, so if you only want to use tags, set mask to 'Nothing'.

See Also
mask
int terrainSampleSize = 3

Controls how large the sample size for the terrain is.

A higher value is faster to scan but less accurate

const int TileIndexMask = 0x7FFFF
const int TileIndexOffset = 12
NavmeshTile [] tiles
private

All tiles.

A tile can be got from a tile coordinate as tiles[x + z*tileXCount]

int tileSizeX = 128

Size of a tile along the X axis in voxels.

Warning
Do not modify, it is set from editorTileSize at Scan
int tileSizeZ = 128

Size of a tile along the Z axis in voxels.

Warning
Do not modify, it is set from editorTileSize at Scan
int tileXCount

Number of tiles along the X-axis.

int tileZCount

Number of tiles along the Z-axis.

bool useTiles = false

If true, divide the graph into tiles, otherwise use a single tile covering the whole graph.

const int VertexIndexMask = 0xFFF
float walkableClimb = 0.5F

Height the character can climb.

float walkableHeight = 2F

Character height.

Property Documentation

BBTree bbTree
getset
Bounds forcedBounds
get

World bounds for the graph.

Defined as a bounds object with size #forceBoundsSize and centered at forcedBoundsCenter


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