physics_introduction.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 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
  49. :ref:`Matrix32 <class_Matrix32>`
  50. transform, meaning the can check collision while 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. But 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 bad. 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
  95. :ref:`Shape2D <class_Shape2D>`
  96. API.
  97. - Scene Kinematics: Handle shapes, collisions, broadphase, etc as
  98. nodes. See
  99. :ref:`Area2D <class_Area2D>`.
  100. - Scene Physics: Rigid bodies and constraints as nodes. See
  101. :ref:`RigidBody2D <class_RigidBody2D>`,
  102. and the joint nodes.
  103. Units of Measure
  104. ~~~~~~~~~~~~~~~~
  105. It is often a problem when integrating a 2D Physics engine to a game
  106. that such engines are optimized to work using meters as unit of measure.
  107. Godot uses a built-in custom 2D physics engine that is designed to
  108. function properly in pixels, so all units and default values used for
  109. stabilization are tuned for this, making development more
  110. straightforward.
  111. CollisionObject2D
  112. -----------------
  113. :ref:`CollisionObject2D <class_CollisionObject2D>`
  114. is the (virtual) base node for everything that can be collided in 2D.
  115. Area2D, StaticBody2D, KinematicBody2D and RigidBody2D all inherit from
  116. it. This node contains a list of shapes (Shape2D) and a relative
  117. transform. This means that all collisionable objects in Godot can use
  118. multiple shapes at different transforms (offset/scale/rotation). Just
  119. remember that, as mentioned before, **non-uniform scale will not work
  120. for circle and capsule shapes**.
  121. .. image:: /img/collision_inheritance.png
  122. StaticBody2D
  123. ~~~~~~~~~~~~
  124. The simplest node in the physics engine is the StaticBody2D, which
  125. provides a static collision. This means that other objects can collide
  126. against it, but StaticBody2D will not move by itself or generate any
  127. kind of interaction when colliding other bodies. It's just there to be
  128. collided.
  129. Creating one of those bodies is not enough, because it lacks collision:
  130. .. image:: /img/collision_inheritance.png
  131. From the previous point, we know that CollisionObject2D derived nodes
  132. have an internal lists of shapes and transforms for collisions, but how
  133. to edit them? There are two special nodes for that.
  134. CollisionShape2D
  135. ~~~~~~~~~~~~~~~~
  136. This node is a helper node. It must be created as a direct children of a
  137. CollisionObject2D derived node
  138. :ref:`Area2D <class_Area2D>`.
  139. By itself it does nothing, but when created as a child of the above
  140. mentioned nodes, it adds collision shapes to them. Any amount of
  141. CollisionShape2D children can be created, meaning the parent object will
  142. simply have mroe collision shapes. When added/deleted/moved/edited, it
  143. updates the list of shapes in the parent node.
  144. At run time, though, this node does not exist (can't be accessed with
  145. get\_node() ), since it's only meant to be an editor helper. To access
  146. the shapes created at runtime, use the CollisionObject2D API directly.
  147. As an example, here's the scene from the platformer, containing an
  148. Area2D with child CollisionObject2D and coin sprite:
  149. .. image:: /img/area2dcoin.png
  150. Triggers
  151. ~~~~~~~~
  152. A CollisionShape2D or CollisionPolygon2D can be set as a trigger. When
  153. used in a RigidBody2D or KinematicBody2D, "trigger" shapes become
  154. non-collidable (objects can't collide against it). They just move around
  155. with the object as ghosts. This makes them useful in two situations:
  156. - Disabling collision in a specific shape.
  157. - Get an Area2D to trigger a body\_enter / body\_exit signals with non
  158. collidable objects (useful in several situations).
  159. CollisionPolygon2D
  160. ~~~~~~~~~~~~~~~~~~
  161. This one is similar to CollisionShape2D, except that instead of
  162. assigning a shape, a polygon can be edited (drawn by the user) to
  163. determine the shape. The polygon can be convex or concave, it doesn't
  164. matter.
  165. Going back, here's the scene with the StaticBody2D, the static body is
  166. the child of a sprite (meaning if the sprite moves, the collision does
  167. too). In turn, the CollisionPolygon is a child of staticbody, meaning it
  168. adds collision shapes to it.
  169. .. image:: /img/spritewithcollision.png
  170. In fact, what CollisionPolygon does is to decompose the polygon in
  171. convex shapes (shapes can only be convex, remember?) and adds them to
  172. the CollisionObject2D:
  173. .. image:: /img/decomposed.png
  174. KinematicBody2D
  175. ~~~~~~~~~~~~~~~
  176. :ref:`Kinematic <class_Kinematic>`
  177. bodies are special types of bodies that are meant to be user-controlled.
  178. They are not affected by the physics at all (to other types of bodies,
  179. such a character or a rigidbody, these are the same as a staticbody).
  180. They have however, two main uses:
  181. - **Simulated Motion**: When these bodies are moved manually, either
  182. from code or from an
  183. :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. A special
  194. :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 simulates the center of mass. When real
  199. physics are needed,
  200. :ref:`RigidBody2D <class_RigidBody2D>`
  201. is the node to use. The motion of this body is affected by gravity
  202. and/or other bodies.
  203. Rigid bodies are usually active all the time, but when they end up in
  204. resting position and don't move for a while, they are put to sleep until
  205. something else wakes them up. This saves an enormous amount of CPU.
  206. RigidBody2D nodes update their transform constantly, as it is generated
  207. by the simulation from a position, linear velocity and angular velocity.
  208. As a result, [STRIKEOUT:this node can't be scaled]. Scaling the children
  209. nodes should work fine though.
  210. As a plus, as this is very common in games, it is possible to change a
  211. RigidBody2D node to behave like a Character (no rotation), StaticBody or
  212. KinematicBody according to different situations (example, an enemy
  213. frozen by an ice beam becomes a StaticBody)
  214. The best way to interact with a RigidBody2D is during the force
  215. integration callback. In this very moment, the physics engine
  216. synchronizes state with the scene and allows full modification of the
  217. internal parameters (otherwise, as it may be running in a thread,
  218. changes will not take place until next frame). To do this, the following
  219. function must be overridden:
  220. ::
  221. func _integrate_forces(state):
  222. [use state to change the object]
  223. The \`state\` parameter is of type
  224. :ref:`Physics2DDirectBodyState <class_Physics2DDirectBodyState>`.
  225. Please do not use this object (state) outside the callback as it will
  226. result in an error.
  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. Areas also by default receive mouse/touchscreen input, providing a lower-level way than controls to implement this kind of input in a game. Bodies support this by it's disabled by default.
  262. Physics Global Variables
  263. ------------------------
  264. A few global variables can be tweaked in the project settings for
  265. adjusting how 2D physics works:
  266. .. image:: /img/physics2d_options.png
  267. Leaving them alone is best (except for the gravity, that needs to be
  268. adjusted in most games), but there is one specific parameter that might
  269. need tweaking which is the "cell\_size". Godot 2D physics engine used by
  270. default a space hashing algorithm that divides space in cells to compute
  271. close collision pairs more efficiently.
  272. If a game uses several colliders that are really small and occupy a
  273. small portion of the screen, it might be necessary to shrink that value
  274. (always to a power of 2) to improve efficiency. Likewise if a game uses
  275. few large colliders that span a huge map (of several screens of size),
  276. increasing that value a bit might help save resources.
  277. Fixed Process Callback
  278. ----------------------
  279. The physics engine may spawn multiple threads to improve performance, so
  280. it can use up to a full frame to process physics. Because of this, when
  281. accessing physics variables such as position, linear velocity, etc. they
  282. might not be representative of what is going on in the current frame.
  283. To solve this, Godot has a fixed process callback, which is like process
  284. but it's called once per physics frame (by default 60 times per second).
  285. During this time, the physics engine is in *synchronization* state and
  286. can be accessed directly and without delays.
  287. To enable a fixed process callback, use the set\_fixed\_process()
  288. function, example:
  289. ::
  290. extends KinematicBody2D
  291. func _fixed_process(delta):
  292. move( direction * delta )
  293. func _ready():
  294. set_fixed_process(true)
  295. Casting Rays and Motion Queries
  296. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  297. It is very often desired to "explore" the world around from our code.
  298. Throwing rays is the most common way to do it. The simplest way to do
  299. this is by using the RayCast2D node, which will throw a ray every frame
  300. and record the intersection.
  301. At the moment there isn't a high level API for this, so the physics
  302. server must be used directly. For this, the
  303. :ref:`Physics2DDirectspaceState <class_Physics2DDirectspaceState>`
  304. class must be used. To obtain it, the following steps must be taken:
  305. 1. It must be used inside the \_fixed\_process() callback, or at
  306. \_integrate\_forces()
  307. 2. The 2D RIDs for the space and physics server must be obtained.
  308. The following code should work:
  309. ::
  310. func _fixed_process(delta):
  311. var space = get_world_2d().get_space()
  312. var space_state = Physics2DServer.space_get_direct_state( space )
  313. Enjoy doing space queries!
  314. Contact Reporting
  315. ~~~~~~~~~~~~~~~~~
  316. Remember that not every combination of two bodies can "report" contacts.
  317. Static bodies are passive and will not report contacts when hit.
  318. Kinematic Bodies will report contacts but only against Rigid/Character
  319. bodies. Area2D will report overlap (not detailed contacts) with bodies
  320. and with other areas. The following table should make it more visual:
  321. In case of overlap, who receives collision information?
  322. -------------------------------------------------------
  323. \|\ *. Type \|*. RigidBody \|\ *. CharacterBody \|*. KinematicBody
  324. \|\ *. StaticBody \|*. Area \|
  325. \| **RigidBody** \| Both \| Both \| Both \| Rigidbody \| Area \|
  326. \| **CharacterBody** \| Both \| Both \| Both \| CharacterBody \| Area
  327. \|
  328. \| **KinematicBody** \| Both \| Both \| None \| None \| Area \|
  329. \| **StaticBody** \| RigidBody \| CharacterBody \| None \| None \|
  330. None \|
  331. \| **Area** \| Area \| Area \| Area \| None \| Both \|