2d_movement.rst 10 KB

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