using_character_body_2d.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. .. _doc_using_character_body_2d:
  2. Using CharacterBody2D/3D
  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:`CharacterBody2D <class_CharacterBody2D>` node and show some examples
  11. of how to use it.
  12. .. note:: While this document uses ``CharacterBody2D`` in its examples, the same
  13. concepts apply in 3D as well.
  14. What is a character body?
  15. -------------------------
  16. ``CharacterBody2D`` is for implementing bodies that are controlled via code.
  17. Character 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. .. note:: This document assumes you're familiar with Godot's various physics
  22. bodies. Please read :ref:`doc_physics_introduction` first, for an overview
  23. of the physics options.
  24. .. tip:: A `CharacterBody2D` can be affected by gravity and other forces,
  25. but you must calculate the movement in code. The physics engine will
  26. not move a `CharacterBody2D`.
  27. Movement and collision
  28. ----------------------
  29. When moving a ``CharacterBody2D``, you should not set its ``position`` property
  30. directly. Instead, you use the ``move_and_collide()`` or ``move_and_slide()`` methods.
  31. These methods move the body along a given vector and detect collisions.
  32. .. warning:: You should handle physics body movement in the ``_physics_process()`` callback.
  33. The two movement methods serve different purposes, and later in this tutorial, you'll
  34. see examples of how they work.
  35. move_and_collide
  36. ~~~~~~~~~~~~~~~~
  37. This method takes one required parameter: a :ref:`Vector2 <class_Vector2>` indicating
  38. the body's relative movement. Typically, this is your velocity vector multiplied by the
  39. frame timestep (``delta``). If the engine detects a collision anywhere along
  40. this vector, the body will immediately stop moving. If this happens, the
  41. method will return a :ref:`KinematicCollision2D <class_KinematicCollision2D>` object.
  42. ``KinematicCollision2D`` is an object containing data about the collision
  43. and the colliding object. Using this data, you can calculate your collision
  44. response.
  45. ``move_and_collide`` is most useful when you just want to move the body and
  46. detect collision, but don't need any automatic collision response. For example,
  47. if you need a bullet that ricochets off a wall, you can directly change the angle
  48. of the velocity when you detect a collision. See below for an example.
  49. move_and_slide
  50. ~~~~~~~~~~~~~~
  51. The ``move_and_slide()`` method is intended to simplify the collision
  52. response in the common case where you want one body to slide along the other.
  53. It is especially useful in platformers or top-down games, for example.
  54. .. tip:: ``move_and_slide()`` automatically calculates frame-based movement
  55. using ``delta``. Do *not* multiply your velocity vector by ``delta``
  56. before passing it to ``move_and_slide()``.
  57. When calling ``move_and_slide()``, the function uses a number of node properties
  58. to calculate its slide behavior. These properties can be found in the Inspector,
  59. or set in code.
  60. - ``velocity`` - *default value:* ``Vector2( 0, 0 )``
  61. This property represents the body's velocity vector in pixels per second.
  62. ``move_and_slide()`` will modify this value automatically when colliding.
  63. - ``motion_mode`` - *default value:* ``MOTION_MODE_GROUNDED``
  64. This property is typically used to distinguish between side-scrolling and
  65. top-down movement. When using the default value, you can use the ``is_on_floor()``,
  66. ``is_on_wall()``, and ``is_on_ceiling()`` methods to detect what type of
  67. surface the body is in contact with, and the body will interact with slopes.
  68. When using ``MOTION_MODE_FLOATING``, all collisions will be considered "walls".
  69. - ``up_direction`` - *default value:* ``Vector2( 0, -1 )``
  70. This property allows you to define what surfaces the engine should consider
  71. being the floor. Its value lets you use the ``is_on_floor()``, ``is_on_wall()``,
  72. and ``is_on_ceiling()`` methods to detect what type of surface the body is
  73. in contact with. The default value means that the top side of horizontal surfaces
  74. will be considered "ground".
  75. - ``floor_stop_on_slope`` - *default value:* ``true``
  76. This parameter prevents a body from sliding down slopes when standing still.
  77. - ``wall_min_slide_angle`` - *default value:* ``0.261799`` (in radians, equivalent to ``15`` degrees)
  78. This is the minimum angle where the body is allowed to slide when it hits a
  79. slope.
  80. - ``floor_max_angle`` - *default value:* ``0.785398`` (in radians, equivalent to ``45`` degrees)
  81. This parameter is the maximum angle before a surface is no longer considered a "floor."
  82. There are many other properties that can be used to modify the body's behavior under
  83. specific circumstances. See the :ref:`CharacterBody2D <class_CharacterBody2D>` docs
  84. for full details.
  85. Detecting collisions
  86. --------------------
  87. When using ``move_and_collide()`` the function returns a ``KinematicCollision2D``
  88. directly, and you can use this in your code.
  89. When using ``move_and_slide()`` it's possible to have multiple collisions occur,
  90. as the slide response is calculated. To process these collisions, use ``get_slide_collision_count()``
  91. and ``get_slide_collision()``:
  92. .. tabs::
  93. .. code-tab:: gdscript GDScript
  94. # Using move_and_collide.
  95. var collision = move_and_collide(velocity * delta)
  96. if collision:
  97. print("I collided with ", collision.get_collider().name)
  98. # Using move_and_slide.
  99. move_and_slide()
  100. for i in get_slide_count():
  101. var collision = get_slide_collision(i)
  102. print("I collided with ", collision.get_collider().name)
  103. .. code-tab:: csharp
  104. // Using MoveAndCollide.
  105. var collision = MoveAndCollide(Velocity * (float)delta);
  106. if (collision != null)
  107. {
  108. GD.Print("I collided with ", ((Node)collision.GetCollider()).Name);
  109. }
  110. // Using MoveAndSlide.
  111. MoveAndSlide();
  112. for (int i = 0; i < GetSlideCount(); i++)
  113. {
  114. var collision = GetSlideCollision(i);
  115. GD.Print("I collided with ", ((Node)collision.GetCollider()).Name);
  116. }
  117. .. note:: `get_slide_collision_count()` only counts times the body has collided and changed direction.
  118. See :ref:`KinematicCollision2D <class_KinematicCollision2D>` for details on what
  119. collision data is returned.
  120. Which movement method to use?
  121. -----------------------------
  122. A common question from new Godot users is: "How do you decide which movement
  123. function to use?" Often, the response is to use ``move_and_slide()`` because
  124. it seems simpler, but this is not necessarily the case. One way to think of it
  125. is that ``move_and_slide()`` is a special case, and ``move_and_collide()``
  126. is more general. For example, the following two code snippets result in
  127. the same collision response:
  128. .. image:: img/k2d_compare.gif
  129. .. tabs::
  130. .. code-tab:: gdscript GDScript
  131. # using move_and_collide
  132. var collision = move_and_collide(velocity * delta)
  133. if collision:
  134. velocity = velocity.slide(collision.get_normal())
  135. # using move_and_slide
  136. move_and_slide()
  137. .. code-tab:: csharp
  138. // using MoveAndCollide
  139. var collision = MoveAndCollide(Velocity * (float)delta);
  140. if (collision != null)
  141. {
  142. velocity = velocity.Slide(collision.GetNormal());
  143. }
  144. // using MoveAndSlide
  145. MoveAndSlide();
  146. Anything you do with ``move_and_slide()`` can also be done with ``move_and_collide()``,
  147. but it might take a little more code. However, as we'll see in the examples below,
  148. there are cases where ``move_and_slide()`` doesn't provide the response you want.
  149. In the example above, ``move_and_slide()`` automatically alters the ``velocity``
  150. variable. This is because when the character collides with the environment,
  151. the function recalculates the speed internally to reflect
  152. the slowdown.
  153. For example, if your character fell on the floor, you don't want it to
  154. accumulate vertical speed due to the effect of gravity. Instead, you want its
  155. vertical speed to reset to zero.
  156. ``move_and_slide()`` may also recalculate the kinematic body's velocity several
  157. times in a loop as, to produce a smooth motion, it moves the character and
  158. collides up to five times by default. At the end of the process, the character's
  159. new velocity is available for use on the next frame.
  160. Examples
  161. --------
  162. To see these examples in action, download the sample project:
  163. :download:`using_kinematic2d.zip <files/using_kinematic2d.zip>`.
  164. Movement and walls
  165. ~~~~~~~~~~~~~~~~~~
  166. If you've downloaded the sample project, this example is in "BasicMovement.tscn".
  167. For this example, add a ``CharacterBody2D`` with two children: a ``Sprite2D`` and a
  168. ``CollisionShape2D``. Use the Godot "icon.png" as the Sprite2D's texture (drag it
  169. from the Filesystem dock to the *Texture* property of the ``Sprite2D``). In the
  170. ``CollisionShape2D``'s *Shape* property, select "New RectangleShape2D" and
  171. size the rectangle to fit over the sprite image.
  172. .. note:: See :ref:`doc_2d_movement` for examples of implementing 2D movement schemes.
  173. Attach a script to the CharacterBody2D and add the following code:
  174. .. tabs::
  175. .. code-tab:: gdscript GDScript
  176. extends CharacterBody2D
  177. var speed = 300
  178. func get_input():
  179. var input_dir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
  180. velocity = input_dir * speed
  181. func _physics_process(delta):
  182. get_input()
  183. move_and_collide(velocity * delta)
  184. .. code-tab:: csharp
  185. using Godot;
  186. public partial class CBExample : CharacterBody2D
  187. {
  188. public int Speed = 300;
  189. public void GetInput()
  190. {
  191. Vector2 inputDir = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
  192. Velocity = inputDir * Speed;
  193. }
  194. public override void _PhysicsProcess(double delta)
  195. {
  196. GetInput();
  197. MoveAndCollide(Velocity * (float)delta);
  198. }
  199. }
  200. Run this scene and you'll see that ``move_and_collide()`` works as expected, moving
  201. the body along the velocity vector. Now let's see what happens when you add
  202. some obstacles. Add a :ref:`StaticBody2D <class_StaticBody2D>` with a
  203. rectangular collision shape. For visibility, you can use a sprite, a
  204. Polygon2D, or turn on "Visible Collision Shapes" from the "Debug" menu.
  205. Run the scene again and try moving into the obstacle. You'll see that the ``CharacterBody2D``
  206. can't penetrate the obstacle. However, try moving into the obstacle at an angle and
  207. you'll find that the obstacle acts like glue - it feels like the body gets stuck.
  208. This happens because there is no *collision response*. ``move_and_collide()`` stops
  209. the body's movement when a collision occurs. We need to code whatever response we
  210. want from the collision.
  211. Try changing the function to ``move_and_slide()`` and running again.
  212. ``move_and_slide()`` provides a default collision response of sliding the body along the
  213. collision object. This is useful for a great many game types, and may be all you need
  214. to get the behavior you want.
  215. Bouncing/reflecting
  216. ~~~~~~~~~~~~~~~~~~~
  217. What if you don't want a sliding collision response? For this example ("BounceandCollide.tscn"
  218. in the sample project), we have a character shooting bullets and we want the bullets to
  219. bounce off the walls.
  220. This example uses three scenes. The main scene contains the Player and Walls.
  221. The Bullet and Wall are separate scenes so that they can be instanced.
  222. The Player is controlled by the `w` and `s` keys for forward and back. Aiming
  223. uses the mouse pointer. Here is the code for the Player, using ``move_and_slide()``:
  224. .. tabs::
  225. .. code-tab:: gdscript GDScript
  226. extends CharacterBody2D
  227. var Bullet = preload("res://Bullet.tscn")
  228. var speed = 200
  229. func get_input():
  230. # Add these actions in Project Settings -> Input Map.
  231. var input_dir = Input.get_axis("backward", "forward")
  232. velocity = transform.x * input_dir * speed
  233. if Input.is_action_just_pressed("shoot"):
  234. shoot()
  235. func shoot():
  236. # "Muzzle" is a Marker2D placed at the barrel of the gun.
  237. var b = Bullet.instantiate()
  238. b.start($Muzzle.global_position, rotation)
  239. get_tree().root.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. move_and_slide()
  247. .. code-tab:: csharp
  248. using Godot;
  249. public partial class CBExample : CharacterBody2D
  250. {
  251. private PackedScene _bullet = (PackedScene)GD.Load("res://Bullet.tscn");
  252. public int Speed = 200;
  253. public void GetInput()
  254. {
  255. // Add these actions in Project Settings -> Input Map.
  256. float inputDir = Input.GetAxis("backward", "forward");
  257. Velocity = Transform.x * inputDir * Speed;
  258. if (Input.IsActionPressed("shoot"))
  259. {
  260. Shoot();
  261. }
  262. }
  263. public void Shoot()
  264. {
  265. // "Muzzle" is a Marker2D placed at the barrel of the gun.
  266. var b = (Bullet)_bullet.Instantiate();
  267. b.Start(GetNode<Node2D>("Muzzle").GlobalPosition, Rotation);
  268. GetTree().Root.AddChild(b);
  269. }
  270. public override void _PhysicsProcess(double delta)
  271. {
  272. GetInput();
  273. var dir = GetGlobalMousePosition() - GlobalPosition;
  274. // Don't move if too close to the mouse pointer.
  275. if (dir.Length() > 5)
  276. {
  277. Rotation = dir.Angle();
  278. MoveAndSlide();
  279. }
  280. }
  281. }
  282. And the code for the Bullet:
  283. .. tabs::
  284. .. code-tab:: gdscript GDScript
  285. extends CharacterBody2D
  286. var speed = 750
  287. func start(_position, _direction):
  288. rotation = _direction
  289. position = _position
  290. velocity = Vector2(speed, 0).rotated(rotation)
  291. func _physics_process(delta):
  292. var collision = move_and_collide(velocity * delta)
  293. if collision:
  294. velocity = velocity.bounce(collision.get_normal())
  295. if collision.get_collider().has_method("hit"):
  296. collision.get_collider().hit()
  297. func _on_VisibilityNotifier2D_screen_exited():
  298. # Deletes the bullet when it exits the screen.
  299. queue_free()
  300. .. code-tab:: csharp
  301. using Godot;
  302. public partial class Bullet : CharacterBody2D
  303. {
  304. public int Speed = 750;
  305. public void Start(Vector2 position, float direction)
  306. {
  307. Rotation = direction;
  308. Position = position;
  309. Velocity = new Vector2(speed, 0).Rotated(Rotation);
  310. }
  311. public override void _PhysicsProcess(double delta)
  312. {
  313. var collision = MoveAndCollide(Velocity * (float)delta);
  314. if (collision != null)
  315. {
  316. Velocity = Velocity.Bounce(collision.GetNormal());
  317. if (collision.GetCollider().HasMethod("Hit"))
  318. {
  319. collision.GetCollider().Call("Hit");
  320. }
  321. }
  322. }
  323. public void OnVisibilityNotifier2DScreenExited()
  324. {
  325. // Deletes the bullet when it exits the screen.
  326. QueueFree();
  327. }
  328. }
  329. The action happens in ``_physics_process()``. After using ``move_and_collide()``, if a
  330. collision occurs, a ``KinematicCollision2D`` object is returned (otherwise, the return
  331. is ``Nil``).
  332. If there is a returned collision, we use the ``normal`` of the collision to reflect
  333. the bullet's ``velocity`` with the ``Vector2.bounce()`` method.
  334. If the colliding object (``collider``) has a ``hit`` method,
  335. we also call it. In the example project, we've added a flashing color effect to
  336. the Wall to demonstrate this.
  337. .. image:: img/k2d_bullet_bounce.gif
  338. Platformer movement
  339. ~~~~~~~~~~~~~~~~~~~
  340. Let's try one more popular example: the 2D platformer. ``move_and_slide()``
  341. is ideal for quickly getting a functional character controller up and running.
  342. If you've downloaded the sample project, you can find this in "platformer.tscn".
  343. For this example, we'll assume you have a level made of one or more ``StaticBody2D``
  344. objects. They can be any shape and size. In the sample project, we're using
  345. :ref:`Polygon2D <class_Polygon2D>` to create the platform shapes.
  346. Here's the code for the player body:
  347. .. tabs::
  348. .. code-tab:: gdscript GDScript
  349. extends CharacterBody2D
  350. var speed = 300.0
  351. var jump_speed = -400.0
  352. # Get the gravity from the project settings so you can sync with rigid body nodes.
  353. var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
  354. func _physics_process(delta):
  355. # Add the gravity.
  356. velocity.y += gravity * delta
  357. # Handle Jump.
  358. if Input.is_action_just_pressed("jump") and is_on_floor():
  359. velocity.y = jump_speed
  360. # Get the input direction.
  361. var direction = Input.get_axis("ui_left", "ui_right")
  362. velocity.x = direction * speed
  363. move_and_slide()
  364. .. code-tab:: csharp
  365. using Godot;
  366. public partial class CBExample : CharacterBody2D
  367. {
  368. public float Speed = 100.0f;
  369. public float JumpSpeed = -400.0f;
  370. // Get the gravity from the project settings so you can sync with rigid body nodes.
  371. public float Gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
  372. public override void _PhysicsProcess(double delta)
  373. {
  374. Vector2 velocity = Velocity;
  375. // Add the gravity.
  376. velocity.Y += Gravity * (float)delta;
  377. // Handle jump.
  378. if (Input.IsActionJustPressed("jump") && IsOnFloor())
  379. velocity.Y = JumpSpeed;
  380. // Get the input direction.
  381. Vector2 direction = Input.GetAxis("ui_left", "ui_right");
  382. velocity.X = direction * Speed;
  383. Velocity = velocity;
  384. MoveAndSlide();
  385. }
  386. }
  387. .. image:: img/k2d_platform.gif
  388. In this code we're using ``move_and_slide()`` as described above - to move the body
  389. along its velocity vector, sliding along any collision surfaces such as the ground
  390. or a platform. We're also using ``is_on_floor()`` to check if a jump should be
  391. allowed. Without this, you'd be able to "jump" in midair; great if you're making
  392. Flappy Bird, but not for a platformer game.
  393. There is a lot more that goes into a complete platformer character: acceleration,
  394. double-jumps, coyote-time, and many more. The code above is just a starting point.
  395. You can use it as a base to expand into whatever movement behavior you need for
  396. your own projects.