physics_introduction.rst 19 KB

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