using_character_body_2d.rst 19 KB

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