using_kinematic_body_2d.rst 19 KB

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