How to make a forever loop

sorry if this is a rookie question.
but how do you make a forever loop on godot?

1 Like

while true:

Of course you’ll want to break out of it at some point using return or break. What spurred the question in the first place?

1 Like

i need to make a loop for a platformer game. But thanks!

Right but what feature of a platformer needs this kind of loop? I would only use an infinite loop for certain algorithms, as mis-managing a infinite loop will halt your game. If you want some kind of repeating effect you can use a Timer or AnimationPlayer depending on the feature.

im making something similar to geometry dash, where the player moves foward all the time.

Then you would use the _process function because it runs every frame, you can update position within it.

func _process(delta: float) -> void:
    position.x += SPEED * delta

Or _physics_process if you are using a CharacterBody2D to control your player, check out it’s “basic platformer” template code for an example.

2 Likes

okay, thanks!

1 Like

What may not be obvious at first glance is that Godot has a “forever loop” built in. It calls _process() and _physics_process() every frame for every object. This means in every object’s script, you effectively have:

# while (1) {
func _process(delta: float) -> void:
    [stuff]
# wait_for_vsync()
# }
3 Likes
func _ready():
    while true:
        print("Forever loop...")
        await get_tree().process_frame  # Without this, Godot would freeze

thank ye mate

1 Like

Very roblox style coding haha (though even Roblox has RunService.Heartbeat to connect to); again better to use _process

Thats not technically correct. The _process loops are not ‘forever’. They can be stopped and started at will.

And if your objects script doesn’t have any _process method in it, then it will be stopped by default.

Its forever in the sense that if you left it alone to run, it would run in each frame forever of course.

The same could be said of the entire program, or any part of it.

Not really, loops are loops, whether we are talking about doing them in GD Script, c# or assembler for that matter. The entire program isn’t looping around, there are loops inside the execution of code that might happen for the entire run of the application. (for example the video calls which do need to otherwise nothing would show).

We need to be careful what we are talking about here as to not to confuse. As @esp8266 rightly pointed it out, its very easy to create a loop which would in effect lock up the entire application.

For the purposes of the original question (and the people who might look this up because they want to do something repeatedly), the _process() function is the body of an endless loop, and it’s the correct place to do something like move something to the right forever.

1 Like