ray-casting.rst 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. .. _doc_ray-casting:
  2. Ray-casting
  3. ===========
  4. Introduction
  5. ------------
  6. One of the most common tasks in game development is casting a ray (or
  7. custom shaped object) and checking what it hits. This enables complex
  8. behaviors, AI, etc. to take place. This tutorial will explain how to
  9. do this in 2D and 3D.
  10. Godot stores all the low level game information in servers, while the
  11. scene is just a frontend. As such, ray casting is generally a
  12. lower-level task. For simple raycasts, node such as
  13. :ref:`RayCast <class_RayCast>` and :ref:`RayCast2D <class_RayCast2D>`
  14. will work, as they will return every frame what the result of a raycast
  15. is.
  16. Many times, though, ray-casting needs to be a more interactive process
  17. so a way to do this by code must exist.
  18. Space
  19. -----
  20. In the physics world, Godot stores all the low level collision and
  21. physics information in a *space*. The current 2d space (for 2D Physics)
  22. can be obtained by accessing
  23. :ref:`CanvasItem.get_world_2d().space <class_CanvasItem_method_get_world_2d>`.
  24. For 3D, it's :ref:`Spatial.get_world().space <class_Spatial_method_get_world>`.
  25. The resulting space :ref:`RID <class_RID>` can be used in
  26. :ref:`PhysicsServer <class_PhysicsServer>` and
  27. :ref:`Physics2DServer <class_Physics2DServer>` respectively for 3D and 2D.
  28. Accessing space
  29. ---------------
  30. Godot physics runs by default in the same thread as game logic, but may
  31. be set to run on a separate thread to work more efficiently. Due to
  32. this, the only time accessing space is safe is during the
  33. :ref:`Node._physics_process() <class_Node_method__physics_process>`
  34. callback. Accessing it from outside this function may result in an error
  35. due to space being *locked*.
  36. To perform queries into physics space, the
  37. :ref:`Physics2DDirectSpaceState <class_Physics2DDirectSpaceState>`
  38. and :ref:`PhysicsDirectSpaceState <class_PhysicsDirectSpaceState>`
  39. must be used.
  40. Use the following code in 2D:
  41. .. tabs::
  42. .. code-tab:: gdscript GDscript
  43. func _physics_process(delta):
  44. var space_rid = get_world_2d().space
  45. var space_state = Physics2DServer.space_get_direct_state(space_rid)
  46. .. code-tab:: csharp
  47. public override void _PhysicsProcess(float delta)
  48. {
  49. var spaceRid = GetWorld2d().Space;
  50. var spaceState = Physics2DServer.SpaceGetDirectState(spaceRid);
  51. }
  52. Or more directly:
  53. .. tabs::
  54. .. code-tab:: gdscript GDScript
  55. func _physics_process(delta):
  56. var space_state = get_world_2d().direct_space_state
  57. .. code-tab:: csharp
  58. public override void _PhysicsProcess(float delta)
  59. {
  60. var spaceState = GetWorld2d().DirectSpaceState;
  61. }
  62. And in 3D:
  63. .. tabs::
  64. .. code-tab:: gdscript GDScript
  65. func _physics_process(delta):
  66. var space_state = get_world().direct_space_state
  67. .. code-tab:: csharp
  68. public override void _PhysicsProcess(float delta)
  69. {
  70. var spaceState = GetWorld().DirectSpaceState;
  71. }
  72. Raycast query
  73. -------------
  74. For performing a 2D raycast query, the method
  75. :ref:`Physics2DDirectSpaceState.intersect_ray() <class_Physics2DDirectSpaceState_method_intersect_ray>`
  76. may be used. For example:
  77. .. tabs::
  78. .. code-tab:: gdscript GDScript
  79. func _physics_process(delta):
  80. var space_state = get_world_2d().direct_space_state
  81. # use global coordinates, not local to node
  82. var result = space_state.intersect_ray(Vector2(0, 0), Vector2(50, 100))
  83. .. code-tab:: csharp
  84. public override void _PhysicsProcess(float delta)
  85. {
  86. var spaceState = GetWorld2d().DirectSpaceState;
  87. // use global coordinates, not local to node
  88. var result = spaceState.IntersectRay(new Vector2(), new Vector2(50, 100));
  89. }
  90. The result is a dictionary. If the ray didn't hit anything, the dictionary will
  91. be empty. If it did hit something, it will contain collision information:
  92. .. tabs::
  93. .. code-tab:: gdscript GDScript
  94. if result:
  95. print("Hit at point: ", result.position)
  96. .. code-tab:: csharp
  97. if (result.Count > 0)
  98. GD.Print("Hit at point: ", result["position"]);
  99. The ``result`` dictionary when a collision occurs contains the following
  100. data:
  101. ::
  102. {
  103. position: Vector2 # point in world space for collision
  104. normal: Vector2 # normal in world space for collision
  105. collider: Object # Object collided or null (if unassociated)
  106. collider_id: ObjectID # Object it collided against
  107. rid: RID # RID it collided against
  108. shape: int # shape index of collider
  109. metadata: Variant() # metadata of collider
  110. }
  111. The data is similar in 3D space, using Vector3 coordinates.
  112. Collision exceptions
  113. --------------------
  114. A common use case for ray casting is to enable a character to gather data
  115. about the world around it. One problem with this is that the same character
  116. has a collider, so the ray will only detect its parent's collider,
  117. as shown in the following image:
  118. .. image:: img/raycast_falsepositive.png
  119. To avoid self-intersection, the ``intersect_ray()`` function can take an
  120. optional third parameter which is an array of exceptions. This is an
  121. example of how to use it from a KinematicBody2D or any other
  122. collision object node:
  123. .. tabs::
  124. .. code-tab:: gdscript GDScript
  125. extends KinematicBody2D
  126. func _physics_process(delta):
  127. var space_state = get_world_2d().direct_space_state
  128. var result = space_state.intersect_ray(global_position, enemy_position, [self])
  129. .. code-tab:: csharp
  130. class Body : KinematicBody2D
  131. {
  132. public override void _PhysicsProcess(float delta)
  133. {
  134. var spaceState = GetWorld2d().DirectSpaceState;
  135. var result = spaceState.IntersectRay(globalPosition, enemyPosition, new Godot.Collections.Array { this });
  136. }
  137. }
  138. The exceptions array can contain objects or RIDs.
  139. Collision Mask
  140. --------------
  141. While the exceptions method works fine for excluding the parent body, it becomes
  142. very inconvenient if you need a large and/or dynamic list of exceptions. In
  143. this case, it is much more efficient to use the collision layer/mask system.
  144. The optional fourth argument for ``intersect_ray()`` is a collision mask. For
  145. example, to use the same mask as the parent body, use the ``collision_mask``
  146. member variable:
  147. .. tabs::
  148. .. code-tab:: gdscript GDScript
  149. extends KinematicBody2D
  150. func _physics_process(delta):
  151. var space_state = get_world().direct_space_state
  152. var result = space_state.intersect_ray(global_position, enemy_position,
  153. [self], collision_mask)
  154. .. code-tab:: csharp
  155. class Body : KinematicBody2D
  156. {
  157. public override void _PhysicsProcess(float delta)
  158. {
  159. var spaceState = GetWorld2d().DirectSpaceState;
  160. var result = spaceState.IntersectRay(globalPosition, enemyPosition,
  161. new Godot.Collections.Array { this }, CollisionMask);
  162. }
  163. }
  164. See :ref:`doc_physics_introduction_collision_layer_code_example` for details on how to set the collision mask.
  165. 3D ray casting from screen
  166. --------------------------
  167. Casting a ray from screen to 3D physics space is useful for object
  168. picking. There is not much need to do this because
  169. :ref:`CollisionObject <class_CollisionObject>`
  170. has an "input_event" signal that will let you know when it was clicked,
  171. but in case there is any desire to do it manually, here's how.
  172. To cast a ray from the screen, you need a :ref:`Camera <class_Camera>`
  173. node. A ``Camera`` can be in two projection modes: perspective and
  174. orthogonal. Because of this, both the ray origin and direction must be
  175. obtained. This is because ``origin`` changes in orthogonal mode, while
  176. ``normal`` changes in perspective mode:
  177. .. image:: img/raycast_projection.png
  178. To obtain it using a camera, the following code can be used:
  179. .. tabs::
  180. .. code-tab:: gdscript GDScript
  181. const ray_length = 1000
  182. func _input(event):
  183. if event is InputEventMouseButton and event.pressed and event.button_index == 1:
  184. var camera = $Camera
  185. var from = camera.project_ray_origin(event.position)
  186. var to = from + camera.project_ray_normal(event.position) * ray_length
  187. .. code-tab:: csharp
  188. private const float rayLength = 1000;
  189. public override void _Input(InputEvent @event)
  190. {
  191. if (@event is InputEventMouseButton eventMouseButton && eventMouseButton.Pressed && eventMouseButton.ButtonIndex == 1)
  192. {
  193. var camera = GetNode<Camera>("Camera");
  194. var from = camera.ProjectRayOrigin(eventMouseButton.Position);
  195. var to = from + camera.ProjectRayNormal(eventMouseButton.Position) * rayLength;
  196. }
  197. }
  198. Remember that during ``_input()``, the space may be locked, so in practice
  199. this query should be run in ``_physics_process()``.