03.coding_the_player.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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.png
  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.png
  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. using System;
  26. public class Player : Area2D
  27. {
  28. [Export]
  29. public int Speed = 400; // How fast the player will move (pixels/sec).
  30. public Vector2 ScreenSize; // Size of the game window.
  31. }
  32. .. code-tab:: cpp
  33. // A `player.gdns` file has already been created for you. Attach it to the Player node.
  34. // Create two files `player.cpp` and `player.hpp` next to `entry.cpp` in `src`.
  35. // This code goes in `player.hpp`. We also define the methods we'll be using here.
  36. #ifndef PLAYER_H
  37. #define PLAYER_H
  38. #include <AnimatedSprite.hpp>
  39. #include <Area2D.hpp>
  40. #include <CollisionShape2D.hpp>
  41. #include <Godot.hpp>
  42. #include <Input.hpp>
  43. class Player : public godot::Area2D {
  44. GODOT_CLASS(Player, godot::Area2D)
  45. godot::AnimatedSprite *_animated_sprite;
  46. godot::CollisionShape2D *_collision_shape;
  47. godot::Input *_input;
  48. godot::Vector2 _screen_size; // Size of the game window.
  49. public:
  50. real_t speed = 400; // How fast the player will move (pixels/sec).
  51. void _init() {}
  52. void _ready();
  53. void _process(const double p_delta);
  54. void start(const godot::Vector2 p_position);
  55. void _on_Player_body_entered(godot::Node2D *_body);
  56. static void _register_methods();
  57. };
  58. #endif // PLAYER_H
  59. Using the ``export`` keyword on the first variable ``speed`` allows us to set
  60. its value in the Inspector. This can be handy for values that you want to be
  61. able to adjust just like a node's built-in properties. Click on the ``Player``
  62. node and you'll see the property now appears in the "Script Variables" section
  63. of the Inspector. Remember, if you change the value here, it will override the
  64. value written in the script.
  65. .. warning:: If you're using C#, you need to (re)build the project assemblies
  66. whenever you want to see new export variables or signals. This
  67. build can be manually triggered by clicking the word "Mono" at the
  68. bottom of the editor window to reveal the Mono Panel, then clicking
  69. the "Build Project" button.
  70. .. image:: img/export_variable.png
  71. The ``_ready()`` function is called when a node enters the scene tree, which is
  72. a good time to find the size of the game window:
  73. .. tabs::
  74. .. code-tab:: gdscript GDScript
  75. func _ready():
  76. screen_size = get_viewport_rect().size
  77. .. code-tab:: csharp
  78. public override void _Ready()
  79. {
  80. ScreenSize = GetViewportRect().Size;
  81. }
  82. .. code-tab:: cpp
  83. // This code goes in `player.cpp`.
  84. #include "player.hpp"
  85. void Player::_ready() {
  86. _animated_sprite = get_node<godot::AnimatedSprite>("AnimatedSprite");
  87. _collision_shape = get_node<godot::CollisionShape2D>("CollisionShape2D");
  88. _input = godot::Input::get_singleton();
  89. _screen_size = get_viewport_rect().size;
  90. }
  91. Now we can use the ``_process()`` function to define what the player will do.
  92. ``_process()`` is called every frame, so we'll use it to update elements of our
  93. game, which we expect will change often. For the player, we need to do the
  94. following:
  95. - Check for input.
  96. - Move in the given direction.
  97. - Play the appropriate animation.
  98. First, we need to check for input - is the player pressing a key? For this game,
  99. we have 4 direction inputs to check. Input actions are defined in the Project
  100. Settings under "Input Map". Here, you can define custom events and assign
  101. different keys, mouse events, or other inputs to them. For this game, we will
  102. map the arrow keys to the four directions.
  103. Click on *Project -> Project Settings* to open the project settings window and
  104. click on the *Input Map* tab at the top. Type "move_right" in the top bar and
  105. click the "Add" button to add the ``move_right`` action.
  106. .. image:: img/input-mapping-add-action.png
  107. We need to assign a key to this action. Click the "+" icon on the right, then
  108. click the "Key" option in the drop-down menu. A dialog asks you to type in the
  109. desired key. Press the right arrow on your keyboard and click "Ok".
  110. .. image:: img/input-mapping-add-key.png
  111. Repeat these steps to add three more mappings:
  112. 1. ``move_left`` mapped to the left arrow key.
  113. 2. ``move_up`` mapped to the up arrow key.
  114. 3. And ``move_down`` mapped to the down arrow key.
  115. Your input map tab should look like this:
  116. .. image:: img/input-mapping-completed.png
  117. Click the "Close" button to close the project settings.
  118. .. note::
  119. We only mapped one key to each input action, but you can map multiple keys,
  120. joystick buttons, or mouse buttons to the same input action.
  121. You can detect whether a key is pressed using ``Input.is_action_pressed()``,
  122. which returns ``true`` if it's pressed or ``false`` if it isn't.
  123. .. tabs::
  124. .. code-tab:: gdscript GDScript
  125. func _process(delta):
  126. var velocity = Vector2.ZERO # The player's movement vector.
  127. if Input.is_action_pressed("move_right"):
  128. velocity.x += 1
  129. if Input.is_action_pressed("move_left"):
  130. velocity.x -= 1
  131. if Input.is_action_pressed("move_down"):
  132. velocity.y += 1
  133. if Input.is_action_pressed("move_up"):
  134. velocity.y -= 1
  135. if velocity.length() > 0:
  136. velocity = velocity.normalized() * speed
  137. $AnimatedSprite.play()
  138. else:
  139. $AnimatedSprite.stop()
  140. .. code-tab:: csharp
  141. public override void _Process(float delta)
  142. {
  143. var velocity = Vector2.Zero; // The player's movement vector.
  144. if (Input.IsActionPressed("move_right"))
  145. {
  146. velocity.x += 1;
  147. }
  148. if (Input.IsActionPressed("move_left"))
  149. {
  150. velocity.x -= 1;
  151. }
  152. if (Input.IsActionPressed("move_down"))
  153. {
  154. velocity.y += 1;
  155. }
  156. if (Input.IsActionPressed("move_up"))
  157. {
  158. velocity.y -= 1;
  159. }
  160. var animatedSprite = GetNode<AnimatedSprite>("AnimatedSprite");
  161. if (velocity.Length() > 0)
  162. {
  163. velocity = velocity.Normalized() * Speed;
  164. animatedSprite.Play();
  165. }
  166. else
  167. {
  168. animatedSprite.Stop();
  169. }
  170. }
  171. .. code-tab:: cpp
  172. // This code goes in `player.cpp`.
  173. void Player::_process(const double p_delta) {
  174. godot::Vector2 velocity(0, 0);
  175. velocity.x = _input->get_action_strength("move_right") - _input->get_action_strength("move_left");
  176. velocity.y = _input->get_action_strength("move_down") - _input->get_action_strength("move_up");
  177. if (velocity.length() > 0) {
  178. velocity = velocity.normalized() * speed;
  179. _animated_sprite->play();
  180. } else {
  181. _animated_sprite->stop();
  182. }
  183. }
  184. We start by setting the ``velocity`` to ``(0, 0)`` - by default, the player
  185. should not be moving. Then we check each input and add/subtract from the
  186. ``velocity`` to obtain a total direction. For example, if you hold ``right`` and
  187. ``down`` at the same time, the resulting ``velocity`` vector will be ``(1, 1)``.
  188. In this case, since we're adding a horizontal and a vertical movement, the
  189. player would move *faster* diagonally than if it just moved horizontally.
  190. We can prevent that if we *normalize* the velocity, which means we set its
  191. *length* to ``1``, then multiply by the desired speed. This means no more fast
  192. diagonal movement.
  193. .. tip:: If you've never used vector math before, or need a refresher, you can
  194. see an explanation of vector usage in Godot at :ref:`doc_vector_math`.
  195. It's good to know but won't be necessary for the rest of this tutorial.
  196. We also check whether the player is moving so we can call ``play()`` or
  197. ``stop()`` on the AnimatedSprite.
  198. .. tip:: ``$`` is shorthand for ``get_node()``. So in the code above,
  199. ``$AnimatedSprite.play()`` is the same as
  200. ``get_node("AnimatedSprite").play()``.
  201. In GDScript, ``$`` returns the node at the relative path from the
  202. current node, or returns ``null`` if the node is not found. Since
  203. AnimatedSprite is a child of the current node, we can use
  204. ``$AnimatedSprite``.
  205. Now that we have a movement direction, we can update the player's position. We
  206. can also use ``clamp()`` to prevent it from leaving the screen. *Clamping* a
  207. value means restricting it to a given range. Add the following to the bottom of
  208. the ``_process`` function (make sure it's not indented under the `else`):
  209. .. tabs::
  210. .. code-tab:: gdscript GDScript
  211. position += velocity * delta
  212. position.x = clamp(position.x, 0, screen_size.x)
  213. position.y = clamp(position.y, 0, screen_size.y)
  214. .. code-tab:: csharp
  215. Position += velocity * delta;
  216. Position = new Vector2(
  217. x: Mathf.Clamp(Position.x, 0, ScreenSize.x),
  218. y: Mathf.Clamp(Position.y, 0, ScreenSize.y)
  219. );
  220. .. code-tab:: cpp
  221. godot::Vector2 position = get_position();
  222. position += velocity * (real_t)p_delta;
  223. position.x = godot::Math::clamp(position.x, (real_t)0.0, _screen_size.x);
  224. position.y = godot::Math::clamp(position.y, (real_t)0.0, _screen_size.y);
  225. set_position(position);
  226. .. tip:: The `delta` parameter in the `_process()` function refers to the *frame
  227. length* - the amount of time that the previous frame took to complete.
  228. Using this value ensures that your movement will remain consistent even
  229. if the frame rate changes.
  230. Click "Play Scene" (:kbd:`F6`, :kbd:`Cmd + R` on macOS) and confirm you can move
  231. the player around the screen in all directions.
  232. .. warning:: If you get an error in the "Debugger" panel that says
  233. ``Attempt to call function 'play' in base 'null instance' on a null
  234. instance``
  235. this likely means you spelled the name of the AnimatedSprite node
  236. wrong. Node names are case-sensitive and ``$NodeName`` must match
  237. the name you see in the scene tree.
  238. Choosing animations
  239. ~~~~~~~~~~~~~~~~~~~
  240. Now that the player can move, we need to change which animation the
  241. AnimatedSprite is playing based on its direction. We have the "walk" animation,
  242. which shows the player walking to the right. This animation should be flipped
  243. horizontally using the ``flip_h`` property for left movement. We also have the
  244. "up" animation, which should be flipped vertically with ``flip_v`` for downward
  245. movement. Let's place this code at the end of the ``_process()`` function:
  246. .. tabs::
  247. .. code-tab:: gdscript GDScript
  248. if velocity.x != 0:
  249. $AnimatedSprite.animation = "walk"
  250. $AnimatedSprite.flip_v = false
  251. # See the note below about boolean assignment.
  252. $AnimatedSprite.flip_h = velocity.x < 0
  253. elif velocity.y != 0:
  254. $AnimatedSprite.animation = "up"
  255. $AnimatedSprite.flip_v = velocity.y > 0
  256. .. code-tab:: csharp
  257. if (velocity.x != 0)
  258. {
  259. animatedSprite.Animation = "walk";
  260. animatedSprite.FlipV = false;
  261. // See the note below about boolean assignment.
  262. animatedSprite.FlipH = velocity.x < 0;
  263. }
  264. else if (velocity.y != 0)
  265. {
  266. animatedSprite.Animation = "up";
  267. animatedSprite.FlipV = velocity.y > 0;
  268. }
  269. .. code-tab:: cpp
  270. if (velocity.x != 0) {
  271. _animated_sprite->set_animation("walk");
  272. _animated_sprite->set_flip_v(false);
  273. // See the note below about boolean assignment.
  274. _animated_sprite->set_flip_h(velocity.x < 0);
  275. } else if (velocity.y != 0) {
  276. _animated_sprite->set_animation("up");
  277. _animated_sprite->set_flip_v(velocity.y > 0);
  278. }
  279. .. Note:: The boolean assignments in the code above are a common shorthand for
  280. programmers. Since we're doing a comparison test (boolean) and also
  281. *assigning* a boolean value, we can do both at the same time. Consider
  282. this code versus the one-line boolean assignment above:
  283. .. tabs::
  284. .. code-tab :: gdscript GDScript
  285. if velocity.x < 0:
  286. $AnimatedSprite.flip_h = true
  287. else:
  288. $AnimatedSprite.flip_h = false
  289. .. code-tab:: csharp
  290. if (velocity.x < 0)
  291. {
  292. animatedSprite.FlipH = true;
  293. }
  294. else
  295. {
  296. animatedSprite.FlipH = false;
  297. }
  298. Play the scene again and check that the animations are correct in each of the
  299. directions.
  300. .. tip:: A common mistake here is to type the names of the animations wrong. The
  301. animation names in the SpriteFrames panel must match what you type in
  302. the code. If you named the animation ``"Walk"``, you must also use a
  303. capital "W" in the code.
  304. When you're sure the movement is working correctly, add this line to
  305. ``_ready()``, so the player will be hidden when the game starts:
  306. .. tabs::
  307. .. code-tab:: gdscript GDScript
  308. hide()
  309. .. code-tab:: csharp
  310. Hide();
  311. .. code-tab:: cpp
  312. hide();
  313. Preparing for collisions
  314. ~~~~~~~~~~~~~~~~~~~~~~~~
  315. We want ``Player`` to detect when it's hit by an enemy, but we haven't made any
  316. enemies yet! That's OK, because we're going to use Godot's *signal*
  317. functionality to make it work.
  318. Add the following at the top of the script, after ``extends Area2D``:
  319. .. tabs::
  320. .. code-tab:: gdscript GDScript
  321. signal hit
  322. .. code-tab:: csharp
  323. // Don't forget to rebuild the project so the editor knows about the new signal.
  324. [Signal]
  325. public delegate void Hit();
  326. .. code-tab:: cpp
  327. // This code goes in `player.cpp`.
  328. // We need to register the signal here, and while we're here, we can also
  329. // register the other methods and register the speed property.
  330. void Player::_register_methods() {
  331. godot::register_method("_ready", &Player::_ready);
  332. godot::register_method("_process", &Player::_process);
  333. godot::register_method("start", &Player::start);
  334. godot::register_method("_on_Player_body_entered", &Player::_on_Player_body_entered);
  335. godot::register_property("speed", &Player::speed, (real_t)400.0);
  336. // This below line is the signal.
  337. godot::register_signal<Player>("hit", godot::Dictionary());
  338. }
  339. This defines a custom signal called "hit" that we will have our player emit
  340. (send out) when it collides with an enemy. We will use ``Area2D`` to detect the
  341. collision. Select the ``Player`` node and click the "Node" tab next to the
  342. Inspector tab to see the list of signals the player can emit:
  343. .. image:: img/player_signals.png
  344. Notice our custom "hit" signal is there as well! Since our enemies are going to
  345. be ``RigidBody2D`` nodes, we want the ``body_entered(body: Node)`` signal. This
  346. signal will be emitted when a body contacts the player. Click "Connect.." and
  347. the "Connect a Signal" window appears. We don't need to change any of these
  348. settings so click "Connect" again. Godot will automatically create a function in
  349. your player's script.
  350. .. image:: img/player_signal_connection.png
  351. Note the green icon indicating that a signal is connected to this function. Add
  352. this code to the function:
  353. .. tabs::
  354. .. code-tab:: gdscript GDScript
  355. func _on_Player_body_entered(body):
  356. hide() # Player disappears after being hit.
  357. emit_signal("hit")
  358. # Must be deferred as we can't change physics properties on a physics callback.
  359. $CollisionShape2D.set_deferred("disabled", true)
  360. .. code-tab:: csharp
  361. public void OnPlayerBodyEntered(PhysicsBody2D body)
  362. {
  363. Hide(); // Player disappears after being hit.
  364. EmitSignal(nameof(Hit));
  365. // Must be deferred as we can't change physics properties on a physics callback.
  366. GetNode<CollisionShape2D>("CollisionShape2D").SetDeferred("disabled", true);
  367. }
  368. .. code-tab:: cpp
  369. // This code goes in `player.cpp`.
  370. void Player::_on_Player_body_entered(godot::Node2D *_body) {
  371. hide(); // Player disappears after being hit.
  372. emit_signal("hit");
  373. // Must be deferred as we can't change physics properties on a physics callback.
  374. _collision_shape->set_deferred("disabled", true);
  375. }
  376. Each time an enemy hits the player, the signal is going to be emitted. We need
  377. to disable the player's collision so that we don't trigger the ``hit`` signal
  378. more than once.
  379. .. Note:: Disabling the area's collision shape can cause an error if it happens
  380. in the middle of the engine's collision processing. Using
  381. ``set_deferred()`` tells Godot to wait to disable the shape until it's
  382. safe to do so.
  383. The last piece is to add a function we can call to reset the player when
  384. starting a new game.
  385. .. tabs::
  386. .. code-tab:: gdscript GDScript
  387. func start(pos):
  388. position = pos
  389. show()
  390. $CollisionShape2D.disabled = false
  391. .. code-tab:: csharp
  392. public void Start(Vector2 pos)
  393. {
  394. Position = pos;
  395. Show();
  396. GetNode<CollisionShape2D>("CollisionShape2D").Disabled = false;
  397. }
  398. .. code-tab:: cpp
  399. // This code goes in `player.cpp`.
  400. void Player::start(const godot::Vector2 p_position) {
  401. set_position(p_position);
  402. show();
  403. _collision_shape->set_disabled(false);
  404. }
  405. With the player working, we'll work on the enemy in the next lesson.