I want to play fire on and off animation after a random period of time but for some reason the fire on animation does not play even though the print statement is working
Here is the full code in GDScript
extends Node2D
# Reference to the AnimatedSprite2D node
var animated_sprite: AnimatedSprite2D
# Called when the node enters the scene tree for the first time.
func _ready():
# Get the reference to the AnimatedSprite2D node
animated_sprite = $AnimatedSprite2D
# Start the cycle of turning fire on and off
start_fire_cycle()
# Function to control the fire animation
func fire_animation(on: bool):
if on:
animated_sprite.play("fire_on") # there is an animation named "fire_on"
else:
animated_sprite.play("fire_off") # Stop the animation when fire is off
# Coroutine to manage the fire cycle
func start_fire_cycle() -> void:
while true:
if await fire_is_on():
await get_tree().create_timer(randi_range(2, 5)).timeout
if await fire_is_off():
await get_tree().create_timer(randi_range(2, 5)).timeout
# Function to handle fire on state
func fire_is_on() -> bool:
var duration = randi_range(2, 5)
print("Fire is ON for %s seconds." % duration)
fire_animation(true) # Start the fire animation
await get_tree().create_timer(duration).timeout
return true
# Function to handle fire off state
func fire_is_off() -> bool:
var duration = randi_range(2, 5)
print("Fire is OFF for %s seconds." % duration)
fire_animation(false) # Stop the fire animation
await get_tree().create_timer(duration).timeout
return false
# Helper function to generate a random integer within a range
func randi_range(min: int, max: int) -> int:
return randi() % (max - min + 1) + min
I was expecting the fire animation to play on and off periodically
i tried to use yield but its not allowed in godot 4
New contributor
Rajat Yadav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.