2d_movement.rst 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. .. _doc_2d_movement:
  2. 2D movement overview
  3. ====================
  4. Introduction
  5. ------------
  6. Every beginner has been there: "How do I move my character?" Depending on the
  7. style of game you're making, you may have special requirements, but in general
  8. the movement in most 2D games is based on a small number of designs.
  9. We'll use :ref:`CharacterBody2D <class_CharacterBody2D>` for these examples,
  10. but the principles will apply to other node types (Area2D, RigidBody2D) as well.
  11. .. _doc_2d_movement_setup:
  12. Setup
  13. -----
  14. Each example below uses the same scene setup. Start with a ``CharacterBody2D`` with two
  15. children: ``Sprite2D`` and ``CollisionShape2D``. You can use the Godot icon ("icon.png")
  16. for the Sprite2D's texture or use any other 2D image you have.
  17. Open ``Project -> Project Settings`` and select the "Input Map" tab. Add the following
  18. input actions (see :ref:`InputEvent <doc_inputevent>` for details):
  19. .. image:: img/movement_inputs.webp
  20. 8-way movement
  21. --------------
  22. In this scenario, you want the user to press the four directional keys (up/left/down/right
  23. or W/A/S/D) and move in the selected direction. The name "8-way movement" comes from the
  24. fact that the player can move diagonally by pressing two keys at the same time.
  25. .. image:: img/movement_8way.gif
  26. Add a script to the character body and add the following code:
  27. .. tabs::
  28. .. code-tab:: gdscript GDScript
  29. extends CharacterBody2D
  30. @export var speed = 400
  31. func get_input():
  32. var input_direction = Input.get_vector("left", "right", "up", "down")
  33. velocity = input_direction * speed
  34. func _physics_process(delta):
  35. get_input()
  36. move_and_slide()
  37. .. code-tab:: csharp
  38. using Godot;
  39. public partial class Movement : CharacterBody2D
  40. {
  41. [Export]
  42. public int Speed { get; set; } = 400;
  43. public void GetInput()
  44. {
  45. Vector2 inputDirection = Input.GetVector("left", "right", "up", "down");
  46. Velocity = inputDirection * Speed;
  47. }
  48. public override void _PhysicsProcess(double delta)
  49. {
  50. GetInput();
  51. MoveAndSlide();
  52. }
  53. }
  54. In the ``get_input()`` function, we use :ref:`Input <class_Input>` ``get_vector()`` to check for the
  55. four key events and sum return a direction vector.
  56. We can then set our velocity by multiplying this direction vector, which has a
  57. length of ``1``, by our desired speed.
  58. .. tip:: If you've never used vector math before, or need a refresher,
  59. you can see an explanation of vector usage in Godot at :ref:`doc_vector_math`.
  60. .. note::
  61. If the code above does nothing when you press the keys, double-check that
  62. you've set up input actions correctly as described in the
  63. :ref:`doc_2d_movement_setup` part of this tutorial.
  64. Rotation + movement
  65. -------------------
  66. This type of movement is sometimes called "Asteroids-style" because it resembles
  67. how that classic arcade game worked. Pressing left/right rotates the character,
  68. while up/down moves it forward or backward in whatever direction it's facing.
  69. .. image:: img/movement_rotate1.gif
  70. .. tabs::
  71. .. code-tab:: gdscript GDScript
  72. extends CharacterBody2D
  73. @export var speed = 400
  74. @export var rotation_speed = 1.5
  75. var rotation_direction = 0
  76. func get_input():
  77. rotation_direction = Input.get_axis("left", "right")
  78. velocity = transform.x * Input.get_axis("down", "up") * speed
  79. func _physics_process(delta):
  80. get_input()
  81. rotation += rotation_direction * rotation_speed * delta
  82. move_and_slide()
  83. .. code-tab:: csharp
  84. using Godot;
  85. public partial class Movement : CharacterBody2D
  86. {
  87. [Export]
  88. public int Speed { get; set; } = 400;
  89. [Export]
  90. public float RotationSpeed { get; set; } = 1.5f;
  91. private float _rotationDirection;
  92. public void GetInput()
  93. {
  94. _rotationDirection = Input.GetAxis("left", "right");
  95. Velocity = Transform.X * Input.GetAxis("down", "up") * Speed;
  96. }
  97. public override void _PhysicsProcess(double delta)
  98. {
  99. GetInput();
  100. Rotation += _rotationDirection * RotationSpeed * (float)delta;
  101. MoveAndSlide();
  102. }
  103. }
  104. Here we've added two variables to track our rotation direction and speed.
  105. The rotation is applied directly to the body's ``rotation`` property.
  106. To set the velocity, we use the body's ``transform.x`` which is a vector pointing
  107. in the body's "forward" direction, and multiply that by the speed.
  108. Rotation + movement (mouse)
  109. ---------------------------
  110. This style of movement is a variation of the previous one. This time, the direction
  111. is set by the mouse position instead of the keyboard. The character will always
  112. "look at" the mouse pointer. The forward/back inputs remain the same, however.
  113. .. image:: img/movement_rotate2.gif
  114. .. tabs::
  115. .. code-tab:: gdscript GDScript
  116. extends CharacterBody2D
  117. @export var speed = 400
  118. func get_input():
  119. look_at(get_global_mouse_position())
  120. velocity = transform.x * Input.get_axis("down", "up") * speed
  121. func _physics_process(delta):
  122. get_input()
  123. move_and_slide()
  124. .. code-tab:: csharp
  125. using Godot;
  126. public partial class Movement : CharacterBody2D
  127. {
  128. [Export]
  129. public int Speed { get; set; } = 400;
  130. public void GetInput()
  131. {
  132. LookAt(GetGlobalMousePosition());
  133. Velocity = Transform.X * Input.GetAxis("down", "up") * Speed;
  134. }
  135. public override void _PhysicsProcess(double delta)
  136. {
  137. GetInput();
  138. MoveAndSlide();
  139. }
  140. }
  141. Here we're using the :ref:`Node2D <class_Node2D>` ``look_at()`` method to
  142. point the player towards the mouse's position. Without this function, you
  143. could get the same effect by setting the angle like this:
  144. .. tabs::
  145. .. code-tab:: gdscript GDScript
  146. rotation = get_global_mouse_position().angle_to_point(position)
  147. .. code-tab:: csharp
  148. var rotation = GetGlobalMousePosition().AngleToPoint(Position);
  149. Click-and-move
  150. --------------
  151. This last example uses only the mouse to control the character. Clicking
  152. on the screen will cause the player to move to the target location.
  153. .. image:: img/movement_click.gif
  154. .. tabs::
  155. .. code-tab:: gdscript GDScript
  156. extends CharacterBody2D
  157. @export var speed = 400
  158. var target = position
  159. func _input(event):
  160. # Use is_action_pressed to only accept single taps as input instead of mouse drags.
  161. if event.is_action_pressed(&"click"):
  162. target = get_global_mouse_position()
  163. func _physics_process(delta):
  164. velocity = position.direction_to(target) * speed
  165. # look_at(target)
  166. if position.distance_to(target) > 10:
  167. move_and_slide()
  168. .. code-tab:: csharp
  169. using Godot;
  170. public partial class Movement : CharacterBody2D
  171. {
  172. [Export]
  173. public int Speed { get; set; } = 400;
  174. private Vector2 _target;
  175. public override void _Input(InputEvent @event)
  176. {
  177. // Use IsActionPressed to only accept single taps as input instead of mouse drags.
  178. if (@event.IsActionPressed("click"))
  179. {
  180. _target = GetGlobalMousePosition();
  181. }
  182. }
  183. public override void _PhysicsProcess(double delta)
  184. {
  185. Velocity = Position.DirectionTo(_target) * Speed;
  186. // LookAt(_target);
  187. if (Position.DistanceTo(_target) > 10)
  188. {
  189. MoveAndSlide();
  190. }
  191. }
  192. }
  193. Note the ``distance_to()`` check we make prior to movement. Without this test,
  194. the body would "jitter" upon reaching the target position, as it moves
  195. slightly past the position and tries to move back, only to move too far and
  196. repeat.
  197. Uncommenting the ``look_at()`` line will also turn the body to point in its
  198. direction of motion if you prefer.
  199. .. tip:: This technique can also be used as the basis of a "following" character.
  200. The ``target`` position can be that of any object you want to move to.
  201. Summary
  202. -------
  203. You may find these code samples useful as starting points for your own projects.
  204. Feel free to use them and experiment with them to see what you can make.
  205. You can download this sample project here:
  206. `2d_movement_starter.zip <https://github.com/godotengine/godot-docs-project-starters/releases/download/latest-4.x/2d_movement_starter.zip>`_