Everything is in the GTNav2D namespace. Distances in MovementProfile are in cells. Distances in behaviour settings and in the scripting API are in world units.
NavGraph2D, NavAgent2D, FlyingAgent2D, MovingPlatform2D, GroundChaser, JumpAmbusher, FlyingChaser, RangedShooter, Projectile2DMovementProfile, FlyingProfile, ChaserSettings, AmbusherSettings, FlyerSettings, ShooterSettings, NavTileTypes, NavGraphDataINavAgent, IFlyingAgent, IMovingPlatform, NavAgentStatus, EnemyState, LinkType, NavPathStatusEnemyBehaviour2DNavGraph, NavLinkSet, NavSearch, NavPath, JumpTrajectory, buildersBakes Tilemaps into a navigation graph and answers path queries. A scene can contain several graphs.
| Inspector field | Description |
|---|---|
| Ground Tilemap | Solid tiles. Required. |
| One Way Tilemap | Optional one-way platforms. Needs a PlatformEffector2D with Use One Way and Surface Arc below 180 (170 recommended). |
| Ladder Tilemap | Optional ladders. No collider needed. |
| Tile Types | Optional NavTileTypes overrides for slope detection. |
| Moving Platforms, Auto Find Moving Platforms | Platforms agents may ride. Auto Find (default on) uses every enabled MovingPlatform2D. |
| Profiles | Profiles baked when the scene starts. |
| Bake On Awake | Bake when the scene starts (default on). |
| Bake In Background | Bake at startup on a worker thread. |
| Baked Data | A NavGraphData asset from Bake To Asset. Loaded at startup while it matches the tilemaps. |
| Debug Profile, Draw Nodes, Draw Links, Draw Trajectories | Scene view drawing. Draw Links: HoveredNode (default), All or None. |
| Log Bake Stats | Log node count and bake time. |
| Max Search Nodes | Most nodes one path search may expand (0 = no limit beyond the graph size). Caps the cost of searches for unreachable targets on huge maps. Applies to FindPath and to agents on this graph. |
| Member | Description |
|---|---|
void Bake() |
Rebuilds nodes from the Tilemaps and links for every listed profile. Uses Baked Data if it is up to date. |
void BakeAsync(Action onComplete = null) |
Rebakes on a worker thread (over several frames on WebGL). The old graph is used until the new one is ready. In Edit Mode it bakes synchronously. |
bool IsBaking, bool IsUsingBakedData |
Bake state. |
void BakeInto(NavGraphData) |
Stores the current graph and links in an asset (used by Bake To Asset). |
FlyGrid GetFlyGrid(FlyingProfile) |
Free-space grid used by flying agents. |
IReadOnlyList<IMovingPlatform> MovingPlatforms, void AddMovingPlatform(IMovingPlatform) |
Platforms used for ride links. Rebake after adding. |
Tilemap LadderTilemap, NavTileTypes TileTypes |
Ladder and tile-override sources. |
NavLinkSet GetLinks(MovementProfile) |
Links for a profile. Baked on first use. |
bool HasLinks(MovementProfile) |
True if that profile is already baked. |
NavPathStatus FindPath(MovementProfile, Vector2 from, Vector2 to, NavPath result) |
Path between two world positions. The start snaps to the nearest usable node; the destination snaps to the ground below it (up to 5 cells), so a jumping target resolves to where it will land. |
void SetTilemaps(Tilemap ground, Tilemap oneWay) |
Assigns the sources. Call Bake() afterwards. |
void AddProfile(MovementProfile) |
Adds a profile to bake up front. |
bool Contains(Vector2) |
True if the position is inside the baked grid. |
NavGraph Graph, bool IsBaked, float LastBakeMilliseconds |
Baked data and statistics. |
event Action Baked |
Raised after every bake. |
static IReadOnlyList<NavGraph2D> ActiveGraphs |
Enabled graphs. |
static NavGraph2D FindFor(Vector2) |
The enabled graph containing the position, else the first one. |
const float RecommendedOneWaySurfaceArc |
170. |
int MaxSearchNodes |
See Max Search Nodes above. |
Tilemap GroundTilemap, Tilemap OneWayTilemap, IReadOnlyList<MovementProfile> Profiles, NavGraphData BakedData |
Inspector settings. Assigning BakedData at runtime affects the next Bake(). |
MovementProfile DebugProfile, LinkGizmoMode LinkGizmos, static Color GetLinkColor(LinkType) |
Scene view drawing. |
IMovingPlatform GetPlatform(int), void GetOneWayColliders(List<Collider2D>) |
The platform a ride link refers to (NavLink.Platform); the one-way tilemap’s colliders. |
Scene view colors: green nodes are standable, orange nodes are on one-way platforms, gray nodes are unusable for the Debug Profile. Links: walk white, jump yellow, fall blue, drop-through magenta, climb mint, ride orange.
Moves a Rigidbody2D character along paths. Implements INavAgent.
| Inspector field | Description |
|---|---|
| Graph | Graph to use. If empty, the graph containing the agent is used. |
| Profile | Movement capabilities. |
| Ground Layers | Layers that count as ground. |
| Configure Rigidbody | Sets gravity scale (from the profile), zero damping, frozen rotation, interpolation, continuous collision, and a frictionless material if the collider has none. Default on. |
| Max Retries | Consecutive failed links that are retried, by repathing, before the status becomes Failed. |
| Draw Path | Draw the current path in the Scene view. |
| Member | Description |
|---|---|
bool SetDestination(Vector2) |
Plans and follows a path. Returns false if the destination is unreachable (status becomes Unreachable). Safe to call often; mid-air calls take effect on landing. |
bool CanReach(Vector2) |
Path check without moving. |
void Stop() |
Stops. An airborne agent finishes its current jump first. |
bool JumpTo(Vector2) |
One jump from the current node to the node at the position. Uses a baked link, or validates a jump on demand. |
bool TryFindJumpSpot(Vector2 target, float min, float max, out Vector2 spot) |
Finds a standing spot, min–max away from the target, from which one jump lands on it. Picks the spot that is cheapest to reach. |
NavAgentStatus Status |
Idle, Moving, Arrived, Unreachable or Failed. |
Vector2 Position |
Feet position (bottom center of the collider). |
bool IsGrounded, bool IsAirborne |
Contact state, and whether a jump, fall or drop is in progress. |
bool IsClimbing, bool IsRiding |
On a ladder; on a moving platform between stops. |
IMovingPlatform StandingOn |
The moving platform under the agent’s feet, or null. |
void ApplyKnockback(Vector2 velocity, float seconds) |
Sets the velocity and stops steering for seconds. |
void Suspend(float seconds = -1), void Resume(), bool IsSuspended |
Stops and resumes steering. The destination is kept. |
NavPath Path, int CurrentLinkIndex, Vector2 Destination |
Current plan. |
event Action<NavLink, bool> LinkCompleted |
Raised after each link. The flag is false if the agent did not land where planned. |
NavGraph2D Graph, MovementProfile Profile |
Can be changed at runtime. |
Flies a Rigidbody2D (gravity off) through free space. Implements IFlyingAgent. Positions are feet, like NavAgent2D.
| Member | Description |
|---|---|
Graph, Flying Profile (Inspector) / Graph, FlyingProfile |
Terrain source and flight settings. |
SetDestination, CanReach, Stop, Status, Position |
As in INavAgent. |
bool Dash(Vector2 target, float speed), bool IsDashing |
Straight-line dash that ignores pathfinding. |
bool HasClearLine(Vector2 from, Vector2 to) |
True if the body can fly straight between two feet positions. |
ApplyKnockback, Suspend, Resume, IsSuspended |
As in NavAgent2D. Knockback slows down by itself. |
Vector2 Center, IReadOnlyList<Vector2> Waypoints, int CurrentWaypointIndex |
Body center and current flight path (body centers). |
Kinematic platform that travels between stops and implements IMovingPlatform. See Terrain and Enemy Features.
| Member | Description |
|---|---|
Stops (Inspector) / IReadOnlyList<Vector2> Stops, void SetStops(IEnumerable<Vector2>) |
Offsets from the starting position. |
RouteMode Mode, bool Loops |
PingPong or Loop (Loops is true for a loop through 3 or more stops). |
float Speed, float WaitTime |
Units per second (default 3); seconds docked at each stop (default 1.5). |
Vector2 StopPosition(int) |
Platform position at a stop. |
Patrols, notices the target, chases it across platforms and attacks in melee range. Settings: ChaserSettings. State flow:
Patrol → Alert (reaction time) → Chase → Windup → Attack → Recover → Chase …
The flow ends in Return → Patrol when the target stays unreachable or out of range.
Keeps its distance, moves to a spot from which one jump lands on the target, crouches (Windup), and leaps (Attack). If the target moves during the wind-up, it repositions instead. HasLeapSpot and LeapSpot show the chosen spot. Settings: AmbusherSettings.
Needs an IFlyingAgent, such as FlyingAgent2D. It flies to a point above and beside the target (HoverPoint), hovers (Windup), dives (Attack) and recovers (Recover). IsWaiting is true while it waits near cover for the target to come out (FlyerCoverMode.WaitNearby). Settings: FlyerSettings.
Optional telegraph for any enemy behaviour (added by the GameObject menu items). It tints a sprite (the first SpriteRenderer in children unless assigned): blinking to Windup Color during the wind-up, brighter during the attack, blinking to Stun Color while stunned, and the sprite’s own color otherwise. Blink rates and colors are in the Inspector; BaseColor changes the resting color. Remove it if you drive animations from StateChanged instead.
Moves to a firing spot within range, aims (Windup), fires (Attack) and recovers (Recover). Retreats when the target comes too close. Settings: ShooterSettings. See Terrain and Enemy Features.
| Member | Description |
|---|---|
Projectile Prefab, Muzzle (Inspector) / ProjectilePrefab, Muzzle |
What to fire and from where. |
event Action<Projectile2D> Fired |
Raised for each projectile, right after launch. |
bool HasFiringSpot, Vector2 FiringSpot |
Current firing spot (debug). |
| Member | Description |
|---|---|
void Launch(Vector2 velocity, float gravity, float lifetime, Transform target, Collider2D[] ignore, Action<Projectile2D> onHitTarget) |
Starts the flight. RangedShooter calls it; you can also fire projectiles yourself. |
float Radius, LayerMask HitLayers, bool PassThroughOneWay |
Collision settings (radius default 0.15). The projectile never hits its own colliders or the shooter’s. |
| Rotate To Velocity (Inspector) | Turn the sprite to face the flight direction (default on). |
Vector2 Velocity, float Gravity, Transform Target |
Flight state. |
event Action<Projectile2D, Collider2D> Impact |
Raised once when the projectile ends (collider is null when it expired). |
static bool IsOneWay(Collider2D) |
True for colliders used by a one-way PlatformEffector2D. |
| Member | Description |
|---|---|
Target (Inspector) / Transform Target |
What to pursue. If empty, the object tagged Player (looked up again twice a second while there is none). |
| Settings (Inspector) | The settings asset. If empty, default settings are used. |
| Patrol Points | Transforms visited in order. If empty, the enemy guards its start position. A point that cannot be reached (for example walled off at runtime) is approached as far as possible along the straight line to it. |
On Attack Hit (Inspector) / UnityEvent<Transform> OnAttackHit |
Invoked when an attack hits. |
event Action<Transform> AttackHit |
Same, for code. |
event Action<EnemyState, EnemyState> StateChanged |
(previous, current). Useful for animation. |
EnemyState State, float StateTime |
Current state and seconds spent in it. |
int Facing |
1 = right, -1 = left. For flipping sprites. |
void Stun(float seconds), bool IsStunned |
Suspends the agent and enters Stunned. Afterwards the enemy chases again if the target is in range, otherwise it patrols. |
See Movement Profiles. Script members:
MovementParams ToParams(Vector2 cellSize, float fixedDeltaTime): converts to world units.float GravityInCells.const float LedgeClearance (0.5).event Action Changed, void NotifyChanged(): call it after changing fields from code at runtime, so graphs rebake the links.flySpeed (5 cells/s), acceleration (30 cells/s²), width / height (0.8 / 0.8 cells), passThroughOneWay (on). event Action Changed and void NotifyChanged() work as on MovementProfile.
| Field | Default | Description |
|---|---|---|
| detectionRange | 10 | Distance at which the target is noticed. |
| requireLineOfSight | on | The target’s head, center or feet must be visible. Once chasing, only distance matters. |
| sightBlockers | Default | Layers that block sight. |
| eyeHeight | 1.5 (FlyerSettings: 0.4) | Eye height above the feet. |
| reactionTime | 0.3 | Delay between noticing and acting. |
| giveUpWhenUnreachable | 3 | Seconds the target may stay unreachable before the enemy gives up. |
| giveUpWhenOutOfRange | 5 | Seconds the target may stay out of range before the enemy gives up. |
| reengageCooldown | 2 | After giving up, the enemy ignores the target this long. Afterwards it re-engages only if the target is reachable. |
| repathInterval | 0.25 | Seconds between path updates while pursuing. |
| patrolWaitTime | 1 | Pause at each patrol point. |
| Field | Default | Description |
|---|---|---|
| attackRange | 1.2 | Horizontal distance at which the wind-up starts. |
| attackHeightTolerance | 1 | Maximum height difference for the attack to start or hit. |
| attackWindup | 0.4 | Seconds before the hit lands. |
| attackHitRange | 1.5 | Reach when the hit lands. Leave it during the wind-up to dodge. |
| attackCooldown | 1 | Recovery after the attack. |
See Terrain and Enemy Features for the field table.
See Terrain and Enemy Features for the field table. ShotTrajectory: Straight, Arc.
Per-tile overrides: entries (tile + NavTileKind), NavTileKind KindOf(TileBase). Kinds: Auto, Solid, Empty, Slope45Up, Slope45Down, SlopeGentleUpLow, SlopeGentleUpHigh, SlopeGentleDownHigh, SlopeGentleDownLow.
Baked graph asset written by Bake To Asset: NodeCount, LinkCount, StoredProfiles, bool MatchesGrid(NavGrid). Usually you only assign it to a graph.
| Field | Default | Description |
|---|---|---|
| minLeapDistance / maxLeapDistance | 3 / 5 | Distance band the ambusher leaps from. |
| leapWindup | 0.5 | Crouch time before the leap. |
| maxTargetDrift | 1.5 | Cancel the leap if the target moves this far during the wind-up. |
| hitRadius | 1 | Distance between body centers that counts as a hit during the leap. |
| leapCooldown | 1 | Recovery after landing. |
Implement this interface to let the enemy behaviours drive your own character controller.
public interface INavAgent
{
MovementProfile Profile { get; }
Vector2 Position { get; } // feet
bool IsGrounded { get; }
NavAgentStatus Status { get; }
bool SetDestination(Vector2 worldPosition);
bool CanReach(Vector2 worldPosition);
void Stop();
bool IsSuspended { get; }
void Suspend(float seconds = -1f); // knockback, stun
void Resume();
bool JumpTo(Vector2 worldPosition);
bool TryFindJumpSpot(Vector2 target, float minDistance, float maxDistance, out Vector2 spot);
bool TryFindStandingSpot(Vector2 around, float minDistance, float maxDistance,
Predicate<Vector2> accept, out Vector2 spot); // firing spots
}
A custom implementation can use NavGraph2D.GetLinks and NavSearch for planning. To execute an airborne NavLink:
link.Takeoff.vx = (link.Landing.x - feet.x) / ((link.AirSteps - link.SteerDelay) * Time.fixedDeltaTime) and set the vertical velocity to link.Velocity.y.link.SteerDelay physics steps (steered jumps rise straight up first), then at vx until landing. For most links SteerDelay is 0.Extends INavAgent with Dash(target, speed), IsDashing and HasClearLine(from, to). FlyingChaser needs it.
Implement it on your own platform and register it with NavGraph2D.AddMovingPlatform:
StopCount, GetStopTopCenter(stop), Width;CycleTime, TravelTime(from, to);IsDockedAt(stop), DockTimeRemaining;Velocity, TopCenter;Loops: true when the platform travels from the last stop straight back to the first (agents and jumps are kept out of that leg too).NavAgentStatus: Idle, Moving, Arrived, Unreachable, Failed.EnemyState: Patrol, Alert, Chase, Windup, Attack, Recover, Return, Stunned.LinkType: Walk, Jump, Fall, DropThrough, Climb, Ride. NavLink.IsAirborne is true for Jump, Fall and DropThrough.NavPathStatus: None, Found, NoStartNode, NoGoalNode, NotFound, LimitReached.LinkGizmoMode: HoveredNode, All, None.FlyerCoverMode: ApproachLow, WaitNearby.Derive from EnemyBehaviour2D. The base class already handles detection, patrol and giving up. You implement the engaged states.
using GTNav2D;
using UnityEngine;
public class CowardlyEnemy : EnemyBehaviour2D
{
[SerializeField] ChaserSettings settings;
public override EnemySettings Settings => settings;
protected override void UpdateEngaged()
{
// Run away from the target instead of chasing it.
if (RepathDue())
LastReachable = Agent.SetDestination(Position + (Position - TargetFeet).normalized * 6f);
UpdatePursuit(); // gives up when the target is out of range for too long
}
}
Protected helpers:
Agent (the INavAgent), Position, TargetFeet, TargetCenter, BodyCenter, HasTarget, IsTargetInRange.RepathDue(), RepathNow(), UpdatePursuit(), GiveUp(), ChangeState(EnemyState), RaiseAttackHit().virtual bool IsTargetEngageable(): the default requires the target to be reachable.Pure C# with no MonoBehaviours. Use these classes for tools, custom terrain or turn-based movement.
| Type | Description |
|---|---|
NavGrid |
Cell occupancy (Empty, Solid, OneWay, slope kinds), ladder flags, origin and cell size. SurfaceHeight(cell, x) gives a slope’s surface height. NavGraph2D bakes it from Tilemaps; fill one by hand only to use NavGraphBuilder and NavSearch directly. |
TilemapGridBuilder.Build(ground, oneWay, tileTypes, ladders) |
Tilemaps → NavGrid. |
FlyGrid |
Free space for one flying body size: IsBodyFree, HasClearLine, FindPath(from, to, waypoints). |
NavGraphBuilder.BuildNodes(NavGrid) |
Creates a NavGraph with a node on every empty cell above a solid or one-way cell. |
NavGraphBuilder.BuildLinks(NavGraph, MovementParams) |
Builds a NavLinkSet for one profile. |
NavGraphBuilder.TryCreateJump(graph, params, from, to, out link) |
Validates one jump on demand. |
NavGraph |
Nodes, GetNodeAt(cell), FindNearestNode(world, links, radius), FindGroundNode(world, links, maxDrop) (the node straight below, else the nearest; used for destinations). |
NavNode |
Index, Cell, Position (feet), IsOneWay, Clearance, IsSlope, IsLadder. |
NavLink |
From, To, Type, Cost, Takeoff, Landing, Velocity, AirSteps, SteerDelay (steps of straight-up rise before a steered jump moves sideways); for rides Platform, FromStop, ToStop. |
NavLinkSet |
Per-profile links: Links, FirstLink(node), LinkCountOf(node), FindLink(a, b), IsNodeUsable(node), CountByType(type), Params. |
NavSearch |
A* with its own buffers. Reuse an instance; use separate instances for concurrent queries. FindPath(links, from, to, path), MaxExpandedNodes (0 = graph size), LastExpandedCount. |
NavPath |
Status, Found, Cost, Nodes, Links, Points, TruncateByCost(maxCost) for action-point movement. |
MovementParams |
World-unit movement values used by baking. |
JumpTrajectory |
The shared motion model: PositionAtStep, ApexHeight, LaunchSpeedForApex, FindLandingStep, TrySolve, IsPathClear, SampleLink. |
Ballistics |
Projectile launch solutions with the same motion model: TrySolveArc(delta, maxSpeed, gravity, dt, high, out velocity, out steps), VelocityForSteps, LeadStraight. |
BinaryHeap |
Min-heap used by NavSearch. |
var path = new NavPath();
graph.FindPath(profile, unit.position, target.position, path);
if (path.Found)
{
path.TruncateByCost(actionPoints); // keep only the affordable part
// Execute path.Links one by one with your own animation code.
}