ui_code_a_life_bar.rst 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. Control the game's UI with code
  2. ===============================
  3. Intro
  4. -----
  5. In this tutorial you will connect a character to a life bar and animate
  6. the health loss.
  7. .. figure:: img/lifebar_tutorial_final_result.gif
  8. Here's what you'll create: the bar and the counter animate when
  9. the character takes a hit. They fade when it dies.
  10. Here's what you'll create: the bar and the counter animate when the
  11. character takes a hit. They fade when it dies.
  12. You will learn:
  13. - How to **connect** a character to a GUI with signals
  14. - How to **control** a GUI with GDscript
  15. - How to **animate** a life bar with the `Tween <#>`__ node
  16. .. warning::
  17. This tutorial relies on a recent build of Godot 3's master branch. You will find some differences with Godot 3 alpha 1, and some more changes might happen in Godot 3 beta. We'll adapt the page after the beta release.
  18. If you want to learn how to set up the interface instead, check out the
  19. step-by-step UI tutorials:
  20. - Create a main menu screen
  21. - Create a game user interface
  22. When you code a game, you want to build the core gameplay first: the
  23. main mechanics, player input, win and loss conditions. The UI comes a
  24. bit later. You want to keep all the elements that make up your project
  25. separate if possible. Each character should be in its own scene, with
  26. its own scripts, and so should the UI elements. This prevents bugs,
  27. keeps your project manageable, and allows different team members to work
  28. on different parts of the game.
  29. Once the core gameplay and the UI are ready, you'll need to connect them
  30. somehow. In our example, we have the Enemy who attacks the Player at
  31. constant time intervals. We want the life bar to update when the Player
  32. takes damage.
  33. To do this, we will use **signals**.
  34. .. note::
  35. Signals are Godot's version of the Observer pattern. They allow us to send out some message. Other nodes can connect to the object that **emits** the signal and receive the information. It's a powerful tool we use a lot for User Interface and achievement systems. You don't want to use them everywhere though. Connecting two nodes adds some coupling between them. When there's a lot of connections, they become hard to manage.
  36. For more information on check out the `signals video tutorial <https://youtu.be/l0BkQxF7X3E>`_ on GDquest.
  37. Download and explore the start project
  38. --------------------------------------
  39. Download the Godot project. It contains all the assets and scripts you
  40. need to get started. Extract the .zip archive to get two folders:
  41. - tutorial/ contains the start and end godot games for this tutorial
  42. - exercise/ lets you practice what you'll learn here by adding a new
  43. GUI element on your own. You'll find more on that at the bottom of
  44. the page
  45. Load the ``tutorial/start`` project in Godot. In the ``FileSystem`` dock
  46. double click on LevelMockup.tscn to open it. It's an RPG game's mockup
  47. where 2 characters face each other. The pink enemy attacks and damages
  48. the green square at regular time intervals, until its death. Feel free
  49. to try out the game: the basic combat mechanics already work. But as the
  50. character isn't connected to the life bar the ``GUI`` doesn't do
  51. anything.
  52. .. note::
  53. This is typical of how you'd code a game: you implement the core gameplay first, handle the player's death, and only then you'll add the interface. That's because the UI listens to what's happening in the game. So it can't work if other systems aren't in place yet.
  54. If you design the UI before you prototype and test the gameplay, chances are it won't work well and you'll have to re-create it from scratch.
  55. The scene contains a background sprite, a GUI, and two characters.
  56. .. figure:: img/lifebar_tutorial_life_bar_step_tut_LevelMockup_scene_tree.png
  57. The scene tree, with the GUI scene set to display its children
  58. The GUI scene encapsulates all of the Game User Interface. It comes with
  59. a barebones script where we get the path to nodes that exist inside the
  60. scene:
  61. ::
  62. onready var number_label = $Bars/LifeBar/Count/Background/Number
  63. onready var bar = $Bars/LifeBar/TextureProgress
  64. onready var tween = $Tween
  65. - ``number_label`` displays a life count as a number. It's a ``Label``
  66. node
  67. - ``bar`` is the life bar itself. It's a ``TextureProgress`` node
  68. - ``tween`` is a component-style node that can animate and control any
  69. value or method from any other node
  70. .. note::
  71. The project uses a simple organisation that works for game jams and tiny games.
  72. At the root of the project, in the `res://` folder, you will find the `LevelMockup`. That's the main game scene and the one we will work with. All the components that make up the game are in the `scenes/` folder. The `assets/` folder contains the game sprites and the font for the HP counter. In the `scripts/` folder you will find the enemy, the player, and the GUI controller scripts.
  73. Click the edit scene icon to the right of the node in the scene tree to open the scene in the editor. You'll see the LifeBar and EnergyBar are sub-scenes themselves. You can also right click on the `GUI` node and activate the `Editable Children` checkbox at the bottom of the drop-down menu.
  74. .. image:: img/lifebar_tutorial_Player_with_editable_children_on.png
  75. Set up the Lifebar with the Player's max\_health
  76. ------------------------------------------------
  77. We have to tell the GUI somehow what the player's current health is, to
  78. update the lifebar's texture, and to display the remaining health in the
  79. HP counter in the top left corner of the screen. To do this we send the
  80. player's health to the GUI every time he takes damage. The GUI will then
  81. update the ``Lifebar`` and ``Number`` nodes with this value.
  82. We could stop here to display the number, but we need to initialize the
  83. bar's ``max_value`` for it to update in the right proportions. The first
  84. step is thus to tell the ``GUI`` what the green character's
  85. ``max_health`` is.
  86. .. tip::
  87. The bar, a `TextureProgress`, has a `max_value` of `100` by default. If you don't need to display the character's health with a number, you don't need to change its `max_value` property. You send a percentage from the `Player` to the `GUI` instead: `health / max_health * 100`.
  88. .. image:: img/lifebar_tutorial_TextureProgress_default_max_value.png
  89. Click the script icon to the right of the ``GUI`` in the Scene dock to
  90. open its script. In the ``_ready`` function, we're going to store the
  91. ``Player``'s ``max_health`` in a new variable and use it to set the
  92. ``bar``'s ``max_value``:
  93. ::
  94. func _ready():
  95. var player_max_health = $"../Characters/Player".max_health
  96. bar.max_value = player_max_health
  97. Let's break it down. ``$"../Characters/Player"`` is a shorthand that
  98. goes one node up in the scene tree, and retrieves the
  99. ``Characters/Player`` node from there. It gives us access to the node.
  100. The second part of the statement, ``.max_health``, accesses the
  101. ``max_health`` on the Player node.
  102. The second line assigns this value to ``bar.max_value``. You could
  103. combine the two lines into one, but we'll need to use
  104. ``player_max_health`` again later in the tutorial.
  105. ``Player.gd`` sets the ``health`` to ``max_health`` at the start of the
  106. game, so we could work with this. Why do we still use ``max_health``?
  107. There are two reasons:
  108. 1. We don't have the guarantee that ``health`` will always equal
  109. ``max_health``: a future version of the game may load a level where
  110. the player already lost some health.
  111. 2. Because ``GUI`` is higher than ``Player`` in the scene tree, Godot
  112. will call its ``_ready`` function first. If we got the ``health``
  113. value then it would still be at ``0``.
  114. .. note::
  115. When you open a scene in the game, Godot creates nodes one by one, following the order in your Scene dock, from top to bottom. `GUI` and `Player` are not part of the same node branch. To make sure they both exist when we access each other, we have to use the `_ready` function. Godot calls `_ready` right after it loaded all nodes, before the game starts. It's the perfect function to set everything up and prepare the game session.
  116. Learn more about _ready: :doc:`scripting_continued`
  117. Update health with a signal when the player takes a hit
  118. -------------------------------------------------------
  119. Our GUI is ready to receive the ``health`` value updates from the
  120. ``Player``. To achieve this we're going to use **signals**.
  121. .. note::
  122. There are many useful built-in signals like `enter_tree` and `exit_tree`, that all nodes emit when they are respectively created and destroyed. You can also create your own using the `signal` keyword. On the `Player` node, you'll find two signals we created for you: `died` and `health_changed`.
  123. Why don't we directly get the ``Player`` node in the ``_process``
  124. function and look at the health value? Accessing nodes this way creates
  125. tight coupling between them. If you did it sparingly it may work. As
  126. your game grows bigger, you may have many more connections. If you get
  127. nodes from a bad it's becomes very complex very soon. Not only that: you
  128. need to listen to the changes state constantly in the ``_process``
  129. function. The check happens 60 times a second and you'll likely break
  130. the game because of the order in which the code runs.
  131. On a given frame you may look at another node's property *before* it was
  132. updated: you get a value that from the last frame. This leads to obscure
  133. bugs that are hard to fix. On the other hand, a signal is emitted right
  134. after a change happened. It **guarantees** you're getting a fresh piece
  135. of information. And you will update the state of your connected node
  136. *right after* the change happened.
  137. .. note::
  138. The Observer pattern, that signals derive from, still adds a bit of coupling between node branches. But it's generally lighter and more secure than accessing nodes directly to communicate between two separate classes. It can be okay for a parent node to get values from its children. But you'll want to favor signals if you're working with two separate branches.
  139. Read Game Programming Patterns for more information on the `Observer pattern <http://gameprogrammingpatterns.com/observer.html>`_.
  140. The `full book <http://gameprogrammingpatterns.com/contents.html>`_ is available online for free.
  141. With this in mind let's connect the ``GUI`` to the ``Player``. Click on
  142. the ``Player`` node in the scene dock to select it. Head down to the
  143. Inspector and click on the Node tab. This is the place to connect nodes
  144. to listen the one you selected.
  145. The first section lists custom signals defined in ``player.GD``:
  146. - ``died`` is emitted when the character just died. We will use it in a
  147. moment to hide the UI.
  148. - ``health_changed`` is emitted when the character got hit.
  149. .. figure:: img/lifebar_tutorial_health_changed_signal.png
  150. We're connecting to the took\_damage signal
  151. Select ``health_changed`` and click on the Connect button in the bottom
  152. right corner to open the Connect Signal window. On the left side you can
  153. pick the node that will listen to this signal. Select the ``GUI`` node.
  154. The right side of the screen lets you pack optional values with the
  155. signal. We already took care of it in ``player.GD``. In general I
  156. recommend not to add too many arguments using this window as they're
  157. less convenient than doing it from the code.
  158. .. figure:: img/lifebar_tutorial_connect_signal_window_health_changed.png
  159. The Connect Signal window with the GUI node selected
  160. .. tip::
  161. You can optionally connect nodes from the code. But doing it from the editor has two advantages:
  162. 1. Godot can write new callback functions for you in the connected script
  163. 1. An emitter icon appears next to the node that emits the signal in the Scene dock
  164. At the bottom of the window you will find the path to the node you
  165. selected. We're interested in the second row called "Method in Node".
  166. This is the method on the ``GUI`` node that gets called when the signal
  167. is emitted. This method receives the values sent with the signal and
  168. lets you process them. If you look to the right, there is a "Make
  169. Function" radio button that is on by default. Click the connect button
  170. at the bottom of the window. Godot creates the method inside the ``GUI``
  171. node. The script editor opens with the cursor inside a new
  172. ``_on_player_health_changed`` function.
  173. .. note::
  174. When you connect nodes from the editor, Godot generates a
  175. method name with the following pattern: ``_on_EmitterName_signal_name``.
  176. If you wrote the method already, the "Make Function" option will keep
  177. it. You may replace the name with anything you'd like.
  178. .. figure:: img/lifebar_tutorial_godot_generates_signal_callback.png
  179. Godot writes the callback method for you and takes you to it
  180. Inside the parens after the function name, add a ``player_health``
  181. argument. When the player emits the ``health_changed`` signal it will send
  182. its current ``health`` alongside it. Your code should look like:
  183. ::
  184. func _on_Player_health_changed(player_health):
  185. pass
  186. .. figure:: img/lifebar_tutorial_player_gd_emits_health_changed_code.png
  187. In Player.gd, when the Player emits the took\_damage signal, it also
  188. sends its health value
  189. Inside ``_on_Player_health_changed`` let's call a second function called
  190. ``update_health`` and pass it the ``player_health`` variable.
  191. .. note::
  192. We could directly update the health value on `LifeBar` and `Number`. There are two reasons to use this method instead:
  193. 1. The name makes it very clear for our future selves and teammates that when the player took damage, we update the health count on the GUI
  194. 2. We will reuse this method a bit later
  195. Create a new ``update_health`` method below ``_on_Player_health_changed``.
  196. It takes a new\_value as its only argument:
  197. ::
  198. func update_health(new_value):
  199. This method needs to:
  200. - set the ``Number`` node's ``text`` to ``new_value`` converted to a
  201. string
  202. - set the ``TextureProgress``'s ``value`` to ``new_value``
  203. ::
  204. func update_health(new_value):
  205. number_label.text = str(new_value)
  206. bar.value = new_value
  207. .. tip::
  208. ``str`` is a built-in function that converts about any value to
  209. text. ``Number``'s ``text`` property requires a string so we can't
  210. assign it to ``new_value`` directly
  211. Also call ``update_health`` at the end of the ``_ready`` function to
  212. initialize the ``Number`` node's ``text`` with the right value at the
  213. start of the game. Press F5 to test the game: the life bar update with
  214. every attack!
  215. .. figure:: img/lifebar_tutorial_LifeBar_health_update_no_anim.gif
  216. Both the Number node and the TextureProgress update when the Player
  217. takes a hit
  218. Animate the loss of life with the Tween node
  219. --------------------------------------------
  220. Our interface is functional, but it could use some animation. That's a
  221. good opportunity to introduce the ``Tween`` node, an essential tool to
  222. animate properties. ``Tween`` animates anything you'd like from a start
  223. to an end state over a certain duration. For example it can animate the
  224. health on the ``TextureProgress`` from its current level to the
  225. ``Player``'s new ``health`` when the character takes damage.
  226. The ``GUI`` scene already contains a ``Tween`` child node stored in the
  227. ``tween`` variable. Let's now use it. We have to make some changes to
  228. ``update_health``.
  229. We will use the ``Tween`` node's ``interpolate_property`` method. It
  230. takes seven arguments:
  231. 1. A reference to the node who owns the property to animate
  232. 2. The property's identifier as a string
  233. 3. The starting value
  234. 4. The end value
  235. 5. The animation's duration in seconds
  236. 6. The type of the transition
  237. 7. The easing to use in combination with the equation.
  238. The last two arguments combined correspond to an `easing
  239. equation <#>`__. This controls how the value evolves from the start to
  240. the end point.
  241. Click the script icon next to the ``GUI`` node to open it again. The
  242. ``Number`` node needs text to update itself, and the ``Bar`` needs a
  243. float or an integer. We can use ``interpolate_property`` to animate a
  244. number, but not to animate text directly. We're going to use it to
  245. animate a new ``GUI`` variable named ``animated_health``.
  246. At the top of the script, define a new variable and name it
  247. ``animated_health``. Navigate back to the ``update_health`` method and
  248. clear its content. Let's animate the ``animated_health`` value. Call the
  249. ``Tween`` node's ``interpolate_property`` method:
  250. ::
  251. func update_health(new_value):
  252. tween.interpolate_property(self, "animated_health", animated_health, new_value, 0.6, Tween.TRANS_LINEAR, Tween.EASE_IN)
  253. Let's break down the call:
  254. ::
  255. tween.interpolate_property(self, "animated_health", ...
  256. We target ``animated_health`` on ``self``, that is to say the ``GUI``
  257. node. ``Tween``'s interpolate\_property takes the property's name as a
  258. string. That's why we write it as ``"animated_health"``.
  259. ::
  260. ... _health", animated_health, new_value, 0.6 ...
  261. The starting point is the current value the bar's at. We still have to
  262. code this part, but it's going to be ``animated_health``. The end point
  263. of the animation is the ``Player``'s ``health`` after he
  264. ``health_changed``: that's ``new_value``. And ``0.6`` is the animation's
  265. duration in seconds.
  266. ::
  267. ... 0.6, tween.TRANS_LINEAR, Tween.EASE_IN)
  268. The last two arguments are constants from the ``Tween`` class.
  269. ``TRANS_LINEAR`` means the animation should be linear. ``EASE_IN``
  270. doesn't do anything with a linear transition, but we must provide this
  271. last argument or we'll get an error.
  272. The animation will not play until we activated the ``Tween`` node with
  273. ``tween.start()``. We only have to do this once if the node is not
  274. active. Add this code after the last line:
  275. ::
  276. if not tween.is_active():
  277. tween.start()
  278. .. note::
  279. Although we could animate the `health` property on the `Player`, we really shouldn't. Characters should lose life instantly when they get hit. It makes it a lot easier to manage their state, like to know when one died. You always want to store animations in a separate data container or node. The `tween` node is perfect for code-controlled animations. For hand-made animations, check out `AnimationPlayer`.
  280. Assign the animated\_health to the LifeBar
  281. ------------------------------------------
  282. Now the ``animated_health`` variable animates but we don't update the
  283. actual ``Bar`` and ``Number`` nodes anymore. Let's fix this.
  284. So far, the update\_health method looks like this:
  285. ::
  286. func update_health(new_value):
  287. Tween.interpolate_property(self, "animated_health", animated_health, new_value, 0.6, Tween.TRANS_LINEAR, Tween.EASE_IN)
  288. if not Tween.is_active():
  289. Tween.start()
  290. In this specific case, because ``number_label`` takes text, we need to
  291. use the ``_process`` method to animate it. Let's now update the
  292. ``Number`` and ``TextureProgress`` nodes like before, inside of
  293. ``_process``:
  294. ::
  295. func _process(delta):
  296. number_label.text = str(animated_health)
  297. bar.value = animated_health
  298. .. note::
  299. `number_label` and `bar` are variables that store references to the `Number` and `TextureProgress` nodes.
  300. Play the game to see the bar animate smoothly. But the text displays
  301. decimal number and looks like a mess. And considering the style of the
  302. game, it'd be nice for the life bar to animate in a choppier fashion.
  303. .. figure:: img/lifebar_tutorial_number_animation_messed_up.gif
  304. The animation is smooth but the number is broken
  305. We can fix both problems by rounding out ``animated_health``. Use a
  306. local variable named ``round_value`` to store the rounded
  307. ``animated_health``. Then assign it to ``number_label.text`` and
  308. ``bar.value``:
  309. ::
  310. func _process(delta):
  311. var round_value = round(animated_health)
  312. number_label.text = str(round_value)
  313. bar.value = round_value
  314. Try the game again to see a nice blocky animation.
  315. .. figure:: img/lifebar_tutorial_number_animation_working.gif
  316. By rounding out animated\_health we hit two birds with one stone
  317. .. tip:
  318. ::
  319. Every time the player takes a hit, the `GUI` calls `_on_Player_health_changed`, which in turn calls `update_health`. This updates the animation and the `number_label` and `bar` follow in `_process`.
  320. The animated life bar that shows the health going down gradually is just a trick. It makes the GUI feel alive. If the `Player` takes 3 damage, it happens in an instant.
  321. Fade the bar when the Player dies
  322. ---------------------------------
  323. When the green character dies, it plays a death animation and fades out.
  324. At this point, we shouldn't show the interface anymore. Let's fade the
  325. bar as well when the character died. We will reuse the same ``Tween``
  326. node as it manages multiple animations in parallel for us.
  327. First, the ``GUI`` needs to connect to the ``Player``'s ``died`` signal
  328. to know when it just died. Press :kbd:``F1`` to jump back to the 2D
  329. Workspace. Select the ``Player`` node in the Scene dock and click on the
  330. Node tab next to the Inspector.
  331. Find the ``died`` signal, select it, and click the Connect button.
  332. .. figure:: img/lifebar_tutorial_player_died_signal_enemy_connected.png
  333. The signal should already have the Enemy connected to it
  334. In the Connecting Signal window, connect to the ``GUI`` node again. The
  335. Path to Node should be ``../../GUI`` and the Method in Node should show
  336. ``_on_Player_died``. Leave the Make Function option on and click Connect
  337. at the bottom of the window. This will take you to the ``GUI.gd`` file
  338. in the Script Workspace.
  339. .. figure:: img/lifebar_tutorial_player_died_connecting_signal_window.png
  340. You should get these values in the Connecting Signal window
  341. .. note::
  342. You should see a pattern by now: every time the GUI needs a new piece of information, we emit a new signal. Use them wisely: the more connections you add, the harder they are to track.
  343. To animate a fade on a UI element, we have to use its ``modulate``
  344. property. ``modulate`` is a ``Color`` that multiplies the colors of our
  345. textures.
  346. .. note::
  347. `modulate` comes from the `CanvasItem` class, All 2D and UI nodes inherit from it. It lets you toggle the visibility of the node, assign a shader to it, and modify it using a color with `modulate`.
  348. ``modulate`` takes a ``Color`` value with 4 channels: red, green, blue
  349. and alpha. If we darken any of the first three channels it darkens the
  350. interface. If we lower the alpha channel our interface fades out.
  351. We're going to tween between two color values: from a white with an
  352. alpha of ``1``, that is to say at full opacity, to a pure white with an
  353. alpha value of ``0``, completely transparent. Let's add two variables at
  354. the top of the ``_on_Player_died`` method and name them ``start_color``
  355. and ``end_color``. Use the ``Color()`` constructor to build two
  356. ``Color`` values.
  357. ::
  358. func _on_Player_died():
  359. var start_color = Color(1.0, 1.0, 1.0, 1.0)
  360. var end_color = Color(1.0, 1.0, 1.0, 0.0)
  361. ``Color(1.0, 1.0, 1.0)`` corresponds to white. The fourth argument,
  362. respectively ``1.0`` and ``0.0`` in ``start_color`` and ``end_color``,
  363. is the alpha channel.
  364. We then have to call the ``interpolate_property`` method of the
  365. ``Tween`` node again:
  366. ::
  367. Tween.interpolate_property(self, "modulate", start_color, end_color, 1.0, Tween.TRANS_LINEAR, Tween.EASE_IN)
  368. This time we change the ``modulate`` property and have it animate from
  369. ``start_color`` to the ``end_color``. The duration is of one second,
  370. with a linear transition. Here again, because the transition is linear,
  371. the easing does not matter. Here's the complete ``_on_Player_died``
  372. method:
  373. ::
  374. func _on_Player_died():
  375. var start_color = Color(1.0, 1.0, 1.0, 1.0)
  376. var end_color = Color(1.0, 1.0, 1.0, 0.0)
  377. tween.interpolate_property(self, "modulate", start_color, end_color, 1.0, Tween.TRANS_LINEAR, Tween.EASE_IN)
  378. And that is it. You may now play the game to see the final result!
  379. .. figure:: img/lifebar_tutorial_final_result.gif
  380. The final result. Congratulations for getting there!
  381. .. note::
  382. Using the exact same techniques, you can change the color of the bar when the Player gets poisoned, turn the bar red when its health drops low, shake the UI when he takes a critical hit... the principle is the same: emit a signal to forward the information from the `Player` to the `GUI` and let the `GUI` process it.
  383. .. raw:: html
  384. <!-- ## Exercise: Add the stamina bar -->
  385. .. raw:: html
  386. <!-- Use exercise/start and exercise/end -->
  387. .. raw:: html
  388. <!-- TODO: DEMO: add stamina management code in the exercise version of the project -->