your_first_game.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. .. _doc_your_first_game:
  2. Your First Game
  3. ===============
  4. Overview
  5. --------
  6. This tutorial will guide you through making your first Godot Engine
  7. project. You will learn how the Godot Engine editor works, how to structure
  8. a project, and how to build a 2D game.
  9. .. note:: This project is an introduction to the Godot Engine. It
  10. assumes that you have some programming experience already. If
  11. you're new to programming entirely, you should start here:
  12. :ref:`doc_scripting`.
  13. The game is called *"Dodge the Creeps"*. Your character must move and
  14. avoid the enemies for as long as possible. Here is a preview of the
  15. final result:
  16. .. image:: img/dodge_preview.gif
  17. **Why 2D?**
  18. 3D games are much more complex than 2D ones. You should stick to 2D
  19. until you have a good understanding of the game development process.
  20. Project Setup
  21. -------------
  22. Launch Godot and create a new project. Then, download
  23. :download:`dodge_assets.zip <files/dodge_assets.zip>` - the images and sounds you'll be
  24. using to make the game. Unzip these files in your new project folder.
  25. .. note:: For this tutorial, we will assume you are already familiar with the
  26. Godot Engine editor. If you haven't read :ref:`doc_scenes_and_nodes`, do so now
  27. for an explanation of setting up a project and using the editor.
  28. This game will use "portrait" mode, so we need to adjust the size of the
  29. game window. Click on Project -> Project Settings -> Display -> Window and
  30. set ``Width`` to ``480`` and ``Height`` to ``720``.
  31. Organizing the Project
  32. ~~~~~~~~~~~~~~~~~~~~~~
  33. In this project, we will make 3 independent scenes: ``Player``,
  34. ``Mob``, and ``HUD``, which we will combine into the game's ``Main``
  35. scene. In a larger project, it might be useful to make folders to hold
  36. the various scenes and their scripts, but for this relatively small
  37. game, you can save your scenes and scripts in the root folder, which is
  38. referred to as ``res://``. You can see your project folders in the Filesystem
  39. Dock in the upper left corner:
  40. .. image:: img/filesystem_dock.png
  41. Player Scene
  42. ------------
  43. The first scene we make defines the "Player" object. One of the benefits
  44. of creating a separate Player scene is that we can test it separately, even
  45. before we've created the other parts of the game.
  46. Node Structure
  47. ~~~~~~~~~~~~~~
  48. To begin, click the "Add/Create a New Node" button and add an :ref:`Area2D <class_Area2D>`
  49. node to the scene.
  50. .. image:: img/add_node.png
  51. With ``Area2D`` we can detect other objects that overlap or run into the player.
  52. Change its name to ``Player``. This is the scene's "root" or top-level node.
  53. We can add additional nodes to the player to add functionality.
  54. Save the scene (click Scene -> Save, or press ``Meta-s``).
  55. .. note:: In this project, we will be following the Godot Engine naming
  56. conventions. Classes (Nodes) use ``CapWords``, variables and
  57. functions use ``snake_case``, and constants use ``ALL_CAPS``.
  58. Sprite Animation
  59. ~~~~~~~~~~~~~~~~
  60. Click on the ``Player`` node and add an :ref:`AnimatedSprite <class_AnimatedSprite>` node as a
  61. child. The ``AnimatedSprite`` will handle the appearance and animations
  62. for our player. Notice that there is a warning symbol next to the node.
  63. An ``AnimatedSprite`` requires a :ref:`SpriteFrames <class_SpriteFrames>` resource, which is a
  64. list of the animation(s) it can display. To create one, find the
  65. ``Frames`` property in the Inspector and click "<null>" ->
  66. "New SpriteFrames". Next, in the same location, click
  67. ``<SpriteFrames>`` to open the "SpriteFrames" panel:
  68. .. image:: img/spriteframes_panel.png
  69. On the left is a list of animations. Click the "default" one and rename
  70. it to "right". Then click the "Add" button to create a second animation
  71. named "up". Drag the two images for each animation into "Animation
  72. Frames" side of the panel:
  73. .. image:: img/spriteframes_panel2.png
  74. Finally, add a :ref:`CollisionShape2D <class_CollisionShape2D>` as a child
  75. of the ``Player``. This will determine the player's "hitbox", or the
  76. bounds of its collision area. For this character, a ``CapsuleShape2D``
  77. gives the best fit, so next to "Shape" in the Inspector, click
  78. "<null>"" -> "New CapsuleShape2D". Resize the shape to cover the sprite:
  79. .. image:: img/player_coll_shape.png
  80. .. warning:: Remember not to scale the shape's outline! Only use the
  81. size handles (red) to adjust the shape!
  82. When you're finished, your ``Player`` scene should look like this:
  83. .. image:: img/player_scene_nodes.png
  84. Moving the Player
  85. ~~~~~~~~~~~~~~~~~
  86. Now we need to add some functionality that we can't get from a built-in
  87. node, so we'll add a script. Click the ``Player`` node and click the
  88. "Add Script" button:
  89. .. image:: img/add_script_button.png
  90. In the script settings window, you can leave the default settings, just
  91. click "Create":
  92. .. image:: img/attach_node_window.png
  93. .. note:: If this is your first time encountering GDScript please read
  94. :ref:`doc_scripting` first.
  95. Start by declaring the member variables this object will need:
  96. ::
  97. extends Area2D
  98. var SPEED = 400 # how fast the player will move (pixels/sec)
  99. var velocity = Vector2() # the player's movement vector
  100. var screensize # size of the game window
  101. The ``_ready()`` function is called when a node enters the scene tree, so
  102. that's a good time to find the size of the game window:
  103. ::
  104. func _ready():
  105. hide()
  106. screensize = get_viewport_rect().size
  107. Now we can use the ``_process()`` function to define what the player will do.
  108. The ``_process()`` function is called on every frame, so we'll use it to update
  109. elements of our game which we expect to be changing often. Here we'll have it:
  110. - check for input
  111. - move in the given direction
  112. - play the appropriate animation.
  113. First, we need to check the inputs - is the player pressing a key? For
  114. this game, we have 4 direction inputs to check. Input actions are defined
  115. in the Project Settings under "Input Map". You can define custom events and
  116. assign different keys, mouse events, or other inputs to them. For this demo,
  117. we will use the default events that are assigned to the arrow keys on the
  118. keyboard.
  119. You can detect whether a key is pressed using
  120. ``Input.is_action_pressed()``, which returns ``true`` if it is pressed
  121. or ``false`` if it isn't.
  122. ::
  123. func _process(delta):
  124. velocity = Vector2()
  125. if Input.is_action_pressed("ui_right"):
  126. velocity.x += 1
  127. if Input.is_action_pressed("ui_left"):
  128. velocity.x -= 1
  129. if Input.is_action_pressed("ui_down"):
  130. velocity.y += 1
  131. if Input.is_action_pressed("ui_up"):
  132. velocity.y -= 1
  133. if velocity.length() > 0:
  134. velocity = velocity.normalized() * SPEED
  135. $AnimatedSprite.play()
  136. else:
  137. $AnimatedSprite.stop()
  138. We check each input and add/subtract from the ``velocity`` to obtain a
  139. total direction. For example, if you hold ``right`` and ``down`` at
  140. the same time, the resulting ``velocity`` vector will be ``(1, 1)``. In
  141. this case, since we're adding a horizontal and a vertical movement, the
  142. player would move *faster* than if it just moved horizontally.
  143. We can prevent that if we *normalize* the velocity, which means we set
  144. its *length* to ``1``, and multiply by the desired speed. This means no
  145. more fast diagonal movement.
  146. .. tip:: If you've never used vector math before (or just need a refresher)
  147. you can see an explanation of vector usage in Godot at :ref:`doc_vector_math`.
  148. It's good to know but won't be necessary for the rest of this tutorial.
  149. We also check whether the player is moving so we can start or stop the
  150. AnimatedSprite animation.
  151. Now that we have a movement direction, we can update the player's position
  152. and use ``clamp()`` to prevent it from leaving the screen:
  153. ::
  154. position += velocity * delta
  155. position.x = clamp(position.x, 0, screensize.x)
  156. position.y = clamp(position.y, 0, screensize.y)
  157. .. tip:: *Clamping* a value means restricting it to a given minimum/maximum range.
  158. Click "Play the Edited Scene. (F6)" and confirm you can move the player
  159. around the screen in all directions.
  160. Choosing Animations
  161. ~~~~~~~~~~~~~~~~~~~
  162. Now that the player can move, we need to change which animation the
  163. AnimatedSprite is playing based on direction. We have a "right"
  164. animation, which should be flipped horizontally (using the ``flip_h``
  165. property) for left movement, and an "up" animation, which should be
  166. flipped vertically (``flip_v``) for downward movement.
  167. Let's place this code at the end of our ``_process()`` function:
  168. ::
  169. if velocity.x != 0:
  170. $AnimatedSprite.animation = "right"
  171. $AnimatedSprite.flip_v = false
  172. $AnimatedSprite.flip_h = velocity.x < 0
  173. elif velocity.y != 0:
  174. $AnimatedSprite.animation = "up"
  175. $AnimatedSprite.flip_v = velocity.y > 0
  176. Play the scene again and check that the animations are correct in each
  177. of the directions.
  178. Preparing for Collisions
  179. ~~~~~~~~~~~~~~~~~~~~~~~~
  180. We want the player to detect when it is hit by an enemy, but we haven't
  181. made any enemies yet! That's OK because we're going to use Godot's
  182. *signal* functionality to make it work.
  183. Add the following at the top of the script (after ``extends Area2d``):
  184. ::
  185. signal hit
  186. This defines a custom signal called "hit" that we will have our player
  187. emit (send out) when it collides with an enemy. We will use the Area2D to
  188. detect the collision. Select the ``Player`` node and click the "Node" tab
  189. next to the Inspector to see the list of signals the player can emit:
  190. .. image:: img/player_signals.png
  191. Notice our custom "hit" signal is there as well! Since our enemies are
  192. going to be ``RigidBody2D`` nodes, we want the
  193. ``body_entered( Object body )`` signal - that will be emitted when a
  194. body contacts the player. Click "Connect.." and then "Connect" again on
  195. the "Connecting Signal" window - we don't need to change any of those
  196. settings. Godot will automatically create a function called
  197. ``_on_Player_body_entered`` in your player's script.
  198. .. tip:: When connecting a signal, instead of having Godot create a
  199. function for you, you can also give the name of an existing
  200. function that you want to link the signal to.
  201. Add this code to the function:
  202. ::
  203. func _on_Player_body_entered( area ):
  204. hide() # Player disappears after being hit
  205. emit_signal("hit")
  206. monitoring = false
  207. .. warning:: Disabling the ``monitoring`` property of an ``Area2D`` means
  208. it won't detect collisions. By turning it off, we make
  209. sure we don't trigger the ``hit`` signal more than once. However,
  210. changing the property in the midst of an ``area_entered`` signal
  211. will result in an error, because the engine hasn't finished
  212. processing the current frame yet.
  213. Instead, you can *defer* the change, which will tell the game engine to
  214. wait until it's safe to set monitoring to ``false``. Change the line to
  215. this:
  216. ::
  217. call_deferred("set_monitoring", false)
  218. The last piece for our player is to add a function we can call to reset
  219. the player when starting a new game.
  220. ::
  221. func start(pos):
  222. position = pos
  223. show()
  224. monitoring = true
  225. Enemy Scene
  226. -----------
  227. Now it's time to make the enemies our player will have to dodge. Their
  228. behavior will not be very complex: mobs will spawn randomly at the edges
  229. of the screen and move in a straight line (in a random direction), then
  230. despawn when they go offscreen.
  231. We will build this into a ``Mob`` scene, which we can then *instance* to
  232. create any number of independent mobs in the game.
  233. Node Setup
  234. ~~~~~~~~~~
  235. Click Scene -> New Scene and we'll create the Mob.
  236. The Mob scene will use the following nodes:
  237. - :ref:`RigidBody2D <class_RigidBody2D>` (named ``Mob``)
  238. - :ref:`AnimatedSprite <class_AnimatedSprite>`
  239. - :ref:`CollisionShape2D <class_CollisionShape2D>`
  240. - :ref:`VisibilityNotifier2D <class_VisibilityNotifier2D>` (named ``Visibility``)
  241. In the :ref:`RigidBody2D <class_RigidBody2D>` properties, set ``Gravity Scale`` to ``0`` (so
  242. that the mob will not fall downward). In addition, under the
  243. ``PhysicsBody2D`` section in the Inspector, click the ``Mask`` property and
  244. uncheck the first box. This will ensure that the mobs do not collide with each other.
  245. .. image:: img/set_collision_mask.png
  246. Set up the :ref:`AnimatedSprite <class_AnimatedSprite>` like you did for the player.
  247. This time, we have 3 animations: "fly", "swim", and "walk". Set the ``Playing``
  248. property in the Inspector to "On" and adjust the "Speed (FPS)" setting as shown below.
  249. We'll select one of these randomly so that the mobs will have some variety.
  250. In Godot's 2D space, a heading of zero degrees points to the right. However, our mob art
  251. is drawn pointing upward. To correct for this, set the ``AnimatedSprite``'s "Rotation Deg"
  252. property to ``90``.
  253. .. image:: img/mob_animations.gif
  254. As in the ``Player`` scene, add a ``CapsuleShape2D`` for the
  255. collision and then save the scene.
  256. Enemy Script
  257. ~~~~~~~~~~~~
  258. Add a script to the ``Mob`` and add the following member variables:
  259. ::
  260. extends RigidBody2D
  261. var MIN_SPEED = 150 # minimum speed range
  262. var MAX_SPEED = 250 # maximum speed range
  263. var mob_types = ["walk", "swim", "fly"]
  264. We'll pick a random value between ``MIN_SPEED`` and ``MAX_SPEED`` for
  265. how fast each mob will move (it would be boring if they were all moving
  266. at the same speed). We also have an array containing the names of the three
  267. animations, which we'll use to select a random one.
  268. Now let's look at the rest of the script. In ``_ready()`` we choose a
  269. random one of the three animation types:
  270. ::
  271. func _ready():
  272. $AnimatedSprite.animation = mob_types[randi() % mob_types.size()]
  273. .. note:: You must use ``randomize()`` if you want
  274. your sequence of "random" numbers to be different every time you run
  275. the scene. We're going to use ``randomize()`` in our ``Main`` scene,
  276. so we won't need it here. ``randi() % n`` is the standard way to get
  277. a random integer between ``0`` and ``n-1``.
  278. The last piece is to make the mobs delete themselves when they leave the
  279. screen. Connect the ``screen_exited()`` signal of the ``Visibility``
  280. node and add this code:
  281. ::
  282. func _on_Visible_screen_exited():
  283. queue_free()
  284. That completes the `Mob` scene.
  285. Main Scene
  286. ----------
  287. Now it's time to bring it all together. Create a new scene and add a
  288. :ref:`Node <class_Node>` named ``Main``. Click the "Instance" button and select your
  289. saved ``Player.tscn``.
  290. .. image:: img/instance_scene.png
  291. .. note:: See :ref:`doc_instancing` to learn more about instancing.
  292. Now add the following nodes as children of ``Main``, and name them as
  293. shown (values are in seconds):
  294. - :ref:`Timer <class_Timer>` (named ``MobTimer``) - to control how often mobs spawn
  295. - :ref:`Timer <class_Timer>` (named ``ScoreTimer``) - to increment the score every second
  296. - :ref:`Timer <class_Timer>` (named ``StartTimer``) - to give a delay before starting
  297. - :ref:`Position2D <class_Position2D>` (named ``StartPosition``) - to indicate the player's start position
  298. Set the ``Wait Time`` property of each of the ``Timer`` nodes as
  299. follows:
  300. - ``MobTimer``: ``0.5``
  301. - ``ScoreTimer``: ``1``
  302. - ``StartTimer``: ``2``
  303. In addition, set the ``One Shot`` property of ``StartTimer`` to "On" and
  304. set ``Position`` of the ``StartPosition`` node to ``(240, 450)``.
  305. Spawning Mobs
  306. ~~~~~~~~~~~~~
  307. The Main node will be spawning new mobs, and we want them to appear at a
  308. random location on the edge of the screen. Add a :ref:`Path2D <class_Path2D>` named
  309. ``MobPath`` as a child of ``Main``. When you select the ``Path2D`` node
  310. you will see some new buttons appear at the top of the editor:
  311. .. image:: img/path2d_buttons.png
  312. Select the middle one ("Add Point") and draw the path by clicking to add
  313. the points shown. To have the points snap to the grid, make sure "Use Snap" is
  314. checked. This option can be found under the "Edit" button to the left of the Path2D buttons.
  315. .. image:: img/draw_path2d.png
  316. .. important:: Draw the path in *clockwise* order, or your mobs will spawn
  317. pointing *outwards* instead of *inwards*!
  318. Now that the path is defined, add a :ref:`PathFollow2D <class_PathFollow2D>`
  319. node as a child of ``MobPath`` and name it ``MobSpawnLocation``. This node will
  320. automatically rotate and follow the path you've drawn, so we can use it
  321. to select a random position and direction along the path.
  322. Main Script
  323. ~~~~~~~~~~~
  324. Add a script to ``Main``. At the top of the script we use
  325. ``export (PackedScene)`` to allow us to choose the Mob scene we want to
  326. instance.
  327. ::
  328. extends Node
  329. export (PackedScene) var Mob
  330. var score
  331. func _ready():
  332. randomize()
  333. Using ``export`` lets you set the value of a variable in the Inspector
  334. like so:
  335. .. image:: img/load_mob_scene.png
  336. Click on "<null>"" and choose "Load", then select ``Mob.tscn``.
  337. Next, click on the Player and connect the ``hit`` signal to the
  338. ``game_over`` function, which will handle what needs to happen when a
  339. game ends. We will also have a ``new_game`` function to set everything
  340. up for a new game:
  341. ::
  342. func new_game():
  343. score = 0
  344. $Player.start($StartPosition.position)
  345. $StartTimer.start()
  346. func game_over():
  347. $ScoreTimer.stop()
  348. $MobTimer.stop()
  349. Now connect the ``timeout()`` signal of each of the Timer nodes.
  350. ``StartTimer`` will start the other two timers. ``ScoreTimer`` will
  351. increment the score by 1.
  352. ::
  353. func _on_StartTimer_timeout():
  354. $MobTimer.start()
  355. $ScoreTimer.start()
  356. func _on_ScoreTimer_timeout():
  357. score += 1
  358. In ``_on_MobTimer_timeout()`` we will create a mob instance, pick a
  359. random starting location along the ``Path2D``, and set the mob in
  360. motion. The ``PathFollow2D`` node will automatically rotate as it
  361. follows the path, so we will use that to select the mob's direction as
  362. well as its position.
  363. Note that a new instance must be added to the scene using
  364. ``add_child()``.
  365. ::
  366. func _on_MobTimer_timeout():
  367. # choose a random location on the Path2D
  368. $"MobPath/MobSpawnLocation".set_offset(randi())
  369. # create a Mob instance and add it to the scene
  370. var mob = Mob.instance()
  371. add_child(mob)
  372. # choose a direction and position
  373. var direction = $"MobPath/MobSpawnLocation".rotation
  374. mob.position = $"MobPath/MobSpawnLocation".position
  375. # add some randomness to the direction
  376. direction += rand_range(-PI/4, PI/4)
  377. mob.rotation = direction
  378. # choose the velocity
  379. mob.set_linear_velocity(Vector2(rand_range(mob.MIN_SPEED, mob.MAX_SPEED), 0).rotated(direction))
  380. .. important:: In functions requiring angles, GDScript uses *radians*,
  381. not degrees. If you're more comfortable working with
  382. degrees, you'll need to use the ``deg2rad()`` and
  383. ``rad2deg()`` functions to convert between the two measures.
  384. HUD
  385. ---
  386. The final piece our game needs is a UI: an interface to display things
  387. like score, a "game over" message, and a restart button. Create a new
  388. scene, and add a :ref:`CanvasLayer <class_CanvasLayer>` node named ``HUD`` ("HUD" stands for
  389. "heads-up display", meaning an informational display that appears as an
  390. overlay, on top of the game view).
  391. The :ref:`CanvasLayer <class_CanvasLayer>` node lets us draw our UI elements on
  392. the layer above the rest of the game so that the information it displays doesn't get
  393. covered up by any game elements like the player or the mobs.
  394. The HUD displays the following information:
  395. - Score, changed by ``ScoreTimer``
  396. - A message, such as "Game Over" or "Get Ready!"
  397. - A "Start" button to begin the game
  398. The basic node for UI elements is :ref:`Control <class_Control>`. To create our UI,
  399. we'll use two types of :ref:`Control <class_Control>` nodes: The :ref:`Label <class_Label>`
  400. and the :ref:`Button <class_Button>`.
  401. Create the following children of the ``HUD`` node:
  402. - :ref:`Label <class_Label>` (named ``ScoreLabel``)
  403. - :ref:`Label <class_Label>` (named ``MessageLabel``)
  404. - :ref:`Button <class_Button>` (named ``StartButton``)
  405. - :ref:`Timer <class_Timer>` (named ``MessageTimer``)
  406. .. note:: **Anchors and Margins** ``Control`` nodes have a position and size,
  407. but they also have anchors and margins. Anchors define the
  408. origin, or the reference point for the edges of the node. Margins
  409. update automatically when you move or resize a control node. They
  410. represent the distance from the control node's edges to its anchor.
  411. See :ref:`doc_gui_tutorial` for more details.
  412. Arrange the nodes as shown below. Click the "Anchor" button to
  413. set a Control node's anchor:
  414. .. image:: img/ui_anchor.png
  415. You can drag the nodes to place them manually, or for more precise
  416. placement, use the following settings:
  417. ScoreLabel
  418. ~~~~~~~~~~
  419. - ``Anchor``: "Center Top"
  420. - ``Margin``:
  421. - Left: ``-240``
  422. - Top: ``0``
  423. - Right: ``240``
  424. - Bottom: ``100``
  425. - Text: ``0``
  426. MessageLabel
  427. ~~~~~~~~~~~~
  428. - ``Anchor``: "Center"
  429. - ``Margin``:
  430. - Left: ``-240``
  431. - Top: ``-260``
  432. - Right: ``240``
  433. - Bottom: ``60``
  434. - Text: ``Dodge the Creeps!``
  435. StartButton
  436. ~~~~~~~~~~~
  437. - ``Anchor``: "Center"
  438. - ``Margin``:
  439. - Left: ``-60``
  440. - Top: ``70``
  441. - Right: ``60``
  442. - Bottom: ``150``
  443. - Text: ``Start``
  444. The default font for ``Control`` nodes is very small and doesn't scale
  445. well. There is a font file included in the game assets called
  446. "Xolonium-Regular.ttf". To use this font, do the following for each of
  447. the three ``Control`` nodes:
  448. 1. Under "Custom Fonts", choose "New DynamicFont"
  449. .. image:: img/custom_font1.png
  450. 2. Click on the "DynamicFont" you just added, and under "Font Data",
  451. choose "Load" and select the "Xolonium-Regular.ttf" file. You must
  452. also set the font's ``Size``. A setting of ``64`` works well.
  453. .. image:: img/custom_font2.png
  454. Now add this script to the ``HUD``:
  455. ::
  456. extends CanvasLayer
  457. signal start_game
  458. The ``start_game`` signal tells the ``Main`` node that the button
  459. has been pressed.
  460. ::
  461. func show_message(text):
  462. $MessageLabel.text = text
  463. $MessageLabel.show()
  464. $MessageTimer.start()
  465. This function is called when we want to display a message
  466. temporarily, such as "Get Ready". On the ``MessageTimer``, set the
  467. ``Wait Time`` to ``2`` and set the ``One Shot`` property to "On".
  468. ::
  469. func show_game_over():
  470. show_message("Game Over")
  471. yield($MessageTimer, "timeout")
  472. $StartButton.show()
  473. $MessageLabel.text = "Dodge the\nCreeps!"
  474. $MessageLabel.show()
  475. This function is called when the player loses. It will show "Game
  476. Over" for 2 seconds, and then return to the game title and show the
  477. "Start" button.
  478. ::
  479. func update_score(score):
  480. $ScoreLabel.text = str(score)
  481. This function is called in ``Main`` whenever the score changes.
  482. Connect the ``timeout()`` signal of ``MessageTimer`` and the
  483. ``pressed()`` signal of ``StartButton``.
  484. ::
  485. func _on_StartButton_pressed():
  486. $StartButton.hide()
  487. emit_signal("start_game")
  488. func _on_MessageTimer_timeout():
  489. $MessageLabel.hide()
  490. Connecting HUD to Main
  491. ~~~~~~~~~~~~~~~~~~~~~~
  492. Now that we're done creating the ``HUD`` scene, save it and go back to ``Main``.
  493. Instance the ``HUD`` scene in ``Main`` like you did the ``Player`` scene, and place it at the
  494. bottom of tree. The full tree should look like this, so make sure you didn't miss anything:
  495. .. image:: img/completed_main_scene.png
  496. Now we need to connect the ``HUD`` functionality to our ``Main`` script.
  497. This requires a few additions to the ``Main`` scene:
  498. In the Node tab, connect the HUD's ``start_game`` signal to the
  499. ``new_game()`` function.
  500. In ``new_game()``, update the score display and show the "Get Ready"
  501. message:
  502. ::
  503. $HUD.update_score(score)
  504. $HUD.show_message("Get Ready")
  505. In ``game_over()`` we need to call the corresponding ``HUD`` function:
  506. ::
  507. $HUD.show_game_over()
  508. Finally, add this to ``_on_ScoreTimer_timeout()`` to keep the display in
  509. sync with the changing score:
  510. ::
  511. $HUD.update_score(score)
  512. Finishing Up
  513. ------------
  514. We've now completed all the functionality for our game. Below are some
  515. remaining steps to add a bit more "juice" and improve the game
  516. experience. Feel free to expand the gameplay with your own ideas.
  517. Background
  518. ~~~~~~~~~~
  519. The default gray background is not very appealing, so let's change its
  520. color. One way to do this is to use a :ref:`ColorRect <class_ColorRect>` node. Make it the
  521. first node under ``Main`` so that it will be drawn behind the other
  522. nodes. ``ColorRect`` only has one property: ``Color``. Choose a color
  523. you like and drag the size of the ``ColorRect`` so that it covers the
  524. screen.
  525. You can also add a background image, if you have one, by using a
  526. ``Sprite`` node.
  527. Sound Effects
  528. ~~~~~~~~~~~~~
  529. Sound and music can be the single most effective way to add appeal to
  530. the game experience. In your game assets folder, you have two sound
  531. files: "House In a Forest Loop.ogg", for background music, and
  532. "gameover.wav" for when the player loses.
  533. Add two :ref:`AudioStreamPlayer <class_AudioStreamPlayer>` nodes as children of ``Main``. Name one of
  534. them ``Music`` and the other ``DeathSound``. On each one, click on the
  535. ``Stream`` property, select "Load" and choose the corresponding audio
  536. file.
  537. To play the music, add ``$Music.play()`` in the ``new_game()`` function
  538. and ``$Music.stop()`` in the ``game_over()`` function.
  539. Finally, add ``$DeathSound.play()`` in the ``game_over()`` function as
  540. well.
  541. Particles
  542. ~~~~~~~~~
  543. For one last bit of visual appeal, let's add a trail effect to the
  544. player's movement. Choose your ``Player`` scene and add a
  545. :ref:`Particles2D <class_Particles2D>` node named ``Trail``.
  546. There are a very large number of properties to choose from when
  547. configuring particles. Feel free to experiment and create different
  548. effects. For the effect in the example, use the following settings:
  549. .. image:: img/particle_trail_settings.png
  550. You also need to create a ``Material`` by clicking on ``<null>`` and
  551. then "New ParticlesMaterial". The settings for that are below:
  552. .. image:: img/particle_trail_settings2.png
  553. .. seealso:: See :ref:`Particles2D <class_Particles2D>` for more details on using
  554. particle effects.
  555. Project Files
  556. -------------
  557. You can find a completed version of this project here:
  558. https://github.com/kidscancode/Godot3_dodge/releases