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