Lesson 5
Collectables
Download the week 4 project
Collectables
A signal is a special type of variant that allows you to connect callables (i.e., functions) to them in order to listen and react to certain events. Whenever something happens that causes a signal to be emitted, all of the connected callables will be called. Some common use cases for signals include:
UI events: Whenever the user clicks a button, or changes the value on a slider, they will emit the appropriate signal so that your script can respond to the event.
Collision detection: The Area2D node will emit signals when another Area2D or PhysicsBody2D intersects them. This can be useful for item collection or damage detection.
State changes: If the player's state changes, (ex, going from "alive" to "dead"), it can be useful to emit a signal to let other game objects know.
You can find all of the signals that a node can emit under the Signals tab of the Inspector window:


Homework
Add Coin Scene
Create a new scene with an Area2D root node, rename it "Coin"
Set the Collision Layer to 3 (Collectables)
Uncheck all Collision Mask layers, since the Coin doesn't need to scan for any collision layers.
Add AnimatedSprite2D child node.
Add coin sprites to "default" animation.
Change speed to 8 FPS
Add CollisionShape2D child node.
Add Circle shape.
Resize circle to fully overlap the sprite.
Add a new script to the root node called Collectable
Add @export variable with the collectable's value.
Add collect function that takes a player argument. This function will call player.add_points(value) when the coin is collected.
In the collect function, remove the collectable: queue_free()
Update Player Scene
Add an Area2D child to the Player scene, rename it "CollisionDetection"
Add a CollisionShape2D child to the new Area2D node.
Add a Rectangle shape, resize to overlap the player sprite.
Update the Player Script
Add a new @export variable to the player script called score.
Connect the Area2D's area_entered signal to a new function in the player script (the default function name is fine).
In this new function, check if the area's collision layer is 3 (Collectables). If so, call area.collect(self) to collect it.
Add a new function to the player script called add_points that takes a points argument.
Increment the player's score by the point's passed in: score += points.
Add Audio to Coin
Add AudioStreamPlayer2D child node to the Coin scene.
Set the Stream property to the retro-coin.mp3 audio file. Leave all other properties default.
Update the Collectable script.
Add a new finish() function, move the call to queue_free() to the new finish() function.
In the collect() function, play the AudioStreamPlayer2D node.
Connect the AudioStreamPlayer2D's finished signal to the new finish function.
Hide the AnimatedSprite2D node so the sprite isn't visible once collected.
Disabled the CollisionShape2D node so the object can't collide anymore once collected.
