Part 2 – the coin scene
In this part, you’ll make coins for the player to collect. This will be a separate scene, describing all the properties and behavior of a single coin. Once saved, the main scene will load this one and create multiple instances (that is, copies) of it.
The node setup
Click Scene -> New Scene and add the following nodes. Don’t forget to set the children to not be selectable, as you did with the Player
scene:
Area2D
(namedCoin
):AnimatedSprite2D
CollisionShape2D
Make sure to save the scene once you’ve added the nodes.
Set up AnimatedSprite2D
as you did in the player scene. This time, you only have one animation – a shine/sparkle effect that makes the coin look dynamic and interesting. Add all the frames and set the animation speed to 12 FPS
. The images are also a little too large, so set the Scale value of AnimatedSprite2D
to (0.4, 0.4)
. In CollisionShape2D
, use CircleShape2D
and resize it to cover the coin image.
Using groups
Groups provide a tagging system for nodes, allowing you to identify similar nodes. A node can belong to any number of groups. In order for the player script to correctly detect a coin, you need to ensure that all coins will be in a group called coins. Select the Coin
node, click the Node tab (the same tab where you found the signals), and choose Groups. Type coins
in the box and click Add:
Figure 2.22: The Groups tab
Coin script
Your next step is to add a script to the Coin
node. Select the node and click the new script button, just like you did with the Player
node. If you uncheck the Template option, you’ll get an empty script without any comments or suggestions. The code for the coin is much shorter than the code for the player:
extends Area2D var screensize = Vector2.ZERO func pickup(): queue_free()
Recall that the pickup()
function is called by the player script. It defines what the coin will do when collected. queue_free()
is Godot’s method for removing nodes. It safely removes the node from the tree and deletes it from memory, along with all its children. Later, you’ll add visual and audio effects here, but for now, just having the coin disappear is good enough.
Removing nodes
queue_free()
doesn’t delete the object immediately, but rather adds it to a queue to be deleted at the end of the current frame. This is safer than immediately deleting the node because other code running in the game may still need the node to exist. By waiting until the end of the frame, Godot can be sure that all code that can access the node has completed and the node can be removed safely.
You’ve now completed the second of the two objects needed for this game. The coin object is ready to be placed randomly on the screen, and it can detect when it’s touched by the player, so it can be collected. The remaining piece of the puzzle is how to put it all together. In the next section, you’ll create a third scene to randomly create coins and allow the player to interact with them.