ui_code_a_life_bar.rst 23 KB

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