Help with tweens

Godot Version

4.2

Question

I have this blinking light in my scene using tweens.
image_2024-06-03_075258786

I need to figure out how to make the light blink 4 times, pause for two seconds, and then repeat. Right now, it just blinks continuously. I know there are ways to delay, pause, or stop a tween and restart it, but I’m confused about how to implement them to achieve what I want.

This code will toggle light_on when pressing spacebar, and will perform the tween as you intented.

extends Node2D


@onready var light: Node2D = $Icon
var light_on := false
var tween: Tween


func _ready() -> void:
	# Just sets the scale to Vector.ZERO at this point
	flicker()


func _input(event: InputEvent) -> void:
	if Input.is_action_just_pressed("ui_accept"):
		light_on = not light_on
		flicker()


func flicker() -> void:
	if not light_on:
		if tween:
			tween.stop()
			tween = null

		light.scale = Vector2.ZERO
		return

	light.scale = Vector2.ZERO
	var duration := 0.5
	tween = create_tween()

	# Infinite loop
	tween.set_loops()

	# Turn on and off 4 times
	for i in 4:
		tween.tween_property(light, "scale", Vector2.ONE, duration)
		tween.tween_property(light, "scale", Vector2.ZERO, duration)

	# Wait for x seconds before looping
	tween.tween_interval(2.0)

You can use tween.tween_interval(time:float) method to pause between tweens.
Also, I don’t think chain() will work without giving tween parallel by tween_set.parellel()
In your case, I’d recommend just giving it multiple lines of tween.

var tween = create_tween().set_loops() # This will make tween repeat untill Tween.kill is called
tween.tween_property(light,"scale",Vector2(0.0,0.0),0.5)
tween.tween_property(light,"scale",Vector2(1.0,1.0),0.5)
tween.tween_property(light,"scale",Vector2(0.0,0.0),0.5)
tween.tween_property(light,"scale",Vector2(1.0,1.0),0.5)
tween.tween_property(light,"scale",Vector2(0.0,0.0),0.5)
tween.tween_property(light,"scale",Vector2(1.0,1.0),0.5)
tween.tween_property(light,"scale",Vector2(0.0,0.0),0.5)
tween.tween_property(light,"scale",Vector2(1.0,1.0),0.5)
tween.tween_interval(2)
1 Like

Are you using a tween for educational purposes, or for production? If production, then using an AnimationPlayer would be simpler and cleaner.

I don’t know much about tweens yet, but maybe it will work with: await get_tree().create_timer(2.0).timeout in a for loop

Wow, that was way simpler than I was making it. Thanks for the help!

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