physics_introduction.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. .. _doc_physics_introduction:
  2. Physics introduction
  3. ====================
  4. Our world is made of tangible matter. In our world, a piano can't go
  5. through a wall when going into a house. It needs to use the door. Video
  6. games are often like the real world and Pac-Man can't go through the
  7. walls of his maze (although he can teleport from the left to the right
  8. side of the screen and back).
  9. Anyway, moving sprites around is nice but one day they have to collide
  10. properly, so let's get to the point.
  11. Shapes
  12. ------
  13. The base collidable object in Godot's 2D world is a
  14. :ref:`Shape2D <class_Shape2D>`.
  15. There are many types of shapes, all of them inherit this base class:
  16. - :ref:`CircleShape2D <class_CircleShape2D>`
  17. - :ref:`RectangleShape2D <class_RectangleShape2D>`
  18. - :ref:`CapsuleShape2D <class_CapsuleShape2D>`
  19. - :ref:`ConvexPolygonShape2D <class_ConvexPolygonShape2D>`
  20. - :ref:`ConcavePolygonShape2D <class_ConcavePolygonShape2D>`
  21. - etc. (there are others check the class list).
  22. Shapes are of type
  23. :ref:`Resource <class_Resource>`,
  24. but they can be created via code easily. For example:
  25. ::
  26. # Create a circle
  27. var c = CircleShape2D.new()
  28. c.set_radius(20)
  29. # Create a box
  30. var b = RectangleShape2D.new()
  31. b.set_extents(Vector2(20,10))
  32. The main use for shapes is checking collision/intersection and getting
  33. resolution information. Shapes are mostly convex, (except the
  34. concavepolygon one, which is just a list of segments to check collision
  35. against). This collision check is done easily with the built-in
  36. functions like:
  37. ::
  38. # Check if there is a collision between two shapes, each with a transform
  39. if b.collide(b_xform, a, a_xform):
  40. print("OMG Collision!")
  41. Godot will return correct collision and collision info from the
  42. different calls to the Shape2D api. Collision between all shapes and
  43. transforms can be done this way, or even obtaining contact information,
  44. motion casting, etc.
  45. Transforming shapes
  46. ~~~~~~~~~~~~~~~~~~~
  47. As seen before in the collide functions, 2D shapes in Godot can be
  48. transformed by using a regular :ref:`Matrix32 <class_Matrix32>`
  49. transform, meaning the functions can check for collisions while the
  50. shapes are scaled, moved and
  51. rotated. The only limitation to this is that shapes with curved sections
  52. (such as circle and capsule) can only be scaled uniformly. This means
  53. that circle or capsule shapes scaled in the form of an ellipse **will
  54. not work properly**. This is a limitation on the collision algorithm
  55. used (SAT), so make sure that your circle and capsule shapes are always
  56. scaled uniformly!
  57. .. image:: /img/shape_rules.png
  58. When problems begin
  59. -------------------
  60. Even though this sounds good, reality is that collision detection alone
  61. is usually not enough in most scenarios. Many problems start arising as
  62. long as the development of the game is in progress:
  63. Too many combinations!
  64. ~~~~~~~~~~~~~~~~~~~~~~
  65. Games have several dozens, hundreds, thousands! of objects that can
  66. collide and be collided. The typical approach is to test everything
  67. against everything in two for loops like this:
  68. ::
  69. for i in colliders:
  70. for j in colliders:
  71. if (i.collides(j)):
  72. do_collision_code()
  73. But this scales really badly. Let's imagine there are only 100 objects in
  74. the game. This means that 100\*100=10000 collisions will need to be
  75. tested each frame. This is a lot!
  76. Visual aid
  77. ~~~~~~~~~~
  78. Most of the time, creating a shape via code is not enough. We need to
  79. visually place it over a sprite, draw a collision polygon, etc. It is
  80. obvious that we need nodes to create the proper collision shapes in a
  81. scene.
  82. Collision resolution
  83. ~~~~~~~~~~~~~~~~~~~~
  84. Imagine we solved the collision issue, we can tell easily and quickly
  85. which shapes overlap. If many of them are dynamic objects that move
  86. around, or move according to newtonian physics, solving a collision of
  87. multiple objects can be really difficult code-wise.
  88. Introducing... Godot's physics engine!
  89. --------------------------------------
  90. To solve all these problems, Godot has a physics and collision engine
  91. that is well integrated into the scene system, yet it allows different
  92. levels and layers of functionality. The built-in physics engine can be
  93. used for:
  94. - Simple Collision Detection: See :ref:`Shape2D <class_Shape2D>`
  95. API.
  96. - Scene Kinematics: Handle shapes, collisions, broadphase, etc as
  97. nodes. See :ref:`Area2D <class_Area2D>`.
  98. - Scene Physics: Rigid bodies and constraints as nodes. See
  99. :ref:`RigidBody2D <class_RigidBody2D>`, and the joint nodes.
  100. Units of measure
  101. ~~~~~~~~~~~~~~~~
  102. It is often a problem when integrating a 2D physics engine to a game
  103. that such engines are optimized to work using meters as unit of measure.
  104. Godot uses a built-in custom 2D physics engine that is designed to
  105. function properly in pixels, so all units and default values used for
  106. stabilization are tuned for this, making development more
  107. straightforward.
  108. CollisionObject2D
  109. -----------------
  110. :ref:`CollisionObject2D <class_CollisionObject2D>`
  111. is the (virtual) base node for everything that can be collided in 2D.
  112. Area2D, StaticBody2D, KinematicBody2D and RigidBody2D all inherit from
  113. it. This node contains a list of shapes (Shape2D) and a relative
  114. transform. This means that all collisionable objects in Godot can use
  115. multiple shapes at different transforms (offset/scale/rotation). Just
  116. remember that, as mentioned before, **non-uniform scale will not work
  117. for circle and capsule shapes**.
  118. .. image:: /img/collision_inheritance.png
  119. A CollisionObject2D comes in different flavors: StaticBody2D, RigidBody2D,
  120. KinematicBody2D and Area2D. However, before we dig into them, let's have
  121. a look how to define the shape of a collision object.
  122. There are two special nodes for that.
  123. CollisionShape2D
  124. ~~~~~~~~~~~~~~~~
  125. This node is a helper node, which must be created as a direct child of a
  126. CollisionObject2D-derived node: :ref:`Area2D <class_Area2D>`,
  127. :ref:`StaticBody2D <class_StaticBody2D>`, :ref:`KinematicBody2D <class_KinematicBody2D>`,
  128. :ref:`RigidBody2D <class_RigidBody2D>`.
  129. The purpose of a CollisionShape2D instance is to add collision shapes to
  130. its parent class. Multiple children of type CollisionShape2D can be added to a
  131. CollisionObject2D-derived object with the effect that the parent will
  132. simply get more collision shapes. When a CollisionShape2D is edited (or added, moved,
  133. deleted) the list of shapes in the parent node is updated.
  134. At run time, though, this node does not exist and it can't be accessed with
  135. ``get_node()``. This is because it is a helper node only for editing the collision shapes.
  136. To access the shapes created at runtime, use the CollisionObject2D API directly.
  137. As an example, here's the scene from the platformer, containing an
  138. Area2D (named 'coin') having two children: a CollisionShape2D (named 'collision')
  139. and a sprite (called 'sprite'):
  140. .. image:: /img/area2dcoin.png
  141. CollisionPolygon2D
  142. ~~~~~~~~~~~~~~~~~~
  143. This one is similar to CollisionShape2D, except that instead of
  144. assigning a shape, a polygon can be edited (drawn by the user) to
  145. determine the shape. The polygon can be convex or concave, it doesn't
  146. matter.
  147. Here is another scene involving a CollisionPolygon2D: A StaticBody2D has
  148. been added as a child of a sprite so that the collision object moves together
  149. with the sprite. In turn, the CollisionPolygon is a child of StaticBody2D, meaning it
  150. adds collision shapes to it.
  151. .. image:: /img/spritewithcollision.png
  152. The CollisionPolygon2D will decompose the user-defined polygon into conves shapes
  153. convex shapes (shapes can only be convex, remember?) before adding them to
  154. the CollisionObject2D. The following image shows such a decomposition:
  155. .. image:: /img/decomposed.png
  156. Triggers
  157. ~~~~~~~~
  158. A CollisionShape2D or CollisionPolygon2D can be set as a trigger by setting
  159. the boolean flag with the same name. When
  160. used in a RigidBody2D or KinematicBody2D, "trigger" shapes take part
  161. in collision detection but are unaffected by physics (they don't block
  162. movement etc).
  163. Defining a collision shape as a trigger is mostly useful in two situations:
  164. - Collisions for a specific shape shall be disabled.
  165. - An Area2D shall send ``body_enter`` and ``body_exit`` signals when the
  166. trigger shape enters it (useful in several situations).
  167. StaticBody2D
  168. ~~~~~~~~~~~~
  169. The simplest node in the physics engine is the :ref:`StaticBody2D <class_StaticBody2D>`.
  170. This node takes part in collision detection. However, it does not move or rotate
  171. after a collision, so physics do not influence them. The node is static.
  172. Other nodes can collide against it and will be influenced accordingly.
  173. The platformer example uses StaticBody2D objects for the floors and walls.
  174. These are the static parts of a level and shall stay right where they
  175. are even if the player jumps onto them.
  176. KinematicBody2D
  177. ~~~~~~~~~~~~~~~
  178. Similar to StaticBody2D, objects of type :ref:`KinematicBody2D <class_KinematicBody2D>`
  179. are not affected by physics (although they take part in collision detection, of course).
  180. However, KinematicBody2D are not static but can be moved via code or an animation.
  181. They have two main uses:
  182. - **Simulated Motion**: When these bodies are moved manually, either
  183. from code or from an :ref:`AnimationPlayer <class_AnimationPlayer>`
  184. (with process mode set to fixed!), the physics will automatically
  185. compute an estimate of their linear and angular velocity. This makes
  186. them very useful for moving platforms or other
  187. AnimationPlayer-controlled objects (like a door, a bridge that opens,
  188. etc). As an example, the 2d/platformer demo uses them for moving
  189. platforms.
  190. - **Kinematic Characters**: KinematicBody2D also has an API for moving
  191. objects (the ``move()`` function) while performing collision tests. This
  192. makes them really useful to implement characters that collide against
  193. a world, but that don't require advanced physics. There is a tutorial
  194. about it :ref:`doc_kinematic_character_2d`.
  195. RigidBody2D
  196. ~~~~~~~~~~~
  197. This type of body simulates Newtonian physics. It has mass, friction,
  198. bounce, and the (0,0) coordinates simulate the center of mass. When real
  199. physics are needed, :ref:`RigidBody2D <class_RigidBody2D>`
  200. is the node to use. The motion of this body is affected by gravity
  201. and/or other bodies.
  202. Rigid bodies are usually active all the time, but when they end up in
  203. resting position and don't move for a while, they are put to sleep until
  204. something else wakes them up. This saves an enormous amount of CPU.
  205. RigidBody2D nodes update their transform constantly, as it is generated
  206. by the simulation from a position, linear velocity and angular velocity.
  207. As a result, [STRIKEOUT:this node can't be scaled]. Scaling the children
  208. nodes should work fine though.
  209. A RigidBody2D has a ``Mode`` flag to change its behavior (something
  210. which is very common in games). It can behave like a rigid body,
  211. a character (a rigid body without the ability to rotate so that it is
  212. always upright), a kinematic body or a static body. This flag can be
  213. changed dynamically according to the current situation. For example,
  214. an enemy frozen by an ice beam becomes a static body.
  215. The best way to interact with a RigidBody2D is during the force
  216. integration callback by overriding the function
  217. ::
  218. func _integrate_forces(state):
  219. [use state to change the object]
  220. The "state" parameter is of type :ref:`Physics2DDirectBodyState <class_Physics2DDirectBodyState>`.
  221. Please do not use the state object outside the callback as it will
  222. result in an error.
  223. During the evaluation of the aforementioned function, the physics engine
  224. synchronizes state with the scene and allows full modification of the
  225. object's parameters. Since physics may run in its own thread, parameter
  226. changes outside that callback will not take place until the next frame.
  227. Contact reporting
  228. -----------------
  229. In general, RigidBody2D will not keep track of the contacts, because
  230. this can require a huge amount of memory if thousands of rigid bodies
  231. are in the scene. To get contacts reported, simply increase the amount
  232. of the "contacts reported" property from zero to a meaningful value
  233. (depending on how many you are expecting to get). The contacts can be
  234. later obtained via the
  235. :ref:`Physics2DDirectBodyState.get_contact_count() <class_Physics2DDirectBodyState_get_contact_count>`
  236. and related functions.
  237. Contact monitoring via signals is also available (signals similar to the
  238. ones in Area2D, described below) via a boolean property.
  239. Area2D
  240. ~~~~~~
  241. Areas in Godot physics have three main roles:
  242. 1. Override the space parameters for objects entering them (ie.
  243. gravity, gravity direction, gravity type, density, etc).
  244. 2. Monitor when rigid or kinematic bodies enter or exit the area.
  245. 3. Monitor other areas (this is the simplest way to get overlap test)
  246. The second function is the most common. For it to work, the "monitoring"
  247. property must be enabled (it is by default). There are two types of
  248. signals emitted by this node:
  249. ::
  250. # Simple, high level notification
  251. body_enter(body:PhysicsBody2D)
  252. body_exit(body:PhysicsBody2D)
  253. area_enter(area:Area2D)
  254. area_exit(body:Area2D)
  255. # Low level shape-based notification
  256. # Notifies which shape specifically in both the body and area are in contact
  257. body_enter_shape(body_id:int,body:PhysicsBody2D,body_shape_index:int,area_shape_index:idx)
  258. body_exit_shape(body_id:int,body:PhysicsBody2D,body_shape_index:int,area_shape_index:idx)
  259. area_enter_shape(area_id:int,area:Area2D,area_shape_index:int,self_shape_index:idx)
  260. area_exit_shape(area_id:int,area:Area2D,area_shape_index:int,self_shape_index:idx)
  261. By default, areas also receive mouse/touchscreen input, providing a
  262. lower-level way than controls to implement this kind of input in a game.
  263. Bodies support this but it's disabled by default.
  264. In case of overlap, who receives collision information?
  265. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  266. Remember that not every combination of two bodies can "report" contacts.
  267. Static bodies are passive and will not report contacts when hit.
  268. Kinematic Bodies will report contacts but only against Rigid/Character
  269. bodies. Area2D will report overlap (not detailed contacts) with bodies
  270. and with other areas. The following table should make it more visual:
  271. +-------------------+-------------+-----------------+-----------------+---------------+--------+
  272. | **Type** | *RigidBody* | *CharacterBody* | *KinematicBody* | *StaticBody* | *Area* |
  273. +===================+=============+=================+=================+===============+========+
  274. | **RigidBody** | Both | Both | Both | Rigidbody | Area |
  275. +-------------------+-------------+-----------------+-----------------+---------------+--------+
  276. | **CharacterBody** | Both | Both | Both | CharacterBody | Area |
  277. +-------------------+-------------+-----------------+-----------------+---------------+--------+
  278. | **KinematicBody** | Both | Both | None | None | Area |
  279. +-------------------+-------------+-----------------+-----------------+---------------+--------+
  280. | **StaticBody** | RigidBody | CharacterBody | None | None | None |
  281. +-------------------+-------------+-----------------+-----------------+---------------+--------+
  282. | **Area** | Area | Area | Area | None | Both |
  283. +-------------------+-------------+-----------------+-----------------+---------------+--------+
  284. Physics global variables
  285. ------------------------
  286. A few global variables can be tweaked in the project settings for
  287. adjusting how 2D physics works:
  288. .. image:: /img/physics2d_options.png
  289. Leaving them alone is best (except for the gravity, that needs to be
  290. adjusted in most games), but there is one specific parameter that might
  291. need tweaking which is the "cell_size". Godot 2D physics engine used by
  292. default a space hashing algorithm that divides space in cells to compute
  293. close collision pairs more efficiently.
  294. If a game uses several colliders that are really small and occupy a
  295. small portion of the screen, it might be necessary to shrink that value
  296. (always to a power of 2) to improve efficiency. Likewise if a game uses
  297. few large colliders that span a huge map (of several screens of size),
  298. increasing that value a bit might help save resources.
  299. Fixed process callback
  300. ----------------------
  301. The physics engine may spawn multiple threads to improve performance, so
  302. it can use up to a full frame to process physics. Because of this, when
  303. accessing physics variables such as position, linear velocity, etc. they
  304. might not be representative of what is going on in the current frame.
  305. To solve this, Godot has a fixed process callback, which is like process
  306. but it's called once per physics frame (by default 60 times per second).
  307. During this time, the physics engine is in *synchronization* state and
  308. can be accessed directly and without delays.
  309. To enable a fixed process callback, use the ``set_fixed_process()``
  310. function, example:
  311. ::
  312. extends KinematicBody2D
  313. func _fixed_process(delta):
  314. move(direction * delta)
  315. func _ready():
  316. set_fixed_process(true)
  317. Casting rays and motion queries
  318. -------------------------------
  319. It is very often desired to "explore" the world around from our code.
  320. Throwing rays is the most common way to do it. The simplest way to do
  321. this is by using the RayCast2D node, which will throw a ray every frame
  322. and record the intersection.
  323. At the moment there isn't a high level API for this, so the physics
  324. server must be used directly. For this, the
  325. :ref:`Physics2DDirectspaceState <class_Physics2DDirectspaceState>`
  326. class must be used. To obtain it, the following steps must be taken:
  327. 1. It must be used inside the ``_fixed_process()`` callback, or at
  328. ``_integrate_forces()``
  329. 2. The 2D RIDs for the space and physics server must be obtained.
  330. The following code should work:
  331. ::
  332. func _fixed_process(delta):
  333. var space = get_world_2d().get_space()
  334. var space_state = Physics2DServer.space_get_direct_state(space)
  335. Enjoy doing space queries!