04.making-the-ship-boost

Making the ship boost

In this video, you’ll code a time-limited boost for your ship using signals.

Video playback issue on Firefox

There’s a bug with the video platform that prevents it from running in Firefox. As far as we know, it only happens on Firefox.

If the video above doesn’t load for you, you can watch it on YouTube instead: https://youtu.be/7l2HjwVA7dw.

New concepts

Signals

Signals allow nodes to communicate and react to one another. They are messages that nodes emit when something occurs to them. For example, a Timer emits the "timeout" signal when it times out.

You can connect a signal and a node. When you do so, every time the signal emits, Godot calls the connected function. It happens synchronously: in the video, when the "timeout" signal emits, the connected _on_Timer_timeout() function gets called in the same frame.

You’ll use signals a lot in this course and in your projects. They’re one of Godot’s most useful core features.

Getting nodes

In GDScript, you can access child nodes by calling the get_node() function. This function requires one argument: the path to the target node relative to the node to which you attached the script.

For example, in the picture below, you can access the BodySprite node from the Player node by calling get_node("Pivot/BodySprite").

Once you get a node, you can call its functions and access its variables using the dot (.) operator, like when we wrote get_node("Timer").start() in the video.

Practice: The boost mechanic

In the Godot practice project, open the third practice, The boost mechanic.

In this practice, you’ll reproduce the boost mechanic we saw in this lesson.

You’ll need to add a timer to your scene, connect to its signal, and make the ship boost when pressing the boost input action.

The code

Here’s the ship’s code so far.

extends Sprite

var boost_speed := 1500.0
var normal_speed := 600.0

var max_speed := normal_speed
var velocity := Vector2.ZERO


func _process(delta: float) -> void:
    var direction := Vector2.ZERO
    direction.x = Input.get_axis("move_left", "move_right")
    direction.y = Input.get_axis("move_up", "move_down")

    if direction.length() > 1.0:
        direction = direction.normalized()

    if Input.is_action_just_pressed("boost"):
        max_speed = boost_speed
        get_node("Timer").start()

    velocity = direction * max_speed
    position += velocity * delta
    if direction:
        rotation = velocity.angle()


func _on_Timer_timeout() -> void:
    max_speed = normal_speed

In the next part, you’ll add steering to your node. This time, you won’t have a video: instead, you’ll have to read a short guide and use code listings to modify your ship.

It may not be as comfortable as watching videos, but at the same time, it’s good for you: it’s a more active form of learning.