A* Pathfinding Project  4.1.7
The A* Pathfinding Project for Unity 3D
GridGraph Class Reference

Generates a grid of nodes. More...

Detailed Description

Generates a grid of nodes.

The GridGraph does exactly what the name implies, generates nodes in a grid pattern.
Grid graphs suit well to when you already have a grid based world. Features:

  • You can update the graph during runtime (good for e.g Tower Defence or RTS games)
  • Throw any scene at it, with minimal configurations you can get a good graph from it.
  • Supports raycast and the funnel algorithm
  • Predictable pattern
  • Can apply penalty and walkability values from a supplied image
  • Perfect for terrain worlds since it can make areas unwalkable depending on the slope

The The Snap Size button snaps the internal size of the graph to exactly contain the current number of nodes, i.e not contain 100.3 nodes but exactly 100 nodes.
This will make the "center" coordinate more accurate.
Updating the graph during runtime Any graph which implements the IUpdatableGraph interface can be updated during runtime.
For grid graphs this is a great feature since you can update only a small part of the grid without causing any lag like a complete rescan would.
If you for example just have instantiated a sphere obstacle in the scene and you want to update the grid where that sphere was instantiated, you can do this:

AstarPath.active.UpdateGraphs (ob.collider.bounds);

Where ob is the obstacle you just instantiated (a GameObject).
As you can see, the UpdateGraphs function takes a Bounds parameter and it will send an update call to all updateable graphs.
A grid graph will update that area and a small margin around it equal to collision testing diameter/2

See also
Graph Updates during Runtime for more info about updating Graph Types during runtime

Hexagon graphs The graph can be configured to work like a hexagon graph with some simple settings. Just set the neighbours (called 'connections' in the editor) field to 'Six' and then click the 'Configure as Hexagon Graph' button that will show up. That will set the isometricAngle field to 54.74 (more precisely 90-atan(1/sqrt(2))) and enable uniformEdgeCosts.

Then the graph will work like a hexagon graph. You might want to rotate it to better match your game however.

Note however that the snapping to the closest node is not exactly as you would expect in a real hexagon graph, but it is close enough that you will likely not notice.

Configure using code

// This holds all graph data
AstarData data = AstarPath.active.data;
// This creates a Grid Graph
GridGraph gg = data.AddGraph(typeof(GridGraph)) as GridGraph;
// Setup a grid graph with some values
int width = 50;
int depth = 50;
float nodeSize = 1;
gg.center = new Vector3 (10,0,0);
// Updates internal size from the above values
gg.SetDimensions(width, depth, nodeSize);
// Scans all graphs, do not call gg.Scan(), that is an internal method

Tree colliders It seems that Unity will only generate tree colliders at runtime when the game is started. For this reason, the grid graph will not pick up tree colliders when outside of play mode but it will pick them up once the game starts. If it still does not pick them up make sure that the trees actually have colliders attached to them and that the tree prefabs are in the correct layer (the layer should be included in the 'Collision Testing' mask).

See also
Pathfinding.GraphCollision for documentation on the 'Height Testing' and 'Collision Testing' sections of the grid graph settings.

Classes

class  TextureData
 Used for using a texture as a source for a grid graph. More...
 

Public Member Functions

 GridGraph ()
 
virtual void CalculateConnections (GridNodeBase node)
 Calculates the grid connections for a single node. More...
 
virtual void CalculateConnections (GridNode[] nodes, int x, int z, GridNode node)
 Calculates the grid connections for a single node. More...
 
virtual void CalculateConnections (int x, int z, GridNode node)
 Calculates the grid connections for a single node. More...
 
virtual void CalculateConnections (int x, int z)
 Calculates the grid connections for a single node. More...
 
GraphTransform CalculateTransform ()
 Returns a new transform which transforms graph space to world space. More...
 
bool CheckConnection (GridNode node, int dir)
 Returns if node is connected to it's neighbour in the specified direction. More...
 
override int CountNodes ()
 Number of nodes in the graph. More...
 
virtual void ErodeWalkableArea ()
 Erodes the walkable area. More...
 
void ErodeWalkableArea (int xmin, int zmin, int xmax, int zmax)
 Erodes the walkable area. More...
 
void GenerateMatrix ()
 Generates the matrix used for translating nodes from grid coordinates to world coordinates. More...
 
uint GetConnectionCost (int dir)
 
override NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint)
 Returns the nearest node to a position using the specified NNConstraint. More...
 
override NNInfoInternal GetNearestForce (Vector3 position, NNConstraint constraint)
 Returns the nearest node to a position using the specified constraint . More...
 
GridNode GetNodeConnection (GridNode node, int dir)
 
override void GetNodes (System.Action< GraphNode > action)
 Calls a delegate with all nodes in the graph. More...
 
List< GraphNodeGetNodesInArea (Bounds bounds)
 
List< GraphNodeGetNodesInArea (GraphUpdateShape shape)
 
List< GraphNodeGetNodesInArea (Bounds bounds, GraphUpdateShape shape)
 
List< GraphNodeGetNodesInRegion (Bounds bounds)
 All nodes inside the bounding box. More...
 
List< GraphNodeGetNodesInRegion (GraphUpdateShape shape)
 All nodes inside the shape. More...
 
virtual List< GraphNodeGetNodesInRegion (IntRect rect)
 Get all nodes in a rectangle. More...
 
virtual int GetNodesInRegion (IntRect rect, GridNodeBase[] buffer)
 Get all nodes in a rectangle. More...
 
Int3 GraphPointToWorld (int x, int z, float height)
 Transform a point in graph space to world space. More...
 
bool HasNodeConnection (GridNode node, int dir)
 
bool HasNodeConnection (int index, int x, int z, int dir)
 
virtual bool IsValidConnection (GridNodeBase node1, GridNodeBase node2)
 Returns true if a connection between the adjacent nodes n1 and n2 is valid. More...
 
bool Linecast (Vector3 from, Vector3 to)
 Returns if there is an obstacle between from and to on the graph. More...
 
bool Linecast (Vector3 from, Vector3 to, GraphNode hint)
 Returns if there is an obstacle between from and to on the graph. More...
 
bool Linecast (Vector3 from, Vector3 to, GraphNode hint, out GraphHitInfo hit)
 Returns if there is an obstacle between from and to on the graph. More...
 
bool Linecast (Vector3 from, Vector3 to, GraphNode hint, out GraphHitInfo hit, List< GraphNode > trace)
 Returns if there is an obstacle between from and to on the graph. More...
 
override void OnDrawGizmos (RetainedGizmos gizmos, bool drawNodes)
 Draw gizmos for the graph. More...
 
virtual void RecalculateCell (int x, int z, bool resetPenalties=true, bool resetTags=true)
 Recalculates single node in the graph. More...
 
override void RelocateNodes (Matrix4x4 deltaMatrix)
 Moves the nodes in this graph. More...
 
void RelocateNodes (Vector3 center, Quaternion rotation, float nodeSize, float aspectRatio=1, float isometricAngle=0)
 Relocate the grid graph using new settings. More...
 
void SetDimensions (int width, int depth, float nodeSize)
 Updates unclampedSize from width, depth and nodeSize values. More...
 
void SetNodeConnection (GridNode node, int dir, bool value)
 
void SetNodeConnection (int index, int x, int z, int dir, bool value)
 Set if connection in the specified direction should be enabled. More...
 
virtual void SetUpOffsetsAndCosts ()
 Sets up neighbourOffsets with the current settings. More...
 
bool SnappedLinecast (Vector3 from, Vector3 to, GraphNode hint, out GraphHitInfo hit)
 Returns if there is an obstacle between from and to on the graph. More...
 
virtual void UpdateNodePositionCollision (GridNode node, int x, int z, bool resetPenalty=true)
 Updates position, walkability and penalty for the node. More...
 
void UpdateSizeFromWidthDepth ()
 Updates unclampedSize from width, depth and nodeSize values. More...
 
void UpdateTransform ()
 Updates the transform field which transforms graph space to world space. More...
 
- Public Member Functions inherited from NavGraph
NNInfoInternal GetNearest (Vector3 position)
 Returns the nearest node to a position using the default NNConstraint. More...
 
NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint)
 Returns the nearest node to a position using the specified NNConstraint. More...
 
void GetNodes (System.Func< GraphNode, bool > action)
 Calls a delegate with all nodes in the graph until the delegate returns false. More...
 
void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix)
 Moves nodes in this graph. More...
 
void Scan ()
 Scan the graph. More...
 
void ScanGraph ()
 Scan the graph. More...
 
void SetMatrix (Matrix4x4 m)
 Use to set both matrix and inverseMatrix at the same time. More...
 

Static Public Member Functions

static void CalculateConnections (GridNode node)
 Calculates the grid connections for a single node. More...
 

Public Attributes

const int getNearestForceOverlap = 2
 In GetNearestForce, determines how far to search after a valid node has been found. More...
 
readonly uint [] neighbourCosts = new uint[8]
 Costs to neighbour nodes. More...
 
readonly int [] neighbourOffsets = new int[8]
 Index offset to get neighbour nodes. More...
 
readonly int [] neighbourXOffsets = new int[8]
 Offsets in the X direction for neighbour nodes. More...
 
readonly int [] neighbourZOffsets = new int[8]
 Offsets in the Z direction for neighbour nodes. More...
 
GridNode [] nodes
 All nodes in this graph. More...
 
- Public Attributes inherited from NavGraph
AstarPath active
 Reference to the AstarPath object in the scene. More...
 
bool drawGizmos = true
 Enable to draw gizmos in the Unity scene view. More...
 
uint graphIndex
 Index of the graph, used for identification purposes. More...
 
Guid guid
 Used as an ID of the graph, considered to be unique. More...
 
bool infoScreenOpen
 Used in the editor to check if the info screen is open. More...
 
uint initialPenalty
 Default penalty to apply to all nodes. More...
 
Matrix4x4 inverseMatrix = Matrix4x4.identity
 Inverse of matrix. More...
 
Matrix4x4 matrix = Matrix4x4.identity
 A matrix for translating/rotating/scaling the graph. More...
 
string name
 Name of the graph. More...
 
bool open
 Is the graph open in the editor. More...
 

Protected Member Functions

void CalculateAffectedRegions (GraphUpdateObject o, out IntRect originalRect, out IntRect affectRect, out IntRect physicsRect, out bool willChangeWalkability, out int erosion)
 
bool ClipLineSegmentToBounds (Vector3 a, Vector3 b, out Vector3 outA, out Vector3 outB)
 Clips a line segment in graph space to the graph bounds. More...
 
override void DeserializeExtraInfo (GraphSerializationContext ctx)
 Deserializes graph type specific node data. More...
 
override void DeserializeSettingsCompatibility (GraphSerializationContext ctx)
 An old format for serializing settings. More...
 
override void DestroyAllNodes ()
 Destroys all nodes in the graph. More...
 
virtual bool ErosionAnyFalseConnections (GraphNode baseNode)
 True if the node has any blocked connections. More...
 
virtual List< GraphNodeGetNodesInRegion (Bounds bounds, GraphUpdateShape shape)
 All nodes inside the shape or if null, the bounding box. More...
 
IntRect GetRectFromBounds (Bounds bounds)
 A rect with all nodes that the bounds could touch. More...
 
override void OnDestroy ()
 This function will be called when this graph is destroyed. More...
 
override void PostDeserialization (GraphSerializationContext ctx)
 Called after all deserialization has been done for all graphs. More...
 
override IEnumerable< ProgressScanInternal ()
 Internal method to scan the graph. More...
 
override void SerializeExtraInfo (GraphSerializationContext ctx)
 Serializes graph type specific node data. More...
 
- Protected Member Functions inherited from NavGraph
void DrawUnwalkableNodes (float size)
 

Static Protected Member Functions

static float CrossMagnitude (Vector2 a, Vector2 b)
 Magnitude of the cross product a x b. More...
 

Static Package Attributes

static readonly int [] hexagonNeighbourIndices = { 0, 1, 5, 2, 3, 7 }
 Which neighbours are going to be used when neighbours=6. More...
 

Properties

int Depth [get, set]
 
virtual int LayerCount [get]
 Number of layers in the graph. More...
 
Vector2 size [get, protected set]
 Size of the grid. More...
 
GraphTransform transform [get, private set]
 Determines how the graph transforms graph space to world space. More...
 
virtual bool uniformWidthDepthGrid [get]
 This is placed here so generators inheriting from this one can override it and set it to false. More...
 
int Width [get, set]
 
- Properties inherited from NavGraph
bool exists [get]
 True if the graph exists, false if it has been destroyed. More...
 
- Properties inherited from ITransformedGraph
GraphTransform transform [get]
 

Private Member Functions

void CalculateDimensions (out int width, out int depth, out float nodeSize)
 Calculates the width/depth of the graph from unclampedSize and nodeSize. More...
 
GraphUpdateThreading IUpdatableGraph. CanUpdateAsync (GraphUpdateObject o)
 
void CreateNavmeshSurfaceVisualization (GridNodeBase[] nodes, int nodeCount, GraphGizmoHelper helper)
 Draw the surface as well as an outline of the grid graph. More...
 
void ErodeNode (GraphNode node)
 Internal method used for erosion. More...
 
void ErodeNodeWithTags (GraphNode node, int iteration)
 Internal method used for erosion. More...
 
void ErodeNodeWithTagsInit (GraphNode node)
 Internal method used for erosion. More...
 
GridNode GetNodeConnection (int index, int x, int z, int dir)
 Get the connecting node from the node at (x,z) in the specified direction. More...
 
void RemoveGridGraphFromStatic ()
 
void IUpdatableGraph. UpdateArea (GraphUpdateObject o)
 Internal function to update an area of the graph. More...
 
void IUpdatableGraph. UpdateAreaInit (GraphUpdateObject o)
 May be called on the Unity thread before starting the update. More...
 
void IUpdatableGraph. UpdateAreaPost (GraphUpdateObject o)
 May be called on the Unity thread after executing the update. More...
 

Inspector - Settings

bool useRaycastNormal [get]
 Use heigh raycasting normal for max slope calculation. More...
 
int width
 Width of the grid in nodes. More...
 
int depth
 Depth (height) of the grid in nodes. More...
 
float aspectRatio = 1F
 Scaling of the graph along the X axis. More...
 
float isometricAngle
 Angle to use for the isometric projection. More...
 
bool uniformEdgeCosts
 If true, all edge costs will be set to the same value. More...
 
Vector3 rotation
 Rotation of the grid in degrees. More...
 
Vector3 center
 Center point of the grid. More...
 
Vector2 unclampedSize
 Size of the grid. More...
 
float nodeSize = 1
 Size of one node in world units. More...
 
GraphCollision collision
 Settings on how to check for walkability and height. More...
 
float maxClimb = 0.4F
 The max position difference between two nodes to enable a connection. More...
 
float maxSlope = 90
 The max slope in degrees for a node to be walkable. More...
 
int erodeIterations
 Erosion of the graph. More...
 
bool erosionUseTags
 Use tags instead of walkability for erosion. More...
 
int erosionFirstTag = 1
 Tag to start from when using tags for erosion. More...
 
NumNeighbours neighbours = NumNeighbours.Eight
 Number of neighbours for each node. More...
 
bool cutCorners = true
 If disabled, will not cut corners on obstacles. More...
 
float penaltyPositionOffset
 Offset for the position when calculating penalty. More...
 
bool penaltyPosition
 Use position (y-coordinate) to calculate penalty. More...
 
float penaltyPositionFactor = 1F
 Scale factor for penalty when calculating from position. More...
 
bool penaltyAngle
 
float penaltyAngleFactor = 100F
 How much penalty is applied depending on the slope of the terrain. More...
 
float penaltyAnglePower = 1
 How much extra to penalize very steep angles. More...
 
bool useJumpPointSearch
 
bool showMeshOutline = true
 Show an outline of the grid nodes in the Unity Editor. More...
 
bool showNodeConnections
 Show the connections between the grid nodes in the Unity Editor. More...
 
bool showMeshSurface = true
 Show the surface of the graph. More...
 
TextureData textureData = new TextureData()
 Holds settings for using a texture as source for a grid graph. More...
 

Constructor & Destructor Documentation

◆ GridGraph()

GridGraph ( )

Member Function Documentation

◆ CalculateAffectedRegions()

void CalculateAffectedRegions ( GraphUpdateObject  o,
out IntRect  originalRect,
out IntRect  affectRect,
out IntRect  physicsRect,
out bool  willChangeWalkability,
out int  erosion 
)
protected

◆ CalculateConnections() [1/5]

static void CalculateConnections ( GridNode  node)
static

Calculates the grid connections for a single node.

Deprecated:
Use the instance function instead

◆ CalculateConnections() [2/5]

virtual void CalculateConnections ( GridNodeBase  node)
virtual

Calculates the grid connections for a single node.

Convenience function, it's slightly faster to use CalculateConnections(int,int) but that will only show when calculating for a large number of nodes. This function will also work for both grid graphs and layered grid graphs.

Reimplemented in LayerGridGraph.

◆ CalculateConnections() [3/5]

virtual void CalculateConnections ( GridNode []  nodes,
int  x,
int  z,
GridNode  node 
)
virtual

Calculates the grid connections for a single node.

Deprecated:
CalculateConnections no longer takes a node array, it just uses the one on the graph

◆ CalculateConnections() [4/5]

virtual void CalculateConnections ( int  x,
int  z,
GridNode  node 
)
virtual

Calculates the grid connections for a single node.

Deprecated:
Use CalculateConnections(x,z) or CalculateConnections(node) instead

◆ CalculateConnections() [5/5]

virtual void CalculateConnections ( int  x,
int  z 
)
virtual

Calculates the grid connections for a single node.

Note that to ensure that connections are completely up to date after updating a node you have to calculate the connections for both the changed node and its neighbours.

In a layered grid graph, this will recalculate the connections for all nodes in the (x,z) cell (it may have multiple layers of nodes).

See also
CalculateConnections(GridNodeBase)

Reimplemented in LayerGridGraph.

◆ CalculateDimensions()

void CalculateDimensions ( out int  width,
out int  depth,
out float  nodeSize 
)
private

Calculates the width/depth of the graph from unclampedSize and nodeSize.

The node size may be changed due to constraints that the width/depth is not allowed to be larger than 1024 (artificial limit).

◆ CalculateTransform()

GraphTransform CalculateTransform ( )

Returns a new transform which transforms graph space to world space.

Does not update the transform field.

See also
UpdateTransform

◆ CanUpdateAsync()

GraphUpdateThreading IUpdatableGraph. CanUpdateAsync ( GraphUpdateObject  o)
private

Implements IUpdatableGraph.

◆ CheckConnection()

bool CheckConnection ( GridNode  node,
int  dir 
)

Returns if node is connected to it's neighbour in the specified direction.

This will also return true if neighbours = NumNeighbours.Four, the direction is diagonal and one can move through one of the adjacent nodes to the targeted node.

See also
neighbourOffsets

◆ ClipLineSegmentToBounds()

bool ClipLineSegmentToBounds ( Vector3  a,
Vector3  b,
out Vector3  outA,
out Vector3  outB 
)
protected

Clips a line segment in graph space to the graph bounds.

That is (0,0,0) is the bottom left corner of the graph and (width,0,depth) is the top right corner. The first node is placed at (0.5,y,0.5). One unit distance is the same as nodeSize.

Returns false if the line segment does not intersect the graph at all.

◆ CountNodes()

override int CountNodes ( )
virtual

Number of nodes in the graph.

Note that this is, unless the graph type has overriden it, an O(n) operation.

This is an O(1) operation for grid graphs and point graphs. For layered grid graphs it is an O(n) operation.

Reimplemented from NavGraph.

Reimplemented in LayerGridGraph.

◆ CreateNavmeshSurfaceVisualization()

void CreateNavmeshSurfaceVisualization ( GridNodeBase []  nodes,
int  nodeCount,
GraphGizmoHelper  helper 
)
private

Draw the surface as well as an outline of the grid graph.

The nodes will be drawn as squares (or hexagons when using neighbours = Six).

◆ CrossMagnitude()

static float CrossMagnitude ( Vector2  a,
Vector2  b 
)
staticprotected

Magnitude of the cross product a x b.

◆ DeserializeExtraInfo()

override void DeserializeExtraInfo ( GraphSerializationContext  ctx)
protectedvirtual

Deserializes graph type specific node data.

See also
SerializeExtraInfo

Reimplemented from NavGraph.

Reimplemented in LayerGridGraph.

◆ DeserializeSettingsCompatibility()

override void DeserializeSettingsCompatibility ( GraphSerializationContext  ctx)
protectedvirtual

An old format for serializing settings.

Deprecated:
This is deprecated now, but the deserialization code is kept to avoid loosing data when upgrading from older versions.

Reimplemented from NavGraph.

◆ DestroyAllNodes()

override void DestroyAllNodes ( )
protectedvirtual

Destroys all nodes in the graph.

Warning
This is an internal method. Unless you have a very good reason, you should probably not call it.

Reimplemented from NavGraph.

◆ ErodeNode()

void ErodeNode ( GraphNode  node)
private

Internal method used for erosion.

◆ ErodeNodeWithTags()

void ErodeNodeWithTags ( GraphNode  node,
int  iteration 
)
private

Internal method used for erosion.

◆ ErodeNodeWithTagsInit()

void ErodeNodeWithTagsInit ( GraphNode  node)
private

Internal method used for erosion.

◆ ErodeWalkableArea() [1/2]

virtual void ErodeWalkableArea ( )
virtual

Erodes the walkable area.

See also
erodeIterations

◆ ErodeWalkableArea() [2/2]

void ErodeWalkableArea ( int  xmin,
int  zmin,
int  xmax,
int  zmax 
)

Erodes the walkable area.

xmin, zmin (inclusive)
xmax, zmax (exclusive)

See also
erodeIterations

◆ ErosionAnyFalseConnections()

virtual bool ErosionAnyFalseConnections ( GraphNode  baseNode)
protectedvirtual

True if the node has any blocked connections.

For 4 and 8 neighbours the 4 axis aligned connections will be checked. For 6 neighbours all 6 neighbours will be checked.

Internal method used for erosion.

Reimplemented in LayerGridGraph.

◆ GenerateMatrix()

void GenerateMatrix ( )

Generates the matrix used for translating nodes from grid coordinates to world coordinates.

Deprecated:
This method has been renamed to UpdateTransform

◆ GetConnectionCost()

uint GetConnectionCost ( int  dir)

◆ GetNearest()

override NNInfoInternal 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.

Reimplemented in LayerGridGraph.

◆ GetNearestForce()

override NNInfoInternal GetNearestForce ( Vector3  position,
NNConstraint  constraint 
)
virtual

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

Returns
an NNInfo. This method will only return an empty NNInfo if there are no nodes which comply with the specified constraint.

Reimplemented from NavGraph.

Reimplemented in LayerGridGraph.

◆ GetNodeConnection() [1/2]

GridNode GetNodeConnection ( GridNode  node,
int  dir 
)

◆ GetNodeConnection() [2/2]

GridNode GetNodeConnection ( int  index,
int  x,
int  z,
int  dir 
)
private

Get the connecting node from the node at (x,z) in the specified direction.

Returns
A GridNode if the node has a connection to that node. Null if no connection in that direction exists
See also
GridNode

◆ GetNodes()

override void GetNodes ( System.Action< GraphNode action)
virtual

Calls a delegate with all nodes in the graph.

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

Do not change the graph structure inside the delegate.

var gg = AstarPath.active.data.gridGraph;
gg.GetNodes(node => {
// Here is a node
Debug.Log("I found a node at position " + (Vector3)node.position);
});

If you want to store all nodes in a list you can do this

var gg = AstarPath.active.data.gridGraph;
List<GraphNode> nodes = new List<GraphNode>();
gg.GetNodes((System.Action<GraphNode>)nodes.Add);

Implements NavGraph.

Reimplemented in LayerGridGraph.

◆ GetNodesInArea() [1/3]

List<GraphNode> GetNodesInArea ( Bounds  bounds)
Deprecated:
This method has been renamed to GetNodesInRegion

◆ GetNodesInArea() [2/3]

List<GraphNode> GetNodesInArea ( GraphUpdateShape  shape)
Deprecated:
This method has been renamed to GetNodesInRegion

◆ GetNodesInArea() [3/3]

List<GraphNode> GetNodesInArea ( Bounds  bounds,
GraphUpdateShape  shape 
)
Deprecated:
This method has been renamed to GetNodesInRegion

◆ GetNodesInRegion() [1/5]

List<GraphNode> GetNodesInRegion ( Bounds  bounds)

All nodes inside the bounding box.

Note
Be nice to the garbage collector and pool the list when you are done with it (optional)
See also
Pathfinding.Util.ListPool
GetNodesInRegion(GraphUpdateShape)

◆ GetNodesInRegion() [2/5]

List<GraphNode> GetNodesInRegion ( GraphUpdateShape  shape)

All nodes inside the shape.

Note
Be nice to the garbage collector and pool the list when you are done with it (optional)
See also
Pathfinding.Util.ListPool
GetNodesInRegion(Bounds)

◆ GetNodesInRegion() [3/5]

virtual List<GraphNode> GetNodesInRegion ( Bounds  bounds,
GraphUpdateShape  shape 
)
protectedvirtual

All nodes inside the shape or if null, the bounding box.

If a shape is supplied, it is assumed to be contained inside the bounding box.

See also
GraphUpdateShape.GetBounds

Reimplemented in LayerGridGraph.

◆ GetNodesInRegion() [4/5]

virtual List<GraphNode> GetNodesInRegion ( IntRect  rect)
virtual

Get all nodes in a rectangle.

Parameters
rectRegion in which to return nodes. It will be clamped to the grid.

Reimplemented in LayerGridGraph.

◆ GetNodesInRegion() [5/5]

virtual int GetNodesInRegion ( IntRect  rect,
GridNodeBase []  buffer 
)
virtual

Get all nodes in a rectangle.

Parameters
rectRegion in which to return nodes. It will be clamped to the grid.
bufferBuffer in which the nodes will be stored. Should be at least as large as the number of nodes that can exist in that region.
Returns
The number of nodes written to the buffer.
Note
This method is much faster than GetNodesInRegion(IntRect) which returns a list because this method can make use of the highly optimized System.Array.Copy method.

Reimplemented in LayerGridGraph.

◆ GetRectFromBounds()

IntRect GetRectFromBounds ( Bounds  bounds)
protected

A rect with all nodes that the bounds could touch.

This correctly handles rotated graphs and other transformations. The returned rect is guaranteed to not extend outside the graph bounds.

◆ GraphPointToWorld()

Int3 GraphPointToWorld ( int  x,
int  z,
float  height 
)

Transform a point in graph space to world space.

This will give you the node position for the node at the given x and z coordinate if it is at the specified height above the base of the graph.

◆ HasNodeConnection() [1/2]

bool HasNodeConnection ( GridNode  node,
int  dir 
)

◆ HasNodeConnection() [2/2]

bool HasNodeConnection ( int  index,
int  x,
int  z,
int  dir 
)

◆ IsValidConnection()

virtual bool IsValidConnection ( GridNodeBase  node1,
GridNodeBase  node2 
)
virtual

Returns true if a connection between the adjacent nodes n1 and n2 is valid.

Also takes into account if the nodes are walkable.

This method may be overriden if you want to customize what connections are valid. It must however hold that IsValidConnection(a,b) == IsValidConnection(b,a).

This is used for calculating the connections when the graph is scanned or updated.

See also
CalculateConnections

◆ Linecast() [1/4]

bool Linecast ( Vector3  from,
Vector3  to 
)

Returns if there is an obstacle between from and to on the graph.

This is not the same as Physics.Linecast, this function traverses the graph and looks for collisions.

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

Implements IRaycastableGraph.

◆ Linecast() [2/4]

bool Linecast ( Vector3  from,
Vector3  to,
GraphNode  hint 
)

Returns if there is an obstacle between from and to on the graph.

Parameters
[in]fromPoint to linecast from
[in]toPoint to linecast to
[in]hintIf you have some idea of what the start node might be (the one close to from), pass it to hint since it can enable faster lookups

This is not the same as Physics.Linecast, this function traverses the graph and looks for collisions.

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

Implements IRaycastableGraph.

◆ Linecast() [3/4]

bool Linecast ( Vector3  from,
Vector3  to,
GraphNode  hint,
out GraphHitInfo  hit 
)

Returns if there is an obstacle between from and to on the graph.

Parameters
[in]fromPoint to linecast from
[in]toPoint to linecast to
[out]hitContains info on what was hit, see GraphHitInfo
[in]hintIf you have some idea of what the start node might be (the one close to _a), pass it to hint since it can enable faster lookups

This is not the same as Physics.Linecast, this function traverses the graph and looks for collisions.

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

Implements IRaycastableGraph.

◆ Linecast() [4/4]

bool Linecast ( Vector3  from,
Vector3  to,
GraphNode  hint,
out GraphHitInfo  hit,
List< GraphNode trace 
)

Returns if there is an obstacle between from and to on the graph.

Parameters
[in]fromPoint to linecast from
[in]toPoint to linecast to
[out]hitContains info on what was hit, see GraphHitInfo
[in]hintThis parameter is deprecated. It will be ignored.
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.

It uses a method similar to Bresenham's line algorithm but it has been extended to allow the start and end points to lie on non-integer coordinates (which makes the math a bit trickier).

See also
https://en.wikipedia.org/wiki/Bresenham's_line_algorithm
Version
In 3.6.8 this method was rewritten to improve accuracy and performance. Previously it used a sampling approach which could cut corners of obstacles slightly and was pretty inefficient.

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

Implements IRaycastableGraph.

◆ OnDestroy()

override void OnDestroy ( )
protectedvirtual

This function will be called when this graph is destroyed.

Reimplemented from NavGraph.

Reimplemented in LayerGridGraph.

◆ OnDrawGizmos()

override void OnDrawGizmos ( RetainedGizmos  gizmos,
bool  drawNodes 
)
virtual

Draw gizmos for the graph.

Reimplemented from NavGraph.

◆ PostDeserialization()

override void PostDeserialization ( GraphSerializationContext  ctx)
protectedvirtual

Called after all deserialization has been done for all graphs.

Can be used to set up more graph data which is not serialized

Reimplemented from NavGraph.

Reimplemented in LayerGridGraph.

◆ RecalculateCell()

virtual void RecalculateCell ( int  x,
int  z,
bool  resetPenalties = true,
bool  resetTags = true 
)
virtual

Recalculates single node in the graph.

For a layered grid graph this will recalculate all nodes at a specific (x,z) cell in the grid. For grid graphs this will simply recalculate the single node at those coordinates.

Parameters
xX coordinate of the cell
zZ coordinate of the cell
resetPenaltiesIf true, the penalty of the nodes will be reset to the initial value as if the graph had just been scanned (this excludes texture data however which is only done when scanning the graph).
resetTagsIf true, the tag will be reset to zero (the default tag).
Note
This must only be called when it is safe to update nodes. For example when scanning the graph or during a graph update.
This will not recalculate any connections as this method is often run for several adjacent nodes at a time. After you have recalculated all the nodes you will have to recalculate the connections for the changed nodes as well as their neighbours.
See also
CalculateConnections

Reimplemented in LayerGridGraph.

◆ RelocateNodes() [1/2]

override void RelocateNodes ( Matrix4x4  deltaMatrix)
virtual

Moves the nodes in this graph.

Multiplies all node positions by deltaMatrix.

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

var graph = AstarPath.data.pointGraph;
var m = Matrix4x4.TRS (new Vector3(10,0,0), Quaternion.identity, Vector3.one);
graph.RelocateNodes (m);
Note
For grid graphs, navmesh graphs and recast graphs it is recommended to use their custom overloads of the RelocateNodes method which take parameters for e.g center and nodeSize (and additional parameters) instead since they are both easier to use and are less likely to mess up pathfinding.
Warning
This method is lossy for PointGraphs, so calling it many times may cause node positions to lose precision. For example if you set the scale to 0 in one call then all nodes will be scaled/moved to the same point and you will not be able to recover their original positions. The same thing happens for other - less extreme - values as well, but to a lesser degree.

Reimplemented from NavGraph.

◆ RelocateNodes() [2/2]

void RelocateNodes ( Vector3  center,
Quaternion  rotation,
float  nodeSize,
float  aspectRatio = 1,
float  isometricAngle = 0 
)

Relocate the grid graph using new settings.

This will move all nodes in the graph to new positions which matches the new settings.

◆ RemoveGridGraphFromStatic()

void RemoveGridGraphFromStatic ( )
private

◆ ScanInternal()

override IEnumerable<Progress> ScanInternal ( )
protectedvirtual

Internal method to scan the graph.

Called from AstarPath.ScanAsync. Override this function to implement custom scanning logic. Progress objects can be yielded to show progress info in the editor and to split up processing over several frames when using async scanning.

Implements NavGraph.

Reimplemented in LayerGridGraph.

◆ SerializeExtraInfo()

override void SerializeExtraInfo ( GraphSerializationContext  ctx)
protectedvirtual

Serializes graph type specific node data.

This function can be overriden to serialize extra node information (or graph information for that matter) which cannot be serialized using the standard serialization. Serialize the data in any way you want and return a byte array. When loading, the exact same byte array will be passed to the DeserializeExtraInfo function.
These functions will only be called if node serialization is enabled.

Reimplemented from NavGraph.

Reimplemented in LayerGridGraph.

◆ SetDimensions()

void SetDimensions ( int  width,
int  depth,
float  nodeSize 
)

Updates unclampedSize from width, depth and nodeSize values.

Also generates a new matrix .

Note
This does not rescan the graph, that must be done with Scan

You should use this method instead of setting the width and depth fields as the grid dimensions are not defined by the width and depth variables but by the unclampedSize and center variables.

var gg = AstarPath.active.data.gridGraph;
var width = 80;
var depth = 60;
var nodeSize = 1.0f;
gg.SetDimensions(width, depth, nodeSize);
// Recalculate the graph

◆ SetNodeConnection() [1/2]

void SetNodeConnection ( GridNode  node,
int  dir,
bool  value 
)

◆ SetNodeConnection() [2/2]

void SetNodeConnection ( int  index,
int  x,
int  z,
int  dir,
bool  value 
)

Set if connection in the specified direction should be enabled.

Note that bounds checking will still be done when getting the connection value again, so it is not necessarily true that HasNodeConnection will return true just because you used SetNodeConnection on a node to set a connection to true.

Parameters
indexIndex of the node
xX coordinate of the node
zZ coordinate of the node
dirDirection from 0 up to but excluding 8.
valueEnable or disable the connection
Note
This is identical to Pathfinding.Node.SetConnectionInternal
Deprecated:

◆ SetUpOffsetsAndCosts()

virtual void SetUpOffsetsAndCosts ( )
virtual

Sets up neighbourOffsets with the current settings.

neighbourOffsets, neighbourCosts, neighbourXOffsets and neighbourZOffsets are set up.
The cost for a non-diagonal movement between two adjacent nodes is RoundToInt (nodeSize * Int3.Precision)
The cost for a diagonal movement between two adjacent nodes is RoundToInt (nodeSize * Sqrt (2) * Int3.Precision)

◆ SnappedLinecast()

bool SnappedLinecast ( Vector3  from,
Vector3  to,
GraphNode  hint,
out GraphHitInfo  hit 
)

Returns if there is an obstacle between from and to on the graph.

This function is different from the other Linecast functions since it 1) snaps the start and end positions directly to the graph.

Parameters
[in]fromPoint to linecast from
[in]toPoint to linecast to
[out]hitContains info on what was hit, see GraphHitInfo
[in]hint

◆ UpdateArea()

void IUpdatableGraph. UpdateArea ( GraphUpdateObject  o)
private

Internal function to update an area of the graph.

Implements IUpdatableGraph.

◆ UpdateAreaInit()

void IUpdatableGraph. UpdateAreaInit ( GraphUpdateObject  o)
private

May be called on the Unity thread before starting the update.

See also
CanUpdateAsync

Implements IUpdatableGraph.

◆ UpdateAreaPost()

void IUpdatableGraph. UpdateAreaPost ( GraphUpdateObject  o)
private

May be called on the Unity thread after executing the update.

See also
CanUpdateAsync

Implements IUpdatableGraph.

◆ UpdateNodePositionCollision()

virtual void UpdateNodePositionCollision ( GridNode  node,
int  x,
int  z,
bool  resetPenalty = true 
)
virtual

Updates position, walkability and penalty for the node.

Assumes that collision.Initialize (...) has been called before this function

Deprecated:
Use RecalculateCell instead which works both for grid graphs and layered grid graphs.

◆ UpdateSizeFromWidthDepth()

void UpdateSizeFromWidthDepth ( )

Updates unclampedSize from width, depth and nodeSize values.

Deprecated:
Use SetDimensions instead

◆ UpdateTransform()

void UpdateTransform ( )

Updates the transform field which transforms graph space to world space.

In graph space all nodes are laid out in the XZ plane with the first node having a corner in the origin. One unit in graph space is one node so the first node in the graph is at (0.5,0) the second one at (1.5,0) etc.

This takes the current values of the parameters such as position and rotation into account the transform that was used the last time the graph was scanned is stored in the transform field.

The transform field is calculated using this method when the graph is scanned. The width, depth variables are also updated based on the unclampedSize field.

Member Data Documentation

◆ aspectRatio

float aspectRatio = 1F

Scaling of the graph along the X axis.

This should be used if you want different scales on the X and Y axis of the grid

◆ center

Vector3 center

Center point of the grid.

◆ collision

GraphCollision collision

Settings on how to check for walkability and height.

◆ cutCorners

bool cutCorners = true

If disabled, will not cut corners on obstacles.

If connections is Eight, obstacle corners might be cut by a connection, setting this to false disables that.

cutCorners.png

◆ depth

int depth

Depth (height) of the grid in nodes.

See also
SetDimensions

◆ erodeIterations

int erodeIterations

Erosion of the graph.

The graph can be eroded after calculation. This means a margin is put around unwalkable nodes or other unwalkable connections. It is really good if your graph contains ledges where the nodes without erosion are walkable too close to the edge.

Below is an image showing a graph with erode iterations 0, 1 and 2

Note
A high number of erode iterations can seriously slow down graph updates during runtime (GraphUpdateObject) and should be kept as low as possible.
See also
erosionUseTags

◆ erosionFirstTag

int erosionFirstTag = 1

Tag to start from when using tags for erosion.

See also
erosionUseTags
erodeIterations

◆ erosionUseTags

bool erosionUseTags

Use tags instead of walkability for erosion.

Tags will be used for erosion instead of marking nodes as unwalkable. The nodes will be marked with tags in an increasing order starting with the tag erosionFirstTag. Debug with the Tags mode to see the effect. With this enabled you can in effect set how close different AIs are allowed to get to walls using the Valid Tags field on the Seeker component.

See also
erosionFirstTag

◆ getNearestForceOverlap

const int getNearestForceOverlap = 2

In GetNearestForce, determines how far to search after a valid node has been found.

◆ hexagonNeighbourIndices

readonly int [] hexagonNeighbourIndices = { 0, 1, 5, 2, 3, 7 }
staticpackage

Which neighbours are going to be used when neighbours=6.

◆ isometricAngle

float isometricAngle

Angle to use for the isometric projection.

If you are making a 2D isometric game, you may want to use this parameter to adjust the layout of the graph to match your game. This will essentially scale the graph along one of its diagonals to produce something like this:

A perspective view of an isometric graph.

A top down view of an isometric graph. Note that the graph is entirely 2D, there is no perspective in this image.

Usually the angle that you want to use is either 30 degrees (alternatively 90-30 = 60 degrees) or atan(1/sqrt(2)) which is approximately 35.264 degrees (alternatively 90 - 35.264 = 54.736 degrees). You might also want to rotate the graph plus or minus 45 degrees around the Y axis to get the oritientation required for your game.

You can read more about it on the wikipedia page linked below.

See also
http://en.wikipedia.org/wiki/Isometric_projection
https://en.wikipedia.org/wiki/Isometric_graphics_in_video_games_and_pixel_art
rotation

◆ maxClimb

float maxClimb = 0.4F

The max position difference between two nodes to enable a connection.

Set to 0 to ignore the value.

◆ maxSlope

float maxSlope = 90

The max slope in degrees for a node to be walkable.

◆ neighbourCosts

readonly uint [] neighbourCosts = new uint[8]

Costs to neighbour nodes.

◆ neighbourOffsets

readonly int [] neighbourOffsets = new int[8]

Index offset to get neighbour nodes.

Added to a node's index to get a neighbour node index.

Z
|
|
6 2 5
\ | /
-- 3 - X - 1 ----- X
/ | \
7 0 4
|
|

◆ neighbours

Number of neighbours for each node.

Either four, six, eight connections per node.

Six connections is primarily for emulating hexagon graphs.

◆ neighbourXOffsets

readonly int [] neighbourXOffsets = new int[8]

Offsets in the X direction for neighbour nodes.

Only 1, 0 or -1

◆ neighbourZOffsets

readonly int [] neighbourZOffsets = new int[8]

Offsets in the Z direction for neighbour nodes.

Only 1, 0 or -1

◆ nodes

GridNode [] nodes

All nodes in this graph.

Nodes are laid out row by row.

The first node has grid coordinates X=0, Z=0, the second one X=1, Z=0
the last one has grid coordinates X=width-1, Z=depth-1.

var gg = AstarPath.active.data.gridGraph;
int x = 5;
int z = 8;
GridNode node = gg.nodes[z*gg.width + x];
See also
GetNodes

◆ nodeSize

float nodeSize = 1

Size of one node in world units.

See also
SetDimensions

◆ penaltyAngle

bool penaltyAngle

◆ penaltyAngleFactor

float penaltyAngleFactor = 100F

How much penalty is applied depending on the slope of the terrain.

At a 90 degree slope (not that exactly 90 degree slopes can occur, but almost 90 degree), this penalty is applied. At a 45 degree slope, half of this is applied and so on. Note that you may require very large values, a value of 1000 is equivalent to the cost of moving 1 world unit.

◆ penaltyAnglePower

float penaltyAnglePower = 1

How much extra to penalize very steep angles.

◆ penaltyPosition

bool penaltyPosition

Use position (y-coordinate) to calculate penalty.

◆ penaltyPositionFactor

float penaltyPositionFactor = 1F

Scale factor for penalty when calculating from position.

See also
penaltyPosition

◆ penaltyPositionOffset

float penaltyPositionOffset

Offset for the position when calculating penalty.

See also
penaltyPosition

◆ rotation

Vector3 rotation

Rotation of the grid in degrees.

◆ showMeshOutline

bool showMeshOutline = true

Show an outline of the grid nodes in the Unity Editor.

◆ showMeshSurface

bool showMeshSurface = true

Show the surface of the graph.

Each node will be drawn as a square (unless e.g hexagon graph mode has been enabled).

◆ showNodeConnections

bool showNodeConnections

Show the connections between the grid nodes in the Unity Editor.

◆ textureData

TextureData textureData = new TextureData()

Holds settings for using a texture as source for a grid graph.

Texure data can be used for fine grained control over how the graph will look. It can be used for positioning, penalty and walkability control.
Below is a screenshot of a grid graph with a penalty map applied. It has the effect of the AI taking the longer path along the green (low penalty) areas.

Color data is got as 0...255 values.
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

Warning
Can only be used with Unity 3.4 and up

◆ unclampedSize

Vector2 unclampedSize

Size of the grid.

Might be negative or smaller than nodeSize

◆ uniformEdgeCosts

bool uniformEdgeCosts

If true, all edge costs will be set to the same value.

If false, diagonals will cost more. This is useful for a hexagon graph where the diagonals are actually the same length as the normal edges (since the graph has been skewed)

◆ useJumpPointSearch

bool useJumpPointSearch

◆ width

int width

Width of the grid in nodes.

See also
SetDimensions

Property Documentation

◆ Depth

int Depth
getset

◆ LayerCount

virtual int LayerCount
get

Number of layers in the graph.

For grid graphs this is always 1, for layered grid graphs it can be higher. The nodes array has the size width*depth*layerCount.

◆ size

Vector2 size
getprotected set

Size of the grid.

Will always be positive and larger than nodeSize.

See also
UpdateTransform

◆ transform

GraphTransform transform
getprivate set

Determines how the graph transforms graph space to world space.

See also
UpdateTransform

◆ uniformWidthDepthGrid

virtual bool uniformWidthDepthGrid
get

This is placed here so generators inheriting from this one can override it and set it to false.

If it is true, it means that the nodes array's length will always be equal to width*depth It is used mainly in the editor to do auto-scanning calls, setting it to false for a non-uniform grid will reduce the number of scans

◆ useRaycastNormal

bool useRaycastNormal
get

Use heigh raycasting normal for max slope calculation.

True if maxSlope is less than 90 degrees.

◆ Width

int Width
getset

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