using_kinematic_body_2d.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 of them
  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. // using MoveAndCollide
  86. var collision = MoveAndCollide(velocity * delta);
  87. if (collision != null)
  88. {
  89. velocity = velocity.Slide(collision.Normal);
  90. }
  91. // using MoveAndSlide
  92. velocity = MoveAndSlide(velocity);
  93. Anything you do with ``move_and_slide()`` can also be done with ``move_and_collide()``,
  94. but it might take a little more code. However, as we'll see in the examples below,
  95. there are cases where ``move_and_slide()`` doesn't provide the response you want.
  96. Examples
  97. --------
  98. To see these examples in action, download the sample project:
  99. :download:`using_kinematic2d.zip <files/using_kinematic2d.zip>`.
  100. Movement and walls
  101. ~~~~~~~~~~~~~~~~~~
  102. If you've downloaded the sample project, this example is in the "BasicMovement.tscn" scene.
  103. For this example, Add a ``KinematicBody2D`` with two children: a ``Sprite`` and a
  104. ``CollisionShape2D``. Use the Godot "icon.png" as the Sprite's texture (drag it
  105. from the Filesystem dock to the *Texture* property of the ``Sprite``). In the
  106. ``CollisionShape2D``'s *Shape* property, select "New RectangleShape2D" and
  107. size the rectangle to fit over the sprite image.
  108. .. note:: See :ref:`doc_2d_movement` for examples of implementing 2D movement schemes.
  109. Attach a script to the KinematicBody2D and add the following code:
  110. .. tabs::
  111. .. code-tab:: gdscript GDScript
  112. extends KinematicBody2D
  113. var speed = 250
  114. var velocity = Vector2()
  115. func get_input():
  116. # Detect up/down/left/right keystate and only move when pressed
  117. velocity = Vector2()
  118. if Input.is_action_pressed('ui_right'):
  119. velocity.x += 1
  120. if Input.is_action_pressed('ui_left'):
  121. velocity.x -= 1
  122. if Input.is_action_pressed('ui_down'):
  123. velocity.y += 1
  124. if Input.is_action_pressed('ui_up'):
  125. velocity.y -= 1
  126. velocity = velocity.normalized() * speed
  127. func _physics_process(delta):
  128. get_input()
  129. move_and_collide(velocity * delta)
  130. .. code-tab:: csharp
  131. using Godot;
  132. using System;
  133. public class KBExample : KinematicBody2D
  134. {
  135. public int Speed = 250;
  136. private Vector2 _velocity = new Vector2();
  137. public void getInput()
  138. {
  139. // Detect up/down/left/right keystate and only move when pressed
  140. _velocity = new Vector2();
  141. if (Input.IsActionPressed("ui_right"))
  142. {
  143. _velocity.x += 1;
  144. }
  145. if (Input.IsActionPressed("ui_left"))
  146. {
  147. _velocity.x -= 1;
  148. }
  149. if (Input.IsActionPressed("ui_down"))
  150. {
  151. _velocity.y += 1;
  152. }
  153. if (Input.IsActionPressed("ui_up"))
  154. {
  155. _velocity.y -= 1;
  156. }
  157. }
  158. public override void _PhysicsProcess(float delta)
  159. {
  160. getInput();
  161. MoveAndCollide(velocity * delta);
  162. }
  163. }
  164. Run this scene and you'll see that ``move_and_collide()`` works as expected, moving
  165. the body along the velocity vector. Now let's see what happens when you add
  166. some obstacles. Add a :ref:`StaticBody2D <class_StaticBody2D>` with a
  167. rectangular collision shape. For visibility, you can use a sprite, a
  168. Polygon2D, or turn on "Visible Collision Shapes" from the "Debug" menu.
  169. Run the scene again and try moving into the obstacle. You'll see that the ``KinematicBody2D``
  170. can't penetrate the obstacle. However, try moving into the obstacle at an angle and
  171. you'll find that the obstacle acts like glue - it feels like the body gets stuck.
  172. This happens because there is no *collision response*. ``move_and_collide()`` stops
  173. the body's movement when a collision occurs. We need to code whatever response we
  174. want from the collision.
  175. Try changing the function to ``move_and_slide(velocity)`` and running again.
  176. Note that we removed ``delta`` from the velocity calculation.
  177. ``move_and_slide()`` provides a default collision response of sliding the body along the
  178. collision object. This is useful for a great many game types, and may be all you need
  179. to get the behavior you want.
  180. Bouncing/reflecting
  181. ~~~~~~~~~~~~~~~~~~~
  182. What if you don't want a sliding collision response? For this example ("BounceandCollide.tscn"
  183. in the sample project), we have a character shooting bullets and we want the bullets to
  184. bounce off the walls.
  185. This example uses three scenes. The main scene contains the Player and Walls.
  186. The Bullet and Wall are separate scenes so that they can be instanced.
  187. The Player is controlled by the `w` and `s` keys for forward and back. Aiming
  188. uses the mouse pointer. Here is the code for the Player, using ``move_and_slide()``:
  189. .. tabs::
  190. .. code-tab:: gdscript GDScript
  191. extends KinematicBody2D
  192. var Bullet = preload("res://Bullet.tscn")
  193. var speed = 200
  194. var velocity = Vector2()
  195. func get_input():
  196. # add these actions in Project Settings -> Input Map
  197. velocity = Vector2()
  198. if Input.is_action_pressed('backward'):
  199. velocity = Vector2(-speed/3, 0).rotated(rotation)
  200. if Input.is_action_pressed('forward'):
  201. velocity = Vector2(speed, 0).rotated(rotation)
  202. if Input.is_action_just_pressed('mouse_click'):
  203. shoot()
  204. func shoot():
  205. # "Muzzle" is a Position2D placed at the barrel of the gun
  206. var b = Bullet.instance()
  207. b.start($Muzzle.global_position, rotation)
  208. get_parent().add_child(b)
  209. func _physics_process(delta):
  210. get_input()
  211. var dir = get_global_mouse_position() - global_position
  212. # Don't move if too close to the mouse pointer
  213. if dir.length() > 5:
  214. rotation = dir.angle()
  215. velocity = move_and_slide(velocity)
  216. .. code-tab:: csharp
  217. using Godot;
  218. using System;
  219. public class KBExample : KinematicBody2D
  220. {
  221. private PackedScene _bullet = (PackedScene)GD.Load("res://Bullet.tscn");
  222. public int Speed = 200;
  223. private Vector2 _velocity = new Vector2();
  224. public void getInput()
  225. {
  226. // add these actions in Project Settings -> Input Map
  227. _velocity = new Vector2();
  228. if (Input.IsActionPressed("backward"))
  229. {
  230. _velocity = new Vector2(-speed/3, 0).Rotated(Rotation);
  231. }
  232. if (Input.IsActionPressed("forward"))
  233. {
  234. _velocity = new Vector2(speed, 0).Rotated(Rotation);
  235. }
  236. if (Input.IsActionPressed("mouse_click"))
  237. {
  238. Shoot();
  239. }
  240. }
  241. public void Shoot()
  242. {
  243. // "Muzzle" is a Position2D placed at the barrel of the gun
  244. var b = (Bullet)_bullet.Instance();
  245. b.Start(((Node2D)GetNode("Muzzle")).GlobalPosition, Rotation);
  246. GetParent().AddChild(b);
  247. }
  248. public override void _PhysicsProcess(float delta)
  249. {
  250. getInput();
  251. var dir = GetGlobalMousePosition() - GlobalPosition;
  252. // Don't move if too close to the mouse pointer
  253. if (dir.Length() > 5)
  254. {
  255. Rotation = dir.Angle();
  256. _velocity = MoveAndSlide(_velocity);
  257. }
  258. }
  259. }
  260. And the code for the Bullet:
  261. .. tabs::
  262. .. code-tab:: gdscript GDScript
  263. extends KinematicBody2D
  264. var speed = 750
  265. var velocity = Vector2()
  266. func start(pos, dir):
  267. rotation = dir
  268. position = pos
  269. velocity = Vector2(speed, 0).rotated(rotation)
  270. func _physics_process(delta):
  271. var collision = move_and_collide(velocity * delta)
  272. if collision:
  273. velocity = velocity.bounce(collision.normal)
  274. if collision.collider.has_method("hit"):
  275. collision.collider.hit()
  276. func _on_VisibilityNotifier2D_screen_exited():
  277. queue_free()
  278. .. code-tab:: csharp
  279. using Godot;
  280. using System;
  281. public class Bullet : KinematicBody2D
  282. {
  283. public int Speed = 750;
  284. private Vector2 _velocity = new Vector2();
  285. public void Start(Vector2 pos, float dir)
  286. {
  287. Rotation = dir;
  288. Position = pos;
  289. _velocity = new Vector2(speed, 0).Rotated(Rotation);
  290. }
  291. public override void _PhysicsProcess(float delta)
  292. {
  293. var collsion = MoveAndCollide(_velocity * delta);
  294. if (collsion != null)
  295. {
  296. _velocity = _velocity.Bounce(collsion.Normal);
  297. if (collsion.Collider.HasMethod("Hit"))
  298. {
  299. collsion.Collider.Hit();
  300. }
  301. }
  302. }
  303. public void OnVisibilityNotifier2DScreenExited()
  304. {
  305. QueueFree();
  306. }
  307. }
  308. The action happens in ``_physics_process()``. After using ``move_and_collide()`` if a
  309. collision occurs, a ``KinematicCollision2D`` object is returned (otherwise, the return
  310. is ``Nil``).
  311. If there is a returned collision, we use the ``normal`` of the collision to reflect
  312. the bullet's ``velocity`` with the ``Vector2.bounce()`` method.
  313. If the colliding object (``collider``) has a ``hit`` method,
  314. we also call it. In the example project, we've added a flashing color effect to
  315. the Wall to demonstrate this.
  316. .. image:: img/k2d_bullet_bounce.gif
  317. Platformer movement
  318. ~~~~~~~~~~~~~~~~~~~
  319. Let's try one more popular example: the 2D platformer. ``move_and_slide()``
  320. is ideal for quickly getting a functional character controller up and running.
  321. If you've downloaded the sample project, you can find this in "Platformer.tscn".
  322. For this example, we'll assume you have a level made of ``StaticBody2D`` objects.
  323. They can be any shape and size. In the sample project, we're using
  324. :ref:`Polygon2D <class_Polygon2D>` to create the platform shapes.
  325. Here's the code for the player body:
  326. .. tabs::
  327. .. code-tab:: gdscript GDScript
  328. extends KinematicBody2D
  329. export (int) var run_speed = 100
  330. export (int) var jump_speed = -400
  331. export (int) var gravity = 1200
  332. var velocity = Vector2()
  333. var jumping = false
  334. func get_input():
  335. velocity.x = 0
  336. var right = Input.is_action_pressed('ui_right')
  337. var left = Input.is_action_pressed('ui_left')
  338. var jump = Input.is_action_just_pressed('ui_select')
  339. if jump and is_on_floor():
  340. jumping = true
  341. velocity.y = jump_speed
  342. if right:
  343. velocity.x += run_speed
  344. if left:
  345. velocity.x -= run_speed
  346. func _physics_process(delta):
  347. get_input()
  348. velocity.y += gravity * delta
  349. if jumping and is_on_floor():
  350. jumping = false
  351. velocity = move_and_slide(velocity, Vector2(0, -1))
  352. .. code-tab:: csharp
  353. using Godot;
  354. using System;
  355. public class KBExample : KinematicBody2D
  356. {
  357. [Export] public int RunSpeed = 100;
  358. [Export] public int JumpSpeed = -400;
  359. [Export] public int Gravity = 1200;
  360. Vector2 velocity = new Vector2();
  361. bool jumping = false;
  362. public void getInput()
  363. {
  364. velocity.x = 0;
  365. bool right = Input.IsActionPressed("ui_right");
  366. bool left = Input.IsActionPressed("ui_left");
  367. bool jump = Input.IsActionPressed("ui_select");
  368. if (jump && IsOnFloor())
  369. {
  370. jumping = true;
  371. velocity.y = JumpSpeed;
  372. }
  373. if (right)
  374. {
  375. velocity.x += RunSpeed;
  376. }
  377. if (left)
  378. {
  379. velocity.x -= RunSpeed;
  380. }
  381. }
  382. public override void _PhysicsProcess(float delta)
  383. {
  384. getInput();
  385. velocity.y += Gravity * delta;
  386. if (jumping && IsOnFloor())
  387. {
  388. jumping = false;
  389. }
  390. velocity = MoveAndSlide(velocity, new Vector2(0, -1));
  391. }
  392. }
  393. .. image:: img/k2d_platform.gif
  394. When using ``move_and_slide()`` the function returns a vector representing the
  395. movement that remained after the slide collision occurred. Setting that value back
  396. to the character's ``velocity`` allows us to smoothly move up and down slopes. Try
  397. removing ``velocity =`` and see what happens if you don't do this.
  398. Also note that we've added ``Vector2(0, -1)`` as the floor normal. This is a vector
  399. pointing straight upward. This means that if the character collides with an object
  400. that has this normal, it will be considered a floor.
  401. Using the floor normal allows us to make jumping work, using ``is_on_floor()``. This
  402. function will only return ``true`` after a ``move_and_slide()`` collision where the
  403. colliding body's normal is within 45 degrees of the given floor vector (this can
  404. be adjusted by setting ``floor_max_angle``).
  405. This also allows you to implement other features like wall jumps using ``is_on_wall()``,
  406. for example.