navigation_introduction_2d.rst 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. .. _doc_navigation_overview_2d:
  2. 2D navigation overview
  3. ======================
  4. Godot provides multiple objects, classes and servers to facilitate grid-based or mesh-based navigation and pathfinding for 2D and 3D games.
  5. The following section provides a quick overview over all available navigation related objects in Godot for 2D scenes and their primary use.
  6. Godot provides the following objects and classes for 2D navigation:
  7. - :ref:`Astar2D<class_Astar2D>`
  8. ``Astar2D`` objects provide an option to find the shortest path in a graph of weighted **points**.
  9. The AStar2D class is best suited for cell-based 2D gameplay that does not require actors to reach any possible position within an area but only predefined, distinct positions.
  10. - :ref:`AstarGrid2D<class_AstarGrid2D>`
  11. ``AstarGrid2D`` is a variant of AStar2D that is specialized for partial 2D grids.
  12. AstarGrid2D is simpler to use when applicable because it doesn't require you to manually create points and connect them together.
  13. - :ref:`NavigationServer2D<class_NavigationServer2D>`
  14. ``NavigationServer2D`` provides a powerful server API to find the shortest path between two positions on an area defined by a navigation mesh.
  15. The NavigationServer is best suited for 2D realtime gameplay that does require actors to reach any possible position within a navigation mesh defined area.
  16. Mesh-based navigation scales well with large game worlds as a large area can often be defined with a single polygon when it would require many, many grid cells.
  17. The NavigationServer holds different navigation maps that each consist of regions that hold navigation mesh data.
  18. Agents can be placed on a map for avoidance calculation.
  19. RIDs are used to reference internal maps, regions, and agents when communicating with the server.
  20. The following NavigationServer RID types are available.
  21. - NavMap RID
  22. Reference to a specific navigation map that holds regions and agents.
  23. The map will attempt to join the navigation meshes of the regions by proximity.
  24. The map will synchronize regions and agents each physics frame.
  25. - NavRegion RID
  26. Reference to a specific navigation region that can hold navigation mesh data.
  27. The region can be enabled / disabled or the use restricted with a navigation layer bitmask.
  28. - NavLink RID
  29. Reference to a specific navigation link that connects two navigation mesh positions over arbitrary distances.
  30. - NavAgent RID
  31. Reference to a specific avoidance agent.
  32. The avoidance is specified by a radius value.
  33. - NavObstacle RID
  34. Reference to a specific avoidance obstacle used to affect and constrain the avoidance velocity of agents.
  35. The following scene tree nodes are available as helpers to work with the NavigationServer2D API.
  36. - :ref:`NavigationRegion2D<class_NavigationRegion2D>` Node
  37. A Node that holds a NavigationPolygon resource that defines a navigation mesh for the NavigationServer2D.
  38. - The region can be enabled / disabled.
  39. - The use in pathfinding can be further restricted through the ``navigation_layers`` bitmask.
  40. - The NavigationServer2D will join the navigation meshes of regions by proximity for a combined navigation mesh.
  41. - :ref:`NavigationLink2D<class_NavigationLink2D>` Node
  42. A Node that connects two positions on navigation meshes over arbitrary distances for pathfinding.
  43. - The link can be enabled / disabled.
  44. - The link can be made one-way or bidirectional.
  45. - The use in pathfinding can be further restricted through the ``navigation_layers`` bitmask.
  46. Links tell the pathfinding that a connection exists and at what cost. The actual agent handling and movement needs to happen in custom scripts.
  47. - :ref:`NavigationAgent2D<class_NavigationAgent2D>` Node
  48. A helper Node used to facilitate common NavigationServer2D API calls for pathfinding and avoidance.
  49. Use this Node with a Node2D inheriting parent Node.
  50. - :ref:`NavigationObstacle2D<class_NavigationObstacle2D>` Node
  51. A Node that can be used to affect and constrain the avoidance velocity of avoidance enabled agents.
  52. This Node does NOT affect the pathfinding of agents. You need to change the navigation meshes for that instead.
  53. The 2D navigation meshes are defined with the following resources:
  54. - :ref:`NavigationPolygon<class_NavigationPolygon>` Resource
  55. A resource that holds 2D navigation mesh data.
  56. It provides polygon drawing tools to allow defining navigation areas inside the Editor as well as at runtime.
  57. - The NavigationRegion2D Node uses this resource to define its navigation area.
  58. - The NavigationServer2D uses this resource to update the navigation mesh of individual regions.
  59. - The TileSet Editor creates and uses this resource internally when defining tile navigation areas.
  60. .. seealso::
  61. You can see how 2D navigation works in action using the
  62. `2D Navigation Polygon <https://github.com/godotengine/godot-demo-projects/tree/master/2d/navigation>`__
  63. and `Grid-based Navigation with AStarGrid2D <https://github.com/godotengine/godot-demo-projects/tree/master/2d/navigation_astar>`__
  64. demo projects.
  65. Setup for 2D scene
  66. ------------------
  67. The following steps show the basic setup for minimal viable navigation in 2D.
  68. It uses the NavigationServer2D and a NavigationAgent2D for path movement.
  69. #. Add a NavigationRegion2D Node to the scene.
  70. #. Click on the region node and add a new NavigationPolygon Resource to the region node.
  71. .. image:: img/nav_2d_min_setup_step1.png
  72. #. Define the movable navigation area with the NavigationPolygon draw tool. Then click
  73. the `Bake NavigationPolygon`` button on the toolbar.
  74. .. image:: img/nav_2d_min_setup_step2.png
  75. .. note::
  76. The navigation mesh defines the area where an actor can stand and move with its center.
  77. Leave enough margin between the navigation polygon edges and collision objects to not get path following actors repeatedly stuck on collision.
  78. #. Add a CharacterBody2D node in the scene with a basic collision shape and a sprite or mesh
  79. for visuals.
  80. #. Add a NavigationAgent2D node below the character node.
  81. .. image:: img/nav_2d_min_setup_step3.webp
  82. #. Add the following script to the CharacterBody2D node. We make sure to set a movement target
  83. after the scene has fully loaded and the NavigationServer had time to sync.
  84. .. tabs::
  85. .. code-tab:: gdscript GDScript
  86. extends CharacterBody2D
  87. var movement_speed: float = 200.0
  88. var movement_target_position: Vector2 = Vector2(60.0,180.0)
  89. @onready var navigation_agent: NavigationAgent2D = $NavigationAgent2D
  90. func _ready():
  91. # These values need to be adjusted for the actor's speed
  92. # and the navigation layout.
  93. navigation_agent.path_desired_distance = 4.0
  94. navigation_agent.target_desired_distance = 4.0
  95. # Make sure to not await during _ready.
  96. actor_setup.call_deferred()
  97. func actor_setup():
  98. # Wait for the first physics frame so the NavigationServer can sync.
  99. await get_tree().physics_frame
  100. # Now that the navigation map is no longer empty, set the movement target.
  101. set_movement_target(movement_target_position)
  102. func set_movement_target(movement_target: Vector2):
  103. navigation_agent.target_position = movement_target
  104. func _physics_process(delta):
  105. if navigation_agent.is_navigation_finished():
  106. return
  107. var current_agent_position: Vector2 = global_position
  108. var next_path_position: Vector2 = navigation_agent.get_next_path_position()
  109. velocity = current_agent_position.direction_to(next_path_position) * movement_speed
  110. move_and_slide()
  111. .. code-tab:: csharp C#
  112. using Godot;
  113. public partial class MyCharacterBody2D : CharacterBody2D
  114. {
  115. private NavigationAgent2D _navigationAgent;
  116. private float _movementSpeed = 200.0f;
  117. private Vector2 _movementTargetPosition = new Vector2(70.0f, 226.0f);
  118. public Vector2 MovementTarget
  119. {
  120. get { return _navigationAgent.TargetPosition; }
  121. set { _navigationAgent.TargetPosition = value; }
  122. }
  123. public override void _Ready()
  124. {
  125. base._Ready();
  126. _navigationAgent = GetNode<NavigationAgent2D>("NavigationAgent2D");
  127. // These values need to be adjusted for the actor's speed
  128. // and the navigation layout.
  129. _navigationAgent.PathDesiredDistance = 4.0f;
  130. _navigationAgent.TargetDesiredDistance = 4.0f;
  131. // Make sure to not await during _Ready.
  132. Callable.From(ActorSetup).CallDeferred();
  133. }
  134. public override void _PhysicsProcess(double delta)
  135. {
  136. base._PhysicsProcess(delta);
  137. if (_navigationAgent.IsNavigationFinished())
  138. {
  139. return;
  140. }
  141. Vector2 currentAgentPosition = GlobalTransform.Origin;
  142. Vector2 nextPathPosition = _navigationAgent.GetNextPathPosition();
  143. Velocity = currentAgentPosition.DirectionTo(nextPathPosition) * _movementSpeed;
  144. MoveAndSlide();
  145. }
  146. private async void ActorSetup()
  147. {
  148. // Wait for the first physics frame so the NavigationServer can sync.
  149. await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame);
  150. // Now that the navigation map is no longer empty, set the movement target.
  151. MovementTarget = _movementTargetPosition;
  152. }
  153. }
  154. .. note::
  155. On the first frame the NavigationServer map has not synchronized region data and any path query will return empty. Wait for the NavigationServer synchronization by awaiting one frame in the script.