Creators – Week 7

It was time this week to finish up Roll-A-Ball. After the session, I did some additional tweaking. There are changes to the materials and camera position. I also added a splash screen, background sound, a font resource and a sound effect when a pickup is collected. Each level has an associated target time and you advance to the next level depending on whether you beat that time. There are four levels in total. At the end, depending on how you did, you get “You won” or “Game over” message and the option to restart. Here it is in action:

Collision

Although the pickups were technically just over the ground, and not intersecting it, we found previously that for many of us, when we ran, several of the pickups detected contact with the ground and deleted it. We “fixed” that by temporarily lifting the CollisionShape3D in the pickup up by 0.01m, but we returned to this to correct it.

Every node that collides with another, in our specific case Area3D and RigidBody3D, derives from the CollisionObject3D node and has a Layer and Mask property:

Layer is the collision layer that this node is in. Note that something can be in more than one layer.

Mask is the collision layer that we watch for collisions with. Anything not in these nominated layers will be ignored.

All we had to do to fix this, was to set the Mask for the Pickup to 2, and the Layer for the Player to 2. Now the pickup ignores all collisions except with the player (everything else, including the ground, being in Layer 1 by default).

Dynamic Level Loading

We wanted the GameManager to be able to load levels automatically. First we created our level, by adding a Node3D called “Level 1” to our Main scene and dragging all pickups into it. We then right-clicked and chose “Save Branch as Scene…” to make it a scene of its own. We then deleted the instance of the level from the scene, since we were going to have the Game Manager create it.

We added a new variable to Game Manager:

@export var level : PackedScene

PackedScene is the type used for a scene saved to disk. We were then able to assign our level scene to this variable in the inspector.

Next we had to add some code to get this level created. We added these lines at the bottom of the GameManager’s _ready() function:

var current_level = level.instantiate()
add_child(current_level)

This takes the level from the disk and actually creates nodes from it (instantiate()). We save that to a variable current_level and the use add_child() to actually add this to the current scene. When we ran, all was as normal, but looking at the remote tree, we could see that Level 1 was now a child of Game Manager.

We then created a few extra levels and tried loading them instead, by selecting them in the inspector.

Handing Multiple Levels Automatically

We then went back and decided to add support for multiple levels, having the game change to the next level automatically. We added these variables to the game_manager.gd script:

@export var levels : Array[PackedScene]

var current_level : Node3D
var current_level_index : int = -1

An Array, as you might remember from the first few weeks, is a variable that can store multiple values like a list. We then removed the last two lines from _ready() and created this function instead:

func load_next_level() -> void:
	if (current_level != null):
		current_level.queue_free()

	current_level_index += 1
	current_level = level[current_level_index].instantiate() as Level
	add_child(current_level)

This function:

  • Removes the current level, if there’s one loaded
  • Increments the level counter
  • Loads the next level and adds it to the scene

Note that it doesn’t know when to stop yet and will keep trying to load even when there’s no levels left.

Finally we had to call this function from somewhere. All that was needed was to edit _process() as follows:

func _process(delta: float) -> void:
	pickups_count_label.text = "Remaining Pickups: " + str(pickup_count)

	if (pickup_count == 0):
		load_next_level()

If we’re at the start of the game, when the pickup_count is also zero, or we’ve just collected all the pickups i a level, the game will call load_next_level() and load a level.

We tested this and it worked.

Reseting the Player

We wanted to reset the player. This means returning it to its starting position and clearing any linear and angular velocity from the RigidBody3D. For a RigidBody3D, all changes to physics variables should happen in _physics_process().

To make this work, we first added three variables to player.gd:

var initial_pos : Vector3
var initial_rot : Vector3

var reset_requested : bool = false

The first two are to remember the initial position and rotation of the player and the third is a switch we can toggle to true when we want to trigger a reset.

To remember the initial position and rotation, we just needed to add these two lines to _ready():

	initial_pos = position
	initial_rot = rotation

Then in _physics_process() we change it to read as follows:

func _physics_process(delta : float) -> void:
	if (reset_requested):
		position = initial_pos
		rotation = initial_rot
		linear_velocity = Vector3.ZERO
		angular_velocity = Vector3.ZERO
		reset_requested = false
	else:
		var input = Input.get_vector("Up", "Down", "Left", "Right")
		apply_torque(power * delta * Vector3(input.x, 0, -input.y))

If reset_required is true, then we put the ball position and rotation back to their original values and set both linear_velocity and angular_velocity to zero. Finally we set reset_requested back to false so that we won’t run this code again until it’s needed.

To actually trigger this, in game_manager.gd, we added a variable for the player:

@onready var player: RigidBody3D = $"../Player"

And we updated _process() to also reset the player:

func _process(delta: float) -> void:
	pickups_count_label.text = "Remaining Pickups: " + str(pickup_count)

	if (pickup_count == 0):
		load_next_level()
		player.reset_requested = true

Handing Running out of Levels

To handle running out of levels, we updated our load_next_level() function in game_manager.gd to check that there actually was another level to load and to return false if there wasn’t. We changed the return type to -> bool first:

func load_next_level() -> bool:
	if (current_level != null):
		current_level.queue_free()

	current_level_index += 1
	if (current_level_index >= len(level)):
		return false

	current_level = level[current_level_index].instantiate() as Level
	time_remaining = current_level.target_seconds
	add_child(current_level)

	return true

This uses the len() function to check the size of the level array and if there isn’t another level to load return false.

Now the game doesn’t crash when it runs out of levels. Finally we added this logic to game_manager.gd’s _process() to hide the player once we run out of levels:

func _process(delta: float) -> void:
	pickups_count_label.text = "Remaining Pickups: " + str(pickup_count)
	
	if (pickup_count == 0):
		if (load_next_level() == false):
			player.hide()

Getting the Code

All our code for this year is available on our GitHub.

Creators – Week 6

This week we added some pickups to our game, some signals (Godot’s term for messages or events) to indicate their creation or collection, and a game manager to keep track of everything.

Pickups

To create our pickups we created a new scene with an Area3D as the root node. An Area3D, in conjunction with a CollisionShape3D, allows us to define an area where bodies entering and exiting this area can be detected.

We paired this Area3D with a cylinder CollisionShape3D and a cylinder MeshInstance3D, both about the same height as our player ball.

We created a new StandardMaterial3D resource for our pickup and used the checker texture again, this time scaled to appear multiple times on the object, to give it some visual interest.

Signals

Signals are Godot’s way for nodes to tell other nodes when something’s happened. There are many built-in signals in the existing nodes and you can easily define others yourself.

To demonstrate, we created a new script attached to the root node of the pickup scene, and with this same node selected, we then went to the tab underneath the Inspector tab, a tab called Node.

This shows the list of signals on this node available to connect to. We right clicked on body_entered() and connected it to the pickup script, creating a new function called _on_body_entered() in that script.

We just set the following code there to show that we’d detected something entering the area (as defined by the collider):

func _on_body_entered(body: Node3D) -> void:
	print(body.name + " entered the area")

We created an instance of the pickup in our Main scene by using the “Instantiate Child Scene” button at the top of the scene view, and selecting the pickup scene:

We moved this pickup off centre and tested our code by playing it and rolling the player into the pickup. The message “Player entered the area” was printed to the Output window.

We updated this code by adding queue_free() at the end of the function:

func _on_body_entered(body: Node3D) -> void:
	print(body.name + " entered the area")
	queue_free()

This function means “please queue this node (and all it’s child nodes) for deletion at the end of this frame”. When we test again, we see that rolling the player into the pickup now makes the pickup disappear.

A Handy Way To Handle Events

In Godot connecting a node to another’s signal normally means that the first node has to have a reference to the second.

There’s a nice pattern that simplifies things. We make a central place that holds the signals, nodes that want to “emit” (or cause the signal to fire) and nodes that want to know when the signal was emitted just need to know about this central place, they don’t need to know about each other.

Godot has a system whereby a script can be set to autoload when the game starts, it doesn’t have to be connected to a node in a scene. Even more convenient, it will declare a global (visible everywhere) variable for this class instance that everyone can easily access.

This might sound complex, but it’s super easy in practice. We created a new script called events.gd. The contents were as follows:

extends Node

signal pickup_created
signal pickup_collected

We then went to Project Settings | Globals and under Autoload, selected the events.gd script and pressed “+ Add”

Firing the Events from Pickup

In pickup.gd we added two lines to our _ready() and _on_body_entered() functions to cause the appropriate signals to be emitted when the pickup was created and collected respectively:

func _ready() -> void:
	Events.pickup_created.emit()

func _on_body_entered(body: Node3D) -> void:
	print(body.name + " entered the area")
	queue_free()
	Events.pickup_collected.emit()

See that we’re using the global variable “Events” here to access the signals.

We tested that we could read these signals by putting code into Player, but as this was just for quick testing, we won’t replicate it here.

Game Manager

We created a new Node3D in the Main scene, called it Game Manager, and created a new script attached to it.

In this script we added two variables to the top of the class:

extends Node3D

@export var pickup_count : int = 0
@export var game_time : float = 0

One is an integer variable to keep track of the number of pickups. The second is a float variable that tracks how long the game has been running for. Both have “@export” at the start, this means that they both appear as variables in the Inspector, which is handy.

For the pickup count, we first added two new functions, to respond to the creation and collection signals respectively:

func _on_pickup_created() -> void:
	pickup_count += 1
	
func _on_pickup_collected() -> void:
	pickup_count -= 1

All these to is increase or decrease the pickup_count variable. We need then to connect them to the signals, so that they get called if the signal is emitted. We do that in _ready():

func _ready() -> void:
	Events.pickup_created.connect(_on_pickup_created)
	Events.pickup_collected.connect(_on_pickup_collected)

For game_time, all we have to do is keep adding the delta values available in _process(), which represent the time in seconds since the last frame was drawn, together:

func _process(delta: float) -> void:
	game_time += delta

To see these running we ran our game and in the Scene view, switched to the “Remote” tree. The remote tree is the tree of the game that’s running. Looking at the Game Manager node in the inspector, we could verify the variables were working as expected.

Getting the Code

All our code for this year is be available on our GitHub.