2d_movement.rst 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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:`KinematicBody2D <class_KinematicBody2D>` for these examples,
  10. but the principles will apply to other node types (Area2D, RigidBody2D) as well.
  11. Setup
  12. -----
  13. Each example below uses the same scene setup. Start with a ``KinematicBody2D`` with two
  14. children: ``Sprite`` and ``CollisionShape2D``. You can use the Godot icon ("icon.png")
  15. for the Sprite's texture or use any other 2D image you have.
  16. Open ``Project -> Project Settings`` and select the "Input Map" tab. Add the following
  17. input actions (see :ref:`InputEvent <doc_inputevent>` for details):
  18. .. image:: img/movement_inputs.png
  19. 8-way movement
  20. --------------
  21. In this scenario, you want the user to press the four directional keys (up/left/down/right
  22. or W/A/S/D) and move in the selected direction. The name "8-way movement" comes from the
  23. fact that the player can move diagonally by pressing two keys at the same time.
  24. .. image:: img/movement_8way.gif
  25. Add a script to the kinematic body and add the following code:
  26. .. tabs::
  27. .. code-tab:: gdscript GDScript
  28. extends KinematicBody2D
  29. export (int) var speed = 200
  30. var velocity = Vector2()
  31. func get_input():
  32. velocity = Vector2()
  33. if Input.is_action_pressed('right'):
  34. velocity.x += 1
  35. if Input.is_action_pressed('left'):
  36. velocity.x -= 1
  37. if Input.is_action_pressed('down'):
  38. velocity.y += 1
  39. if Input.is_action_pressed('up'):
  40. velocity.y -= 1
  41. velocity = velocity.normalized() * speed
  42. func _physics_process(delta):
  43. get_input()
  44. move_and_slide(velocity)
  45. .. code-tab:: csharp
  46. using Godot;
  47. using System;
  48. public class Movement : KinematicBody2D
  49. {
  50. [Export] public int Speed = 200;
  51. Vector2 velocity = new Vector2();
  52. public void GetInput()
  53. {
  54. velocity = new Vector2();
  55. if (Input.IsActionPressed("right"))
  56. velocity.x += 1;
  57. if (Input.IsActionPressed("left"))
  58. velocity.x -= 1;
  59. if (Input.IsActionPressed("down"))
  60. velocity.y += 1;
  61. if (Input.IsActionPressed("up"))
  62. velocity.y -= 1;
  63. velocity = velocity.Normalized() * Speed;
  64. }
  65. public override void _PhysicsProcess(float delta)
  66. {
  67. GetInput();
  68. MoveAndSlide(velocity);
  69. }
  70. }
  71. In the ``get_input()`` function we check for the four key events and sum them
  72. up to get the velocity vector. This has the benefit of making two opposite keys
  73. cancel each other out, but will also result in diagonal movement being faster
  74. due to the two directions being added together.
  75. We can prevent that if we *normalize* the velocity, which means we set
  76. its *length* to ``1``, and multiply by the desired speed.
  77. .. tip:: If you've never used vector math before, or need a refresher,
  78. you can see an explanation of vector usage in Godot at :ref:`doc_vector_math`.
  79. Rotation + movement
  80. -------------------
  81. This type of movement is sometimes called "Asteroids-style" because it resembles
  82. how that classic arcade game worked. Pressing left/right rotates the character,
  83. while up/down moves it forward or backward in whatever direction it's facing.
  84. .. image:: img/movement_rotate1.gif
  85. .. tabs::
  86. .. code-tab:: gdscript GDScript
  87. extends KinematicBody2D
  88. export (int) var speed = 200
  89. export (float) var rotation_speed = 1.5
  90. var velocity = Vector2()
  91. var rotation_dir = 0
  92. func get_input():
  93. rotation_dir = 0
  94. velocity = Vector2()
  95. if Input.is_action_pressed('right'):
  96. rotation_dir += 1
  97. if Input.is_action_pressed('left'):
  98. rotation_dir -= 1
  99. if Input.is_action_pressed('down'):
  100. velocity = Vector2(-speed, 0).rotated(rotation)
  101. if Input.is_action_pressed('up'):
  102. velocity = Vector2(speed, 0).rotated(rotation)
  103. func _physics_process(delta):
  104. get_input()
  105. rotation += rotation_dir * rotation_speed * delta
  106. move_and_slide(velocity)
  107. .. code-tab:: csharp
  108. using Godot;
  109. using System;
  110. public class Movement : KinematicBody2D
  111. {
  112. [Export] public int Speed = 200;
  113. [Export] public float RotationSpeed = 1.5f;
  114. Vector2 velocity = new Vector2();
  115. int rotationDir = 0;
  116. public void GetInput()
  117. {
  118. rotationDir = 0;
  119. velocity = new Vector2();
  120. if (Input.IsActionPressed("right"))
  121. rotationDir += 1;
  122. if (Input.IsActionPressed("left"))
  123. rotationDir -= 1;
  124. if (Input.IsActionPressed("down"))
  125. velocity = new Vector2(-Speed, 0).Rotated(Rotation);
  126. if (Input.IsActionPressed("up"))
  127. velocity = new Vector2(Speed, 0).Rotated(Rotation);
  128. velocity = velocity.Normalized() * Speed;
  129. }
  130. public override void _PhysicsProcess(float delta)
  131. {
  132. GetInput();
  133. Rotation += rotationDir * RotationSpeed * delta;
  134. MoveAndSlide(velocity);
  135. }
  136. }
  137. Here we've added two new variables to track our rotation direction and speed.
  138. Again, pressing both keys at once will cancel out and result in no rotation.
  139. The rotation is applied directly to the body's ``rotation`` property.
  140. To set the velocity, we use the ``Vector2.rotated()`` method, so that it points
  141. in the same direction as the body. ``rotated()`` is a useful vector function
  142. that you can use in many circumstances where you would otherwise need to apply
  143. trigonometric functions.
  144. Rotation + movement (mouse)
  145. ---------------------------
  146. This style of movement is a variation of the previous one. This time, the direction
  147. is set by the mouse position instead of the keyboard. The character will always
  148. "look at" the mouse pointer. The forward/back inputs remain the same, however.
  149. .. image:: img/movement_rotate2.gif
  150. .. tabs::
  151. .. code-tab:: gdscript GDScript
  152. extends KinematicBody2D
  153. export (int) var speed = 200
  154. var velocity = Vector2()
  155. func get_input():
  156. look_at(get_global_mouse_position())
  157. velocity = Vector2()
  158. if Input.is_action_pressed('down'):
  159. velocity = Vector2(-speed, 0).rotated(rotation)
  160. if Input.is_action_pressed('up'):
  161. velocity = Vector2(speed, 0).rotated(rotation)
  162. func _physics_process(delta):
  163. get_input()
  164. move_and_slide(velocity)
  165. .. code-tab:: csharp
  166. using Godot;
  167. using System;
  168. public class Movement : KinematicBody2D
  169. {
  170. [Export] public int Speed = 200;
  171. Vector2 velocity = new Vector2();
  172. public void GetInput()
  173. {
  174. LookAt(GetGlobalMousePosition());
  175. velocity = new Vector2();
  176. if (Input.IsActionPressed("down"))
  177. velocity = new Vector2(-Speed, 0).Rotated(Rotation);
  178. if (Input.IsActionPressed("up"))
  179. velocity = new Vector2(Speed, 0).Rotated(Rotation);
  180. velocity = velocity.Normalized() * Speed;
  181. }
  182. public override void _PhysicsProcess(float delta)
  183. {
  184. GetInput();
  185. MoveAndSlide(velocity);
  186. }
  187. }
  188. Here we're using the :ref:`Node2D <class_Node2D>` ``look_at()`` method to
  189. point the player towards a given position. Without this function, you
  190. could get the same effect by setting the angle like this:
  191. .. tabs::
  192. .. code-tab:: gdscript GDScript
  193. rotation = get_global_mouse_position().angle_to_point(position)
  194. .. code-tab:: csharp
  195. var rotation = GetGlobalMousePosition().AngleToPoint(Position);
  196. Click-and-move
  197. --------------
  198. This last example uses only the mouse to control the character. Clicking
  199. on the screen will cause the player to move to the target location.
  200. .. image:: img/movement_click.gif
  201. .. tabs::
  202. .. code-tab:: gdscript GDScript
  203. extends KinematicBody2D
  204. export (int) var speed = 200
  205. var target = Vector2()
  206. var velocity = Vector2()
  207. func _input(event):
  208. if event.is_action_pressed('click'):
  209. target = get_global_mouse_position()
  210. func _physics_process(delta):
  211. velocity = (target - position).normalized() * speed
  212. # rotation = velocity.angle()
  213. if (target - position).length() > 5:
  214. move_and_slide(velocity)
  215. .. code-tab:: csharp
  216. using Godot;
  217. using System;
  218. public class Movement : KinematicBody2D
  219. {
  220. [Export] public int Speed = 200;
  221. Vector2 target = new Vector2();
  222. Vector2 velocity = new Vector2();
  223. public override void _Input(InputEvent @event)
  224. {
  225. if (@event.IsActionPressed("click"))
  226. {
  227. target = GetGlobalMousePosition();
  228. }
  229. }
  230. public override void _PhysicsProcess(float delta)
  231. {
  232. velocity = (target - Position).Normalized() * Speed;
  233. // Rotation = velocity.Angle();
  234. if ((target - Position).Length() > 5)
  235. {
  236. MoveAndSlide(velocity);
  237. }
  238. }
  239. }
  240. Note the ``length()`` check we make prior to movement. Without this test,
  241. the body would "jitter" upon reaching the target position, as it moves
  242. slightly past the position and tries to move back, only to move too far and
  243. repeat.
  244. Uncommenting the ``rotation`` line will also turn the body to point in its
  245. direction of motion if you prefer.
  246. .. tip:: This technique can also be used as the basis of a "following" character.
  247. The ``target`` position can be that of any object you want to move to.
  248. Summary
  249. -------
  250. You may find these code samples useful as starting points for your own projects.
  251. Feel free to use them and experiment with them to see what you can make.
  252. You can download this sample project here:
  253. :download:`2D_movement_demo.zip <files/2D_movement_demo.zip>`