How do I make a looping tween?

Godot Version

4.5

Question

How can I create a looping tween? On the Godot Docs (or as I like to call them, the Godocs)
it says:

Warning: Make sure to always add some duration/delay when using infinite loops. To prevent the game freezing, 0-duration looped animations (e.g. a single CallbackTweener with no delay) are stopped after a small number of loops, which may produce unexpected results. If a Tween’s lifetime depends on some node, always use bind_node().

How can I do this? I want my coin to bob up and down. This is my code, why doesn’t it work?

And this is the Coin scene to which this is attached:
image

1 Like

It doesn’t work because for both tweens you set the position to be the exact same:
Vector2(0, 2)

Simply change the second Vector2 to be: Vector2(0, 0) and it’ll work. Or you can also set it to Vector2(0, -2) if you want it to move more.

1 Like

That warning just means that you shouldn’t have infinite looping tweens with no duration or delay. In your case, each tween_property() has a duration already so it won’t cause any issues.

If you want to add a small delay between tweening different properties then you need to use PropertyTweener.set_delay()

And, as @tibaverus said, you are tweening to the same value both times so it won’t bob.

BTW, the wait() function is not the correct way to do it . More info about how to correctly setup it here:

Personally, what I’d do in this situation is chain things. Something like:


func _ready() -> void:
    _bob_up()

func _bob_up() -> void:
    tween = create_tween()
    tween.tween_property(sprite, "position", Vector2(0.0, 2.0), 1)
    tween.tween_callback(_bob_down)

func _bob_down() -> void:
    tween = create_tween()
    tween.tween_property(sprite, "position", Vector2(0.0, 0.0), 1)
    tween.tween_callback(_bob_up)

When one tween completes it fires the next in the chain.

1 Like

Theoretically your code here should perform no different than:

func _ready() -> void:
    _bob()

func _bob() -> void:
    tween = create_tween()
    tween.set_loops()
    tween.tween_property(sprite, "position", Vector2(0.0, 2.0), 1)
    tween.tween_property(sprite, "position", Vector2(0.0, 0.0), 1)
1 Like

Thank you so much! :godot:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.