using_kinematic_body_2d.rst 19 KB

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