How to increase the speed of the game?

Hello, I am making a game, and I want to speed it up like the google trex game. So as the game goes, I want the speed to increase. But I don’t know how to put it into code, can you help?

Hi,

You could define three values: a default speed, an additional speed, and an acceleration.
The default speed would be a fixed value, for instance 10 (that’s an arbitrary value, the value may be very different depending on your code and that would be okay). The additional speed would start at 0, and be incremented over time using the acceleration.
To move your character, you then use the sum of both the default speed and the additional speed. Something like this:

@export var default_speed: float = 10
@export var acceleration: float = 0.1
var additional_speed: float = 0

func _process(delta: float):
    additional_speed += acceleration * delta
    var speed = default_speed + additional_speed
    # Apply speed to your movement.

Here, the speed would increment by 0.1 every second (since the acceleration is multiplied by delta).


You might also want to include a maximum speed that the character cannot exceed, for the game still being playable even when the speed is high:

@export var default_speed: float = 10
@export var acceleration: float = 0.1
@export var maximum_speed: float = 30
var additional_speed: float = 0

func _process(delta: float):
    additional_speed += acceleration * delta
    var speed = default_speed + additional_speed
    if speed > maximum_speed:
        speed = maximum_speed
    
    # Apply speed to your movement.

I’ve wrote the code without testing it so it may need a few changes, but I hope that helps!

1 Like

Thank you soooo much, you’re a lifesaver!! ToT The only thing is that the maximum speed doesn’t work for some reason, it just goes beyond that

Oh, there’s indeed a flaw in my code, now that I read it again.
Should be:

func _process(delta: float):
    additional_speed += acceleration * delta

    var speed = default_speed + additional_speed
    if speed > maximum_speed:
        speed = maximum_speed

    # Apply speed to your movement.

The speed that should be clamped is the final speed, not the additional one. I’m editing the first post too.

Yess!!! It works now!! I’m so grateful, thank you so so much!!! <3

1 Like