physics_introduction.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. .. _doc_physics_introduction:
  2. Physics introduction
  3. ====================
  4. In game development, you often need to know when two objects in the game
  5. intersect or come into contact. This is known as **collision detection**.
  6. When a collision is detected, you typically want something to happen. This
  7. is known as **collision response**.
  8. Godot offers a number of collision objects in 2D and 3D to provide both collision detection
  9. and response. Trying to decide which one to use for your project can be confusing.
  10. You can avoid problems and simplify development if you understand how each works
  11. and what their pros and cons are.
  12. In this guide, you will learn:
  13. - Godot's four collision object types
  14. - How each collision object works
  15. - When and why to choose one type over another
  16. .. note:: This document's examples will use 2D objects. Every 2D physics object
  17. and collision shape has a direct equivalent in 3D and in most cases
  18. they work in much the same way.
  19. Collision objects
  20. -----------------
  21. Godot offers four kinds of physics bodies, extending :ref:`CollisionObject2D <class_CollisionObject2D>`:
  22. - :ref:`Area2D <class_Area2D>`
  23. ``Area2D`` nodes provide **detection** and **influence**. They can detect when
  24. objects overlap and can emit signals when bodies enter or exit. An ``Area2D``
  25. can also be used to override physics properties, such as gravity or damping,
  26. in a defined area.
  27. The other three bodies extend :ref:`PhysicsBody2D <class_PhysicsBody2D>`:
  28. - :ref:`StaticBody2D <class_StaticBody2D>`
  29. A static body is one that is not moved by the physics engine. It participates
  30. in collision detection, but does not move in response to the collision. They
  31. are most often used for objects that are part of the environment or that do
  32. not need to have any dynamic behavior.
  33. - :ref:`RigidBody2D <class_RigidBody2D>`
  34. This is the node that implements simulated 2D physics. You do not control a
  35. ``RigidBody2D`` directly, but instead you apply forces to it (gravity, impulses,
  36. etc.) and the physics engine calculates the resulting movement. :ref:`Read more about using rigid bodies. <doc_rigid_body>`
  37. - :ref:`KinematicBody2D <class_KinematicBody2D>`
  38. A body that provides collision detection, but no physics. All movement and
  39. collision response must be implemented in code.
  40. Collision shapes
  41. ~~~~~~~~~~~~~~~~
  42. A physics body can hold any number of :ref:`Shape2D <class_Shape2D>` objects
  43. as children. These shapes are used to define the object's collision bounds
  44. and to detect contact with other objects.
  45. .. note:: In order to detect collisions, at least one ``Shape2D`` must be
  46. assigned to the object.
  47. The most common way to assign a shape is by adding a :ref:`CollisionShape2D <class_CollisionShape2D>`
  48. or :ref:`CollisionPolygon2D <class_CollisionPolygon2D>` as a child of the object.
  49. These nodes allow you to draw the shape directly in the editor workspace.
  50. .. important:: Be careful to never scale your collision shapes in the editor.
  51. The "Scale" property in the Inspector should remain ``(1, 1)``. When changing
  52. the size of the collision shape, you should always use the size handles, **not**
  53. the ``Node2D`` scale handles. Scaling a shape can result in unexpected
  54. collision behavior.
  55. .. image:: img/player_coll_shape.png
  56. Physics process callback
  57. ~~~~~~~~~~~~~~~~~~~~~~~~
  58. The physics engine may spawn multiple threads to improve performance, so
  59. it can use up to a full frame to process physics. Because of this, the value
  60. of a body's state variables such as ``position`` or ``linear velocity``
  61. may not be accurate for the current frame.
  62. In order to avoid this inaccuracy, any code that needs to access a body's properties should
  63. be run in the :ref:`Node._physics_process() <class_Node_method__physics_process>`
  64. callback, which is called before each physics step at a constant frame rate
  65. (60 times per second by default).
  66. Collision layers and masks
  67. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  68. One of the most powerful, but frequently misunderstood, collision features
  69. is the collision layer system. This system allows you to build up complex
  70. interactions between a variety of objects. The key concepts are **layers**
  71. and **masks**. Each ``CollisionObject2D`` has 20 different physics layers
  72. it can interact with.
  73. Let's look at each of the properties in turn:
  74. - collision_layer
  75. This describes the layers that the object appears **in**. By default, all
  76. bodies are on layer ``1``.
  77. - collision_mask
  78. This describes what layers the body will **scan** for collisions. If an
  79. object isn't in one of the mask layers, the body will ignore it. By default,
  80. all bodies scan layer ``1``.
  81. These properties can be configured via code, or by editing them in the Inspector.
  82. Keeping track of what you're using each layer for can be difficult, so you
  83. may find it useful to assign names to the layers you're using. Names can
  84. be assigned in Project Settings -> Layer Names.
  85. .. image:: img/physics_layer_names.png
  86. **Example:**
  87. You have four node types in your game: Walls, Player, Enemy, and Coin. Both
  88. Player and Enemy should collide with Walls. The Player node should detect
  89. collisions with both Enemy and Coin, but Enemy and Coin should ignore each
  90. other.
  91. Start by naming layers 1-4 "walls", "player", "enemies", and "coins" and
  92. place each node type in its respective layer using the "Layer" property.
  93. Then set each node's "Mask" property by selecting the layers it should
  94. interact with. For example, the Player's settings would look like this:
  95. .. image:: img/player_collision_layers.png
  96. .. image:: img/player_collision_mask.png
  97. Area2D
  98. ------
  99. Area nodes provide **detection** and **influence**. They can detect when
  100. objects overlap and emit signals when bodies enter or exit. Areas can also
  101. be used to override physics properties, such as gravity or damping, in a
  102. defined area.
  103. There are three main uses for :ref:`Area2D <class_Area2D>`:
  104. - Overriding physics parameters (such as gravity) in a given region.
  105. - Detecting when other bodies enter or exit a region or what bodies are currently in a region.
  106. - Checking other areas for overlap.
  107. By default, areas also receive mouse and touchscreen input.
  108. StaticBody2D
  109. ------------
  110. A static body is one that is not moved by the physics engine. It participates
  111. in collision detection, but does not move in response to the collision. However,
  112. it can impart motion or rotation to a colliding body **as if** it were moving,
  113. using its ``constant_linear_velocity`` and ``constant_angular_velocity`` properties.
  114. ``StaticBody2D`` nodes are most often used for objects that are part of the environment
  115. or that do not need to have any dynamic behavior.
  116. Example uses for ``StaticBody2D``:
  117. - Platforms (including moving platforms)
  118. - Conveyor belts
  119. - Walls and other obstacles
  120. RigidBody2D
  121. -----------
  122. This is the node that implements simulated 2D physics. You do not control a
  123. :ref:`RigidBody2D <class_RigidBody2D>` directly. Instead, you apply forces
  124. to it and the physics engine calculates the resulting movement, including
  125. collisions with other bodies, and collision responses, such as bouncing,
  126. rotating, etc.
  127. You can modify a rigid body's behavior via properties such as "Mass",
  128. "Friction", or "Bounce", which can be set in the Inspector.
  129. The body's behavior is also affected by the world's properties, as set in
  130. `Project Settings -> Physics`, or by entering an :ref:`Area2D <class_Area2D>`
  131. that is overriding the global physics properties.
  132. When a rigid body is at rest and hasn't moved for a while, it goes to sleep.
  133. A sleeping body acts like a static body, and its forces are not calculated by
  134. the physics engine. The body will wake up when forces are applied, either by
  135. a collision or via code.
  136. Rigid body modes
  137. ~~~~~~~~~~~~~~~~
  138. A rigid body can be set to one of four modes:
  139. - **Rigid** - The body behaves as a physical object. It collides with other bodies and responds to forces applied to it. This is the default mode.
  140. - **Static** - The body behaves like a :ref:`StaticBody2D <class_StaticBody2D>` and does not move.
  141. - **Character** - Similar to "Rigid" mode, but the body cannot rotate.
  142. - **Kinematic** - The body behaves like a :ref:`KinematicBody2D <class_KinematicBody2D>` and must be moved by code.
  143. Using RigidBody2D
  144. ~~~~~~~~~~~~~~~~~
  145. One of the benefits of using a rigid body is that a lot of behavior can be had
  146. "for free" without writing any code. For example, if you were making an
  147. "Angry Birds"-style game with falling blocks, you would only need to create
  148. RigidBody2Ds and adjust their properties. Stacking, falling, and bouncing would
  149. automatically be calculated by the physics engine.
  150. However, if you do wish to have some control over the body, you should take
  151. care - altering the ``position``, ``linear_velocity``, or other physics properties
  152. of a rigid body can result in unexpected behavior. If you need to alter any
  153. of the physics-related properties, you should use the :ref:`_integrate_forces() <class_RigidBody2D_method__integrate_forces>`
  154. callback instead of ``_physics_process()``. In this callback, you have access
  155. to the body's :ref:`Physics2DDirectBodyState <class_Physics2DDirectBodyState>`,
  156. which allows for safely changing properties and synchronizing them with
  157. the physics engine.
  158. For example, here is the code for an "Asteroids" style spaceship:
  159. .. tabs::
  160. .. code-tab:: gdscript GDScript
  161. extends RigidBody2D
  162. var thrust = Vector2(0, 250)
  163. var torque = 20000
  164. func _integrate_forces(state):
  165. if Input.is_action_pressed("ui_up"):
  166. applied_force = thrust.rotated(rotation)
  167. else:
  168. applied_force = Vector2()
  169. var rotation_dir = 0
  170. if Input.is_action_pressed("ui_right"):
  171. rotation_dir += 1
  172. if Input.is_action_pressed("ui_left"):
  173. rotation_dir -= 1
  174. applied_torque = rotation_dir * torque
  175. .. code-tab:: csharp
  176. class Spaceship : RigidBody2D
  177. {
  178. private Vector2 thrust = new Vector2(0, 250);
  179. private float torque = 20000;
  180. public override void _IntegrateForces(Physics2DDirectBodyState state)
  181. {
  182. if (Input.IsActionPressed("ui_up"))
  183. SetAppliedForce(thrust.Rotated(Rotation));
  184. else
  185. SetAppliedForce(new Vector2());
  186. var rotationDir = 0;
  187. if (Input.IsActionPressed("ui_right"))
  188. rotationDir += 1;
  189. if (Input.IsActionPressed("ui_left"))
  190. rotationDir -= 1;
  191. SetAppliedTorque(rotationDir * torque);
  192. }
  193. }
  194. Note that we are not setting the ``linear_velocity`` or ``angular_velocity``
  195. properties directly, but rather applying forces (``thrust`` and ``torque``) to
  196. the body and letting the physics engine calculate the resulting movement.
  197. .. note:: When a rigid body goes to sleep, the ``_integrate_forces()``
  198. function will not be called. To override this behavior, you will
  199. need to keep the body awake by creating a collision, applying a
  200. force to it, or by disabling the :ref:`can_sleep <class_RigidBody2D_property_can_sleep>`
  201. property. Be aware that this can have a negative effect on performance.
  202. Contact reporting
  203. ~~~~~~~~~~~~~~~~~
  204. By default, rigid bodies do not keep track of contacts, because this can
  205. require a huge amount of memory if many bodies are in the scene. To enable
  206. contact reporting, set the :ref:`contacts_reported <class_RigidBody2D_property_contacts_reported>`
  207. property to a non-zero value. The contacts can then be obtained via
  208. :ref:`Physics2DDirectBodyState.get_contact_count() <class_Physics2DDirectBodyState_method_get_contact_count>`
  209. and related functions.
  210. Contact monitoring via signals can be enabled via the :ref:`contact_monitor <class_RigidBody2D_property_contact_monitor>`
  211. property. See :ref:`RigidBody2D <class_RigidBody2D>` for the list of available
  212. signals.
  213. KinematicBody2D
  214. ---------------
  215. :ref:`KinematicBody2D <class_KinematicBody2D>` bodies detect collisions with
  216. other bodies, but are not affected by physics properties like gravity or friction.
  217. Instead, they must be controlled by the user via code. The physics engine will
  218. not move a kinematic body.
  219. When moving a kinematic body, you should not set its ``position`` directly.
  220. Instead, you use the ``move_and_collide()`` or ``move_and_slide()`` methods.
  221. These methods move the body along a given vector, and it will instantly stop
  222. if a collision is detected with another body. After the body has collided,
  223. any collision response must be coded manually.
  224. Kinematic collision response
  225. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  226. After a collision, you may want the body to bounce, to slide along a wall,
  227. or to alter the properties of the object it hit. The way you handle collision
  228. response depends on which method you used to move the KinematicBody2D.
  229. :ref:`move_and_collide <class_KinematicBody2D_method_move_and_collide>`
  230. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  231. When using ``move_and_collide()``, the function returns a
  232. :ref:`KinematicCollision2D <class_KinematicCollision2D>` object, which contains
  233. information about the collision and the colliding body. You can use this
  234. information to determine the response.
  235. For example, if you want to find the point in space where the collision
  236. occurred:
  237. .. tabs::
  238. .. code-tab:: gdscript GDScript
  239. extends KinematicBody2D
  240. var velocity = Vector2(250, 250)
  241. func _physics_process(delta):
  242. var collision_info = move_and_collide(velocity * delta)
  243. if collision_info:
  244. var collision_point = collision_info.position
  245. .. code-tab:: csharp
  246. class Body : KinematicBody2D
  247. {
  248. private Vector2 velocity = new Vector2(250, 250);
  249. public override void _PhysicsProcess(float delta)
  250. {
  251. var collisionInfo = MoveAndCollide(velocity * delta);
  252. if (collisionInfo != null)
  253. {
  254. var collisionPoint = collisionInfo.GetPosition();
  255. }
  256. }
  257. }
  258. Or to bounce off of the colliding object:
  259. .. tabs::
  260. .. code-tab:: gdscript GDScript
  261. extends KinematicBody2D
  262. var velocity = Vector2(250, 250)
  263. func _physics_process(delta):
  264. var collision_info = move_and_collide(velocity * delta)
  265. if collision_info:
  266. velocity = velocity.bounce(collision_info.normal)
  267. .. code-tab:: csharp
  268. class Body : KinematicBody2D
  269. {
  270. private Vector2 velocity = new Vector2(250, 250);
  271. public override void _PhysicsProcess(float delta)
  272. {
  273. var collisionInfo = MoveAndCollide(velocity * delta);
  274. if (collisionInfo != null)
  275. velocity = velocity.Bounce(collisionInfo.Normal);
  276. }
  277. }
  278. :ref:`move_and_slide <class_KinematicBody2D_method_move_and_slide>`
  279. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  280. Sliding is a common collision response; imagine a player moving along walls
  281. in a top-down game or running up and down slopes in a platformer. While it's
  282. possible to code this response yourself after using ``move_and_collide()``,
  283. ``move_and_slide()`` provides a convenient way to implement sliding movement
  284. without writing much code.
  285. .. warning:: ``move_and_slide()`` automatically includes the timestep in its
  286. calculation, so you should **not** multiply the velocity vector
  287. by ``delta``.
  288. For example, use the following code to make a character that can walk along
  289. the ground (including slopes) and jump when standing on the ground:
  290. .. tabs::
  291. .. code-tab:: gdscript GDScript
  292. extends KinematicBody2D
  293. var run_speed = 350
  294. var jump_speed = -1000
  295. var gravity = 2500
  296. var velocity = Vector2()
  297. func get_input():
  298. velocity.x = 0
  299. var right = Input.is_action_pressed('ui_right')
  300. var left = Input.is_action_pressed('ui_left')
  301. var jump = Input.is_action_just_pressed('ui_select')
  302. if is_on_floor() and jump:
  303. velocity.y = jump_speed
  304. if right:
  305. velocity.x += run_speed
  306. if left:
  307. velocity.x -= run_speed
  308. func _physics_process(delta):
  309. velocity.y += gravity * delta
  310. get_input()
  311. velocity = move_and_slide(velocity, Vector2(0, -1))
  312. .. code-tab:: csharp
  313. class Body : KinematicBody2D
  314. {
  315. private float runSpeed = 350;
  316. private float jumpSpeed = -1000;
  317. private float gravity = 2500;
  318. private Vector2 velocity = new Vector2();
  319. private void getInput()
  320. {
  321. velocity.x = 0;
  322. var right = Input.IsActionPressed("ui_right");
  323. var left = Input.IsActionPressed("ui_left");
  324. var jump = Input.IsActionPressed("ui_select");
  325. if (IsOnFloor() && jump)
  326. velocity.y = jumpSpeed;
  327. if (right)
  328. velocity.x += runSpeed;
  329. if (left)
  330. velocity.x -= runSpeed;
  331. }
  332. public override void _PhysicsProcess(float delta)
  333. {
  334. velocity.y += gravity * delta;
  335. }
  336. }
  337. See :ref:`doc_kinematic_character_2d` for more details on using ``move_and_slide()``,
  338. including a demo project with detailed code.