03.coding_the_player.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. .. _doc_your_first_2d_game_coding_the_player:
  2. Coding the player
  3. =================
  4. In this lesson, we'll add player movement, animation, and set it up to detect
  5. collisions.
  6. To do so, we need to add some functionality that we can't get from a built-in
  7. node, so we'll add a script. Click the ``Player`` node and click the "Attach
  8. Script" button:
  9. .. image:: img/add_script_button.webp
  10. In the script settings window, you can leave the default settings alone. Just
  11. click "Create":
  12. .. note:: If you're creating a C# script or other languages, select the language
  13. from the `language` drop down menu before hitting create.
  14. .. image:: img/attach_node_window.webp
  15. .. note:: If this is your first time encountering GDScript, please read
  16. :ref:`doc_scripting` before continuing.
  17. Start by declaring the member variables this object will need:
  18. .. tabs::
  19. .. code-tab:: gdscript GDScript
  20. extends Area2D
  21. @export var speed = 400 # How fast the player will move (pixels/sec).
  22. var screen_size # Size of the game window.
  23. .. code-tab:: csharp
  24. using Godot;
  25. public partial class Player : Area2D
  26. {
  27. [Export]
  28. public int Speed { get; set; } = 400; // How fast the player will move (pixels/sec).
  29. public Vector2 ScreenSize; // Size of the game window.
  30. }
  31. Using the ``export`` keyword on the first variable ``speed`` allows us to set
  32. its value in the Inspector. This can be handy for values that you want to be
  33. able to adjust just like a node's built-in properties. Click on the ``Player``
  34. node and you'll see the property now appears in the "Script Variables" section
  35. of the Inspector. Remember, if you change the value here, it will override the
  36. value written in the script.
  37. .. warning::
  38. If you're using C#, you need to (re)build the project assemblies
  39. whenever you want to see new export variables or signals. This
  40. build can be manually triggered by clicking the **Build** button at
  41. the top right of the editor.
  42. .. image:: img/build_dotnet.webp
  43. .. image:: img/export_variable.webp
  44. Your ``player.gd`` script should already contain
  45. a ``_ready()`` and a ``_process()`` function.
  46. If you didn't select the default template shown above,
  47. create these functions while following the lesson.
  48. The ``_ready()`` function is called when a node enters the scene tree, which is
  49. a good time to find the size of the game window:
  50. .. tabs::
  51. .. code-tab:: gdscript GDScript
  52. func _ready():
  53. screen_size = get_viewport_rect().size
  54. .. code-tab:: csharp
  55. public override void _Ready()
  56. {
  57. ScreenSize = GetViewportRect().Size;
  58. }
  59. Now we can use the ``_process()`` function to define what the player will do.
  60. ``_process()`` is called every frame, so we'll use it to update elements of our
  61. game, which we expect will change often. For the player, we need to do the
  62. following:
  63. - Check for input.
  64. - Move in the given direction.
  65. - Play the appropriate animation.
  66. First, we need to check for input - is the player pressing a key? For this game,
  67. we have 4 direction inputs to check. Input actions are defined in the Project
  68. Settings under "Input Map". Here, you can define custom events and assign
  69. different keys, mouse events, or other inputs to them. For this game, we will
  70. map the arrow keys to the four directions.
  71. Click on *Project -> Project Settings* to open the project settings window and
  72. click on the *Input Map* tab at the top. Type "move_right" in the top bar and
  73. click the "Add" button to add the ``move_right`` action.
  74. .. image:: img/input-mapping-add-action.webp
  75. We need to assign a key to this action. Click the "+" icon on the right, to
  76. open the event manager window.
  77. .. image:: img/input-mapping-add-key.webp
  78. The "Listening for Input..." field should automatically be selected.
  79. Press the "right" key on your keyboard, and the menu should look like this now.
  80. .. image:: img/input-mapping-event-configuration.webp
  81. Select the "ok" button. The "right" key is now associated with the ``move_right`` action.
  82. Repeat these steps to add three more mappings:
  83. 1. ``move_left`` mapped to the left arrow key.
  84. 2. ``move_up`` mapped to the up arrow key.
  85. 3. And ``move_down`` mapped to the down arrow key.
  86. Your input map tab should look like this:
  87. .. image:: img/input-mapping-completed.webp
  88. Click the "Close" button to close the project settings.
  89. .. note::
  90. We only mapped one key to each input action, but you can map multiple keys,
  91. joystick buttons, or mouse buttons to the same input action.
  92. You can detect whether a key is pressed using ``Input.is_action_pressed()``,
  93. which returns ``true`` if it's pressed or ``false`` if it isn't.
  94. .. tabs::
  95. .. code-tab:: gdscript GDScript
  96. func _process(delta):
  97. var velocity = Vector2.ZERO # The player's movement vector.
  98. if Input.is_action_pressed("move_right"):
  99. velocity.x += 1
  100. if Input.is_action_pressed("move_left"):
  101. velocity.x -= 1
  102. if Input.is_action_pressed("move_down"):
  103. velocity.y += 1
  104. if Input.is_action_pressed("move_up"):
  105. velocity.y -= 1
  106. if velocity.length() > 0:
  107. velocity = velocity.normalized() * speed
  108. $AnimatedSprite2D.play()
  109. else:
  110. $AnimatedSprite2D.stop()
  111. .. code-tab:: csharp
  112. public override void _Process(double delta)
  113. {
  114. var velocity = Vector2.Zero; // The player's movement vector.
  115. if (Input.IsActionPressed("move_right"))
  116. {
  117. velocity.X += 1;
  118. }
  119. if (Input.IsActionPressed("move_left"))
  120. {
  121. velocity.X -= 1;
  122. }
  123. if (Input.IsActionPressed("move_down"))
  124. {
  125. velocity.Y += 1;
  126. }
  127. if (Input.IsActionPressed("move_up"))
  128. {
  129. velocity.Y -= 1;
  130. }
  131. var animatedSprite2D = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
  132. if (velocity.Length() > 0)
  133. {
  134. velocity = velocity.Normalized() * Speed;
  135. animatedSprite2D.Play();
  136. }
  137. else
  138. {
  139. animatedSprite2D.Stop();
  140. }
  141. }
  142. We start by setting the ``velocity`` to ``(0, 0)`` - by default, the player
  143. should not be moving. Then we check each input and add/subtract from the
  144. ``velocity`` to obtain a total direction. For example, if you hold ``right`` and
  145. ``down`` at the same time, the resulting ``velocity`` vector will be ``(1, 1)``.
  146. In this case, since we're adding a horizontal and a vertical movement, the
  147. player would move *faster* diagonally than if it just moved horizontally.
  148. We can prevent that if we *normalize* the velocity, which means we set its
  149. *length* to ``1``, then multiply by the desired speed. This means no more fast
  150. diagonal movement.
  151. .. tip:: If you've never used vector math before, or need a refresher, you can
  152. see an explanation of vector usage in Godot at :ref:`doc_vector_math`.
  153. It's good to know but won't be necessary for the rest of this tutorial.
  154. We also check whether the player is moving so we can call ``play()`` or
  155. ``stop()`` on the AnimatedSprite2D.
  156. .. tip:: ``$`` is shorthand for ``get_node()``. So in the code above,
  157. ``$AnimatedSprite2D.play()`` is the same as
  158. ``get_node("AnimatedSprite2D").play()``.
  159. In GDScript, ``$`` returns the node at the relative path from the
  160. current node, or returns ``null`` if the node is not found. Since
  161. AnimatedSprite2D is a child of the current node, we can use
  162. ``$AnimatedSprite2D``.
  163. Now that we have a movement direction, we can update the player's position. We
  164. can also use ``clamp()`` to prevent it from leaving the screen. *Clamping* a
  165. value means restricting it to a given range. Add the following to the bottom of
  166. the ``_process`` function (make sure it's not indented under the `else`):
  167. .. tabs::
  168. .. code-tab:: gdscript GDScript
  169. position += velocity * delta
  170. position = position.clamp(Vector2.ZERO, screen_size)
  171. .. code-tab:: csharp
  172. Position += velocity * (float)delta;
  173. Position = new Vector2(
  174. x: Mathf.Clamp(Position.X, 0, ScreenSize.X),
  175. y: Mathf.Clamp(Position.Y, 0, ScreenSize.Y)
  176. );
  177. .. tip:: The `delta` parameter in the `_process()` function refers to the *frame
  178. length* - the amount of time that the previous frame took to complete.
  179. Using this value ensures that your movement will remain consistent even
  180. if the frame rate changes.
  181. Click "Play Scene" (:kbd:`F6`, :kbd:`Cmd + R` on macOS) and confirm you can move
  182. the player around the screen in all directions.
  183. .. warning:: If you get an error in the "Debugger" panel that says
  184. ``Attempt to call function 'play' in base 'null instance' on a null
  185. instance``
  186. this likely means you spelled the name of the AnimatedSprite2D node
  187. wrong. Node names are case-sensitive and ``$NodeName`` must match
  188. the name you see in the scene tree.
  189. Choosing animations
  190. ~~~~~~~~~~~~~~~~~~~
  191. Now that the player can move, we need to change which animation the
  192. AnimatedSprite2D is playing based on its direction. We have the "walk" animation,
  193. which shows the player walking to the right. This animation should be flipped
  194. horizontally using the ``flip_h`` property for left movement. We also have the
  195. "up" animation, which should be flipped vertically with ``flip_v`` for downward
  196. movement. Let's place this code at the end of the ``_process()`` function:
  197. .. tabs::
  198. .. code-tab:: gdscript GDScript
  199. if velocity.x != 0:
  200. $AnimatedSprite2D.animation = "walk"
  201. $AnimatedSprite2D.flip_v = false
  202. # See the note below about boolean assignment.
  203. $AnimatedSprite2D.flip_h = velocity.x < 0
  204. elif velocity.y != 0:
  205. $AnimatedSprite2D.animation = "up"
  206. $AnimatedSprite2D.flip_v = velocity.y > 0
  207. .. code-tab:: csharp
  208. if (velocity.X != 0)
  209. {
  210. animatedSprite2D.Animation = "walk";
  211. animatedSprite2D.FlipV = false;
  212. // See the note below about boolean assignment.
  213. animatedSprite2D.FlipH = velocity.X < 0;
  214. }
  215. else if (velocity.Y != 0)
  216. {
  217. animatedSprite2D.Animation = "up";
  218. animatedSprite2D.FlipV = velocity.Y > 0;
  219. }
  220. .. Note:: The boolean assignments in the code above are a common shorthand for
  221. programmers. Since we're doing a comparison test (boolean) and also
  222. *assigning* a boolean value, we can do both at the same time. Consider
  223. this code versus the one-line boolean assignment above:
  224. .. tabs::
  225. .. code-tab :: gdscript GDScript
  226. if velocity.x < 0:
  227. $AnimatedSprite2D.flip_h = true
  228. else:
  229. $AnimatedSprite2D.flip_h = false
  230. .. code-tab:: csharp
  231. if (velocity.X < 0)
  232. {
  233. animatedSprite2D.FlipH = true;
  234. }
  235. else
  236. {
  237. animatedSprite2D.FlipH = false;
  238. }
  239. Play the scene again and check that the animations are correct in each of the
  240. directions.
  241. .. tip:: A common mistake here is to type the names of the animations wrong. The
  242. animation names in the SpriteFrames panel must match what you type in
  243. the code. If you named the animation ``"Walk"``, you must also use a
  244. capital "W" in the code.
  245. When you're sure the movement is working correctly, add this line to
  246. ``_ready()``, so the player will be hidden when the game starts:
  247. .. tabs::
  248. .. code-tab:: gdscript GDScript
  249. hide()
  250. .. code-tab:: csharp
  251. Hide();
  252. Preparing for collisions
  253. ~~~~~~~~~~~~~~~~~~~~~~~~
  254. We want ``Player`` to detect when it's hit by an enemy, but we haven't made any
  255. enemies yet! That's OK, because we're going to use Godot's *signal*
  256. functionality to make it work.
  257. Add the following at the top of the script. If you're using GDScript, add it after
  258. ``extends Area2D``. If you're using C#, add it after ``public partial class Player : Area2D``:
  259. .. tabs::
  260. .. code-tab:: gdscript GDScript
  261. signal hit
  262. .. code-tab:: csharp
  263. // Don't forget to rebuild the project so the editor knows about the new signal.
  264. [Signal]
  265. public delegate void HitEventHandler();
  266. This defines a custom signal called "hit" that we will have our player emit
  267. (send out) when it collides with an enemy. We will use ``Area2D`` to detect the
  268. collision. Select the ``Player`` node and click the "Node" tab next to the
  269. Inspector tab to see the list of signals the player can emit:
  270. .. image:: img/player_signals.webp
  271. Notice our custom "hit" signal is there as well! Since our enemies are going to
  272. be ``RigidBody2D`` nodes, we want the ``body_entered(body: Node2D)`` signal. This
  273. signal will be emitted when a body contacts the player. Click "Connect.." and
  274. the "Connect a Signal" window appears. We don't need to change any of these
  275. settings so click "Connect" again. Godot will automatically create a function in
  276. your player's script.
  277. .. image:: img/player_signal_connection.webp
  278. Note the green icon indicating that a signal is connected to this function. Add
  279. this code to the function:
  280. .. tabs::
  281. .. code-tab:: gdscript GDScript
  282. func _on_body_entered(body):
  283. hide() # Player disappears after being hit.
  284. hit.emit()
  285. # Must be deferred as we can't change physics properties on a physics callback.
  286. $CollisionShape2D.set_deferred("disabled", true)
  287. .. code-tab:: csharp
  288. private void OnBodyEntered(Node2D body)
  289. {
  290. Hide(); // Player disappears after being hit.
  291. EmitSignal(SignalName.Hit);
  292. // Must be deferred as we can't change physics properties on a physics callback.
  293. GetNode<CollisionShape2D>("CollisionShape2D").SetDeferred(CollisionShape2D.PropertyName.Disabled, true);
  294. }
  295. Each time an enemy hits the player, the signal is going to be emitted. We need
  296. to disable the player's collision so that we don't trigger the ``hit`` signal
  297. more than once.
  298. .. Note:: Disabling the area's collision shape can cause an error if it happens
  299. in the middle of the engine's collision processing. Using
  300. ``set_deferred()`` tells Godot to wait to disable the shape until it's
  301. safe to do so.
  302. The last piece is to add a function we can call to reset the player when
  303. starting a new game.
  304. .. tabs::
  305. .. code-tab:: gdscript GDScript
  306. func start(pos):
  307. position = pos
  308. show()
  309. $CollisionShape2D.disabled = false
  310. .. code-tab:: csharp
  311. public void Start(Vector2 position)
  312. {
  313. Position = position;
  314. Show();
  315. GetNode<CollisionShape2D>("CollisionShape2D").Disabled = false;
  316. }
  317. With the player working, we'll work on the enemy in the next lesson.