navigation_using_navigationagents.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. .. _doc_navigation_using_navigationagents:
  2. Using NavigationAgents
  3. ======================
  4. NavigationsAgents are helper nodes that combine functionality
  5. for pathfinding, path following and agent avoidance for a Node2D/3D inheriting parent node.
  6. They facilitate common calls to the NavigationServer API on
  7. behalf of the parent actor node in a more convenient manner for beginners.
  8. 2D and 3D version of NavigationAgents are available as
  9. :ref:`NavigationAgent2D<class_NavigationAgent2D>` and
  10. :ref:`NavigationAgent3D<class_NavigationAgent3D>` respectively.
  11. New NavigationAgent nodes will automatically join the default navigation map on the :ref:`World2D<class_World2D>`/:ref:`World3D<class_World3D>`.
  12. NavigationsAgent nodes are optional and not a hard requirement to use the navigation system.
  13. Their entire functionality can be replaced with scripts and direct calls to the NavigationServer API.
  14. NavigationAgent Pathfinding
  15. ---------------------------
  16. NavigationAgents query a new navigation path on their current navigation map when their ``target_position`` is set with a global position.
  17. The result of the pathfinding can be influenced with the following properties.
  18. - The ``navigation_layers`` bitmask can be used to limit the navigation meshes that the agent can use.
  19. - The ``pathfinding_algorithm`` controls how the pathfinding travels through the navigation mesh polygons in the path search.
  20. - The ``path_postprocessing`` sets if or how the raw path corridor found by the pathfinding is altered before it is returned.
  21. - The ``path_metadata_flags`` enable the collection of additional path point meta data returned by the path.
  22. .. warning::
  23. Disabling path meta flags will disable related signal emissions on the agent.
  24. NavigationAgent Pathfollowing
  25. -----------------------------
  26. After a ``target_position`` has been set for the agent, the next position to follow in the path
  27. can be retrieved with the ``get_next_path_position()`` function.
  28. Once the next path position is received move the parent actor node of the agent
  29. towards this path position with your own movement code.
  30. .. note::
  31. The navigation system never moves the parent node of a NavigationAgent.
  32. The movement is entirely in the hands of users and their custom scripts.
  33. NavigationAgents have their own internal logic to proceed with the current path and call for updates.
  34. The ``get_next_path_position()`` function is responsible for updating many of the agent's internal states and properties.
  35. The function should be repeatedly called *once* every ``physics_process`` until ``is_navigation_finished()`` tells that the path is finished.
  36. The function should not be called after the target position or path end has been reached
  37. as it can make the agent jitter in place due to the repeated path updates.
  38. Always check very early in script with ``is_navigation_finished()`` if the path is already finished.
  39. The following properties influence the path following behavior.
  40. - The ``path_desired_distance`` defines the distance at which the agent advances its internal path index to the next path position.
  41. - The ``target_desired_distance`` defines the distance at which the agent considers the target position to be reached and the path at its end.
  42. - The ``path_max_distance`` defines when an agent requests a new path cause it was moved too far away from the current path point segment.
  43. The important updates are all triggered with the ``get_next_path_position()`` function
  44. when called in ``_physics_process()``.
  45. NavigationAgents can be used with ``process`` but are still limited to a single update that happens in ``physics_process``.
  46. Script examples for various nodes commonly used with NavigationAgents can be found further below.
  47. Pathfollowing common problems
  48. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  49. There are some common user problems and important caveats to consider when writing agent movement scripts.
  50. - The path is returned empty
  51. If an agent queries a path before the navigation map synchronisation, e.g. in a ``_ready()`` function, the path might return empty. In this case the ``get_next_path_position()`` function will return the same position as the agent parent node and the agent will consider the path end reached. This is fixed by making a deferred call or using a callback e.g. waiting for the navigation map changed signal.
  52. - The agent is stuck dancing between two positions
  53. This is usually caused by very frequent path updates every single frame, either deliberate or by accident (e.g. max path distance set too short). The pathfinding needs to find the closest position that are valid on navigation mesh. If a new path is requested every single frame the first path positions might end up switching constantly in front and behind the agent's current position, causing it to dance between the two positions.
  54. - The agent is backtracking sometimes
  55. If an agent moves very fast it might overshoot the path_desired_distance check without ever advancing the path index. This can lead to the agent backtracking to the path point now behind it until it passes the distance check to increase the path index. Increase the desired distances accordingly for your agent speed and update rate usually fixes this as well as a more balanced navigation mesh polygon layout with not too many polygon edges cramped together in small spaces.
  56. - The agent is sometimes looking backwards for a frame
  57. Same as with stuck dancing agents between two positions, this is usually caused by very frequent path updates every single frame. Depending on your navigation mesh layout, and especially when an agent is directly placed over a navigation mesh edge or edge connection, expect path positions to be sometimes slightly "behind" your actors current orientation. This happens due to precision issues and can not always be avoided. This is usually only a visible problem if actors are instantly rotated to face the current path position.
  58. NavigationAgent Avoidance
  59. -------------------------
  60. This section explains how to use the navigation avoidance specific to NavigationAgents.
  61. In order for NavigationAgents to use the avoidance feature the ``enable_avoidance`` property must be set to ``true``.
  62. .. image:: img/agent_avoidance_enabled.png
  63. The ``velocity_computed`` signal of the NavigationAgent node must be connected to receive the safe velocity calculation result.
  64. .. image:: img/agent_safevelocity_signal.png
  65. Use ``set_velocity()`` on the NavigationAgent node in ``_physics_process()`` to update the agent with the current velocity of the agent's parent node.
  66. While avoidance is enabled on the agent the ``safe_velocity`` vector will be received with the velocity_computed signal every physics frame.
  67. This velocity vector should be used to move the NavigationAgent's parent node in order to avoidance collision with other avoidance using agents or avoidance obstacles.
  68. .. note::
  69. Only other agents on the same map that are registered for avoidance themself will be considered in the avoidance calculation.
  70. The following NavigationAgent properties are relevant for avoidance:
  71. - The property ``height`` is available in 3D only. The height together with the current global y-axis position of the agent determines the vertical placement of the agent in the avoidance simulation. Agents using the 2D avoidance will automatically ignore other agents or obstacles that are below or above them.
  72. - The property ``radius`` controls the size of the avoidance circle, or in case of 3D sphere, around the agent. This area describes the agents body and not the avoidance maneuver distance.
  73. - The property ``neighbor_distance`` controls the search radius of the agent when searching for other agents that should be avoided. A lower value reduces processing cost.
  74. - The property ``max_neighbors`` controls how many other agents are considered in the avoidance calculation if they all have overlapping radius.
  75. A lower value reduces processing cost but a too low value may result in agents ignoring the avoidance.
  76. - The properties ``time_horizon_agents`` and ``time_horizon_obstacles`` control the avoidance prediction time for other agents or obstacles in seconds. When agents calculate their safe velocities they choose velocities that can be kept for this amount of seconds without colliding with another avoidance object. The prediction time should be kept as low as possible as agents will slow down their velocities to avoid collision in that timeframe.
  77. - The property ``max_speed`` controls the maximum velocity allowed for the agents avoidance calculation.
  78. If the agents parents moves faster than this value the avoidance ``safe_velocity`` might not be accurate enough to avoid collision.
  79. - The property ``use_3d_avoidance`` switches the agent between the 2D avoidance (xz axis) and the 3D avoidance (xyz axis) on the next update.
  80. Note that 2D avoidance and 3D avoidance run in separate avoidance simulations so agents split between them do not affect each other.
  81. - The properties ``avoidance_layers`` and ``avoidance_mask`` are bitmasks similar to e.g. physics layers. Agents will only avoid other avoidance objects that are on an avoidance layer that matches at least one of their own avoidance mask bits.
  82. - The ``avoidance_priority`` makes agents with a higher priority ignore agents with a lower priority. This can be used to give certain agents more importance in the avoidance simulation, e.g. important npcs characters, without constantly changing their entire avoidance layers or mask.
  83. Avoidance exists in its own space and has no information from navigation meshes or physics collision.
  84. Behind the scene avoidance agents are just circles with different radius on a flat 2D plane or spheres in an otherwise empty 3D space.
  85. NavigationObstacles can be used to add some environment constrains to the avoidance simulation, see :ref:`doc_navigation_using_navigationobstacles`.
  86. .. note::
  87. Avoidance does not affect the pathfinding. It should be seen as an additional option for constantly moving objects that cannot be (re)baked to a navigation mesh efficiently in order to move around them.
  88. Using the NavigationAgent ``enable_avoidance`` property is the preferred option
  89. to toggle avoidance. The following code snippets can be used to
  90. toggle avoidance on agents, create or delete avoidance callbacks or switch avoidance modes.
  91. .. tabs::
  92. .. code-tab:: gdscript GDScript
  93. extends NavigationAgent2D
  94. var agent: RID = get_rid()
  95. # Enable avoidance
  96. NavigationServer2D.agent_set_avoidance_enabled(agent, true)
  97. # Create avoidance callback
  98. NavigationServer2D.agent_set_avoidance_callback(agent, Callable(self, "_avoidance_done"))
  99. # Disable avoidance
  100. NavigationServer2D.agent_set_avoidance_enabled(agent, false)
  101. # Delete avoidance callback
  102. NavigationServer2D.agent_set_avoidance_callback(agent, Callable())
  103. .. tabs::
  104. .. code-tab:: gdscript GDScript
  105. extends NavigationAgent3D
  106. var agent: RID = get_rid()
  107. # Enable avoidance
  108. NavigationServer3D.agent_set_avoidance_enabled(agent, true)
  109. # Create avoidance callback
  110. NavigationServer3D.agent_set_avoidance_callback(agent, Callable(self, "_avoidance_done"))
  111. # Switch to 3D avoidance
  112. NavigationServer3D.agent_set_use_3d_avoidance(agent, true)
  113. # Disable avoidance
  114. NavigationServer3D.agent_set_avoidance_enabled(agent, false)
  115. # Delete avoidance callback
  116. NavigationServer3D.agent_set_avoidance_callback(agent, Callable())
  117. # Switch to 2D avoidance
  118. NavigationServer3D.agent_set_use_3d_avoidance(agent, false)
  119. NavigationAgent Script Templates
  120. --------------------------------
  121. The following sections provides script templates for nodes commonly used with NavigationAgents.
  122. Actor as Node3D
  123. ~~~~~~~~~~~~~~~
  124. This script adds basic navigation movement to a :ref:`Node3D <class_Node3D>` with a :ref:`NavigationAgent3D <class_NavigationAgent3D>` child node.
  125. .. tabs::
  126. .. code-tab:: gdscript GDScript
  127. extends Node3D
  128. @export var movement_speed: float = 4.0
  129. @onready var navigation_agent: NavigationAgent3D = get_node("NavigationAgent3D")
  130. var movement_delta: float
  131. func _ready() -> void:
  132. navigation_agent.velocity_computed.connect(Callable(_on_velocity_computed))
  133. func set_movement_target(movement_target: Vector3):
  134. navigation_agent.set_target_position(movement_target)
  135. func _physics_process(delta):
  136. if navigation_agent.is_navigation_finished():
  137. return
  138. movement_delta = movement_speed * delta
  139. var next_path_position: Vector3 = navigation_agent.get_next_path_position()
  140. var new_velocity: Vector3 = global_position.direction_to(next_path_position) * movement_delta
  141. if navigation_agent.avoidance_enabled:
  142. navigation_agent.set_velocity(new_velocity)
  143. else:
  144. _on_velocity_computed(new_velocity)
  145. func _on_velocity_computed(safe_velocity: Vector3) -> void:
  146. global_position = global_position.move_toward(global_position + safe_velocity, movement_delta)
  147. Actor as CharacterBody3D
  148. ~~~~~~~~~~~~~~~~~~~~~~~~
  149. This script adds basic navigation movement to a :ref:`CharacterBody3D <class_CharacterBody3D>` with a :ref:`NavigationAgent3D <class_NavigationAgent3D>` child node.
  150. .. tabs::
  151. .. code-tab:: gdscript GDScript
  152. extends CharacterBody3D
  153. @export var movement_speed: float = 4.0
  154. @onready var navigation_agent: NavigationAgent3D = get_node("NavigationAgent3D")
  155. func _ready() -> void:
  156. navigation_agent.velocity_computed.connect(Callable(_on_velocity_computed))
  157. func set_movement_target(movement_target: Vector3):
  158. navigation_agent.set_target_position(movement_target)
  159. func _physics_process(delta):
  160. if navigation_agent.is_navigation_finished():
  161. return
  162. var next_path_position: Vector3 = navigation_agent.get_next_path_position()
  163. var new_velocity: Vector3 = global_position.direction_to(next_path_position) * movement_speed
  164. if navigation_agent.avoidance_enabled:
  165. navigation_agent.set_velocity(new_velocity)
  166. else:
  167. _on_velocity_computed(new_velocity)
  168. func _on_velocity_computed(safe_velocity: Vector3):
  169. velocity = safe_velocity
  170. move_and_slide()
  171. Actor as RigidBody3D
  172. ~~~~~~~~~~~~~~~~~~~~
  173. This script adds basic navigation movement to a :ref:`RigidBody3D <class_RigidBody3D>` with a :ref:`NavigationAgent3D <class_NavigationAgent3D>` child node.
  174. .. tabs::
  175. .. code-tab:: gdscript GDScript
  176. extends RigidBody3D
  177. @export var movement_speed: float = 4.0
  178. @onready var navigation_agent: NavigationAgent3D = get_node("NavigationAgent3D")
  179. func _ready() -> void:
  180. navigation_agent.velocity_computed.connect(Callable(_on_velocity_computed))
  181. func set_movement_target(movement_target: Vector3):
  182. navigation_agent.set_target_position(movement_target)
  183. func _physics_process(delta):
  184. if navigation_agent.is_navigation_finished():
  185. return
  186. var next_path_position: Vector3 = navigation_agent.get_next_path_position()
  187. var new_velocity: Vector3 = global_position.direction_to(next_path_position) * movement_speed
  188. if navigation_agent.avoidance_enabled:
  189. navigation_agent.set_velocity(new_velocity)
  190. else:
  191. _on_velocity_computed(new_velocity)
  192. func _on_velocity_computed(safe_velocity: Vector3):
  193. linear_velocity = safe_velocity