using_kinematic_body_2d.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. .. _doc_using_kinematic_body_2d:
  2. Using KinematicBody2D
  3. =====================
  4. Introduction
  5. ------------
  6. Godot offers a number of collision objects to provide both collision detection
  7. and response. Trying to decide which one to use for your project can be confusing.
  8. You can avoid problems and simplify development if you understand how each each
  9. works and what their pros and cons are. In this tutorial, we'll look at the
  10. :ref:`KinematicBody2D <class_KinematicBody2D>` node and show some examples
  11. of how it can be used.
  12. .. note:: This document assumes you're familiar with Godot's various physics
  13. bodies. Please read :ref:`doc_physics_introduction` first.
  14. What is a kinematic body?
  15. -------------------------
  16. ``KinematicBody2D`` is for implementing bodies that are to be controlled via code.
  17. They detect collisions with other bodies when moving, but are not affected by
  18. engine physics properties like gravity or friction. While this means that you
  19. have to write some code to create their behavior, it also means you have more
  20. precise control over how they move and react.
  21. .. tip:: A `KinematicBody2D` can be affected by gravity and other forces,
  22. but you must calculate the movement in code. The physics engine will
  23. not move a `KinematicBody2D`.
  24. Movement and Collision
  25. ----------------------
  26. When moving a ``KinematicBody2D``, you should not set its ``position`` property
  27. directly. Instead, you use the ``move_and_collide()`` or ``move_and_slide()`` methods.
  28. These methods move the body along a given vector and will instantly stop if
  29. a collision is detected with another body. After a KinematicBody2D has collided,
  30. any *collision response* must be coded manually.
  31. .. warning:: Kinematic body movement should only be done in the ``_physics_process()`` callback.
  32. The two movement methods serve different purposes, and later in this tutorial you'll
  33. see examples of how they work.
  34. ``move_and_collide``
  35. ~~~~~~~~~~~~~~~~~~~~
  36. This method takes one parameter: a :ref:`Vector2 <class_Vector2>` indicating the body's
  37. relative movement. Typically, this is your velocity vector multiplied by the
  38. frame timestep (``delta``). If the engine detects a collision anywhere along
  39. this vector, the body will immediately stop moving. If this happens, the
  40. method will return a :ref:`KinematicCollision2D <class_KinematicCollision2D>` object.
  41. ``KinematicCollision2D`` is an object containing data about the collision
  42. and the colliding object. Using this data you can calculate your collision
  43. response.
  44. ``move_and_slide``
  45. ~~~~~~~~~~~~~~~~~~
  46. The ``move_and_slide()`` method is intended to simplify the collision
  47. response in the common case where you want one body to slide along the other.
  48. This is especially useful in platformers or top-down games, for example.
  49. .. tip:: ``move_and_slide()`` automatically calculates frame-based movement
  50. using ``delta``. Do *not* multiply your velocity vector by ``delta``
  51. before passing it to ``move_and_slide()``.
  52. In addition to the velocity vector, ``move_and_slide()`` takes a number of
  53. other parameters allowing you to customize the slide behavior:
  54. - ``floor_normal`` - *default value:* ``Vector2( 0, 0 )``
  55. This parameter allows you to define what surfaces the engine should consider
  56. to be the floor. Setting this lets you use the ``is_on_floor()``, ``is_on_wall()``,
  57. and ``is_on_ceiling()`` methods to detect what type of surface the body is
  58. in contact with. The default value means that all surfaces are considered walls.
  59. - ``slope_stop_min_velocity`` - *default value:* ``5``
  60. This is the minimum velocity when standing on a slope. This prevents a body
  61. from sliding down a slope when standing still.
  62. - ``max_bounces`` - *default value:* ``4``
  63. This is the maximum number of collisions before the body stops moving. Setting
  64. this too low may prevent movement entirely.
  65. - ``floor_max_angle`` - *default value:* ``0.785398`` (in radians, equivalent to ``45`` degrees)
  66. This is the maximum angle before a surface is no longer considered a "floor".
  67. Which movement method to use?
  68. -----------------------------
  69. A common question from new Godot users is: "How do you decide which movement
  70. function to use?" Often the response is to use ``move_and_slide()`` because
  71. it's "simpler", but this is not necessarily the case. One way to think of it
  72. is that ``move_and_slide()`` is a special case, and ``move_and_collide()``
  73. is more general. For example, the following two code snippets result in
  74. the same collision response:
  75. .. image:: img/k2d_compare.gif
  76. .. tabs::
  77. .. code-tab:: gdscript GDScript
  78. # using move_and_collide
  79. var collision = move_and_collide(velocity * delta)
  80. if collision:
  81. velocity = velocity.slide(collision.normal)
  82. # using move_and_slide
  83. velocity = move_and_slide(velocity)
  84. .. code-tab:: csharp
  85. Coming soon
  86. Anything you do with ``move_and_slide()`` can also be done with ``move_and_collide()``,
  87. it just might take a little more code. However, as we'll see in the examples below,
  88. there are cases where ``move_and_slide()`` doesn't provide the response you want.
  89. Examples
  90. --------
  91. To see these examples in action, download the sample project:
  92. :download:`using_kinematic2d.zip <files/using_kinematic2d.zip>`.
  93. Movement and walls
  94. ~~~~~~~~~~~~~~~~~~
  95. If you've downloaded the sample project, this example is in the "BasicMovement.tscn" scene.
  96. For this example, Add a ``KinematicBody2D`` with two children: a ``Sprite`` and a
  97. ``CollisionShape2D``. Use the Godot "icon.png" as the Sprite's texture (drag it
  98. from the Filesystem dock to the *Texture* property of the ``Sprite``). In the
  99. ``CollisionShape2D``'s *Shape* property, select "New RectangleShape2D" and
  100. size the rectangle to fit over the sprite image.
  101. .. note:: See :ref:`doc_2d_movement` for examples of implementing 2D movement schemes.
  102. Attach a script to the KinematicBody2D and add the following code:
  103. .. tabs::
  104. .. code-tab:: gdscript GDScript
  105. extends KinematicBody2D
  106. var speed = 250
  107. var velocity = Vector2()
  108. func get_input():
  109. # Detect up/down/left/right keystate and only move when pressed
  110. velocity = Vector2()
  111. if Input.is_action_pressed('ui_right'):
  112. velocity.x += 1
  113. if Input.is_action_pressed('ui_left'):
  114. velocity.x -= 1
  115. if Input.is_action_pressed('ui_down'):
  116. velocity.y += 1
  117. if Input.is_action_pressed('ui_up'):
  118. velocity.y -= 1
  119. velocity = velocity.normalized() * speed
  120. func _physics_process(delta):
  121. get_input()
  122. move_and_collide(velocity * delta)
  123. .. code-tab:: csharp
  124. Coming soon
  125. Run this scene and you'll see that ``move_and_collide()`` works as expected, moving
  126. the body along the velocity vector. Now let's see what happens when you add
  127. some obstacles. Add a :ref:`StaticBody2D <class_StaticBody2D>` with a
  128. rectangular collision shape. For visibility, you can use a sprite, a
  129. Polygon2D, or just turn on "Visible Collision Shapes" from the "Debug" menu.
  130. Run the scene again and try moving into the obstacle. You'll see that the ``KinematicBody2D``
  131. can't penetrate the obstacle. However, try moving into the obstacle at an angle and
  132. you'll find that the obstacle acts like glue - it feels like the body gets stuck.
  133. This happens because there is no *collision response*. ``move_and_collide()`` just stops
  134. the body's movement when a collision occurs. We need to code whatever response we
  135. want from the collision.
  136. Try changing the function to ``move_and_slide(velocity)`` and running again.
  137. Note that we removed ``delta`` from the velocity calculation.
  138. ``move_and_slide()`` provides a default collision response of sliding the body along the
  139. collision object. This is useful for a great many game types, and may be all you need
  140. to get the behavior you want.
  141. Bouncing/reflecting
  142. ~~~~~~~~~~~~~~~~~~~
  143. What if you don't want a sliding collision response? For this example ("BounceandCollide.tscn"
  144. in the sample project), we have a character shooting bullets and we want the bullets to
  145. bounce off the walls.
  146. This example uses three scenes. The main scene contains the Player and Walls.
  147. The Bullet and Wall are separate scenes so that they can be instanced.
  148. The Player is controlled by the `w` and `s` keys for forward and back. Aiming
  149. uses the mouse pointer. Here is the code for the Player, using ``move_and_slide()``:
  150. .. tabs::
  151. .. code-tab:: gdscript GDScript
  152. extends KinematicBody2D
  153. var Bullet = preload("res://Bullet.tscn")
  154. var speed = 200
  155. var velocity = Vector2()
  156. func get_input():
  157. # add these actions in Project Settings -> Input Map
  158. velocity = Vector2()
  159. if Input.is_action_pressed('backward'):
  160. velocity = Vector2(-speed/3, 0).rotated(rotation)
  161. if Input.is_action_pressed('forward'):
  162. velocity = Vector2(speed, 0).rotated(rotation)
  163. if Input.is_action_just_pressed('mouse_click'):
  164. shoot()
  165. func shoot():
  166. # "Muzzle" is a Position2D placed at the barrel of the gun
  167. var b = Bullet.instance()
  168. b.start($Muzzle.global_position, rotation)
  169. get_parent().add_child(b)
  170. func _physics_process(delta):
  171. get_input()
  172. var dir = get_global_mouse_position() - global_position
  173. # Don't move if too close to the mouse pointer
  174. if dir.length() > 5:
  175. rotation = dir.angle()
  176. velocity = move_and_slide(velocity)
  177. .. code-tab:: csharp
  178. Coming soon
  179. And the code for the Bullet:
  180. .. tabs::
  181. .. code-tab:: gdscript GDScript
  182. extends KinematicBody2D
  183. var speed = 750
  184. var velocity = Vector2()
  185. func start(pos, dir):
  186. rotation = dir
  187. position = pos
  188. velocity = Vector2(speed, 0).rotated(rotation)
  189. func _physics_process(delta):
  190. var collision = move_and_collide(velocity * delta)
  191. if collision:
  192. velocity = velocity.bounce(collision.normal)
  193. if collision.collider.has_method("hit"):
  194. collision.collider.hit()
  195. func _on_VisibilityNotifier2D_screen_exited():
  196. queue_free()
  197. .. code-tab:: csharp
  198. Coming soon
  199. The action happens in ``_physics_process()``. After using ``move_and_collide()`` if a
  200. collision occurs, a ``KinematicCollision2D`` object is returned (otherwise, the return
  201. is ``Nil``).
  202. If there is a returned collision, we use the ``normal`` of the collision to reflect
  203. the bullet's ``velocity`` with the ``Vector2.bounce()`` method.
  204. If the colliding object (``collider``) has a ``hit`` method,
  205. we also call it. In the example project, we've added a flashing color effect to
  206. the Wall to demonstrate this.
  207. .. image:: img/k2d_bullet_bounce.gif
  208. Platformer movement
  209. ~~~~~~~~~~~~~~~~~~~
  210. Let's try one more popular example: the 2D platformer. ``move_and_slide()``
  211. is ideal for quickly getting a functional character controller up and running.
  212. If you've downloaded the sample project, you can find this in "Platformer.tscn".
  213. For this example, we'll assume you have a level made of ``StaticBody2D`` objects.
  214. They can be any shape and size. In the sample project, we're using
  215. :ref:`Polygon2D <class_Polygon2D>` to create the platform shapes.
  216. Here's the code for the player body:
  217. .. tabs::
  218. .. code-tab:: gdscript GDScript
  219. extends KinematicBody2D
  220. export (int) var run_speed = 100
  221. export (int) var jump_speed = -400
  222. export (int) var gravity = 1200
  223. var velocity = Vector2()
  224. var jumping = false
  225. func get_input():
  226. velocity.x = 0
  227. var right = Input.is_action_pressed('ui_right')
  228. var left = Input.is_action_pressed('ui_left')
  229. var jump = Input.is_action_just_pressed('ui_select')
  230. if jump and is_on_floor():
  231. jumping = true
  232. velocity.y = jump_speed
  233. if right:
  234. velocity.x += run_speed
  235. if left:
  236. velocity.x -= run_speed
  237. func _physics_process(delta):
  238. get_input()
  239. velocity.y += gravity * delta
  240. if jumping and is_on_floor():
  241. jumping = false
  242. velocity = move_and_slide(velocity, Vector2(0, -1))
  243. .. code-tab:: csharp
  244. Coming soon
  245. .. image:: img/k2d_platform.gif
  246. When using ``move_and_slide()`` the function returns a vector representing the
  247. movement that remained after the slide collision occurred. Setting that value back
  248. to the character's ``velocity`` allows us to smoothly move up and down slopes. Try
  249. removing ``velocity =`` and see what happens if you don't do this.
  250. Also note that we've added ``Vector2(0, -1)`` as the floor normal. This is a vector
  251. pointing straight upward. This means that if the character collides with an object
  252. that has this normal, it will be considered a floor.
  253. Using the floor normal allows us to make jumping work, using ``is_on_floor()``. This
  254. function will only return ``true`` after a ``move_and_slide()`` collision where the
  255. colliding body's normal is within 45 degrees of the given floor vector (this can
  256. be adjusted by setting ``floor_max_angle``).
  257. This also allows you to implement other features like wall jumps using ``is_on_wall()``,
  258. for example.