Randomising Speed and and Frames of an animated Sprite

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ziggy

i’m currently trying to create an animated sprite that has three images it cycles through, I want the animation to as it selects the next frame for it to be a random one of the three images, I also want it to as it cycles through to randomise the speed as to which the animation plays, I’m fairly new to this is there a loop or something i could use to make this cycle of randomisation repeat over?

this is my code so far:

class_name SpriteFrameResource

const name: String = “walk”

var imageOne = load(“res://Assets/Person Still.png”)
var imageTwo = load(“res://Assets/Person Step 1.png”)
var imageThree = load(“res://Assets/Person Walking.png”)

var randomimage = rand_range(0, 2)

func getFrames() → SpriteFrames:

if randomimage == 0:
	imagenumber = imageOne
elif randomimage == 1:
	imagenumber = imageTwo
else:
	imagenumber = imageThree

self.add_animation(name)

self.add_frame(name, imagenumber)
self.add_frame(name, imagenumber)
self.add_frame(name, imagenumber)
self.set_animation_loop(name, true)
self.set_animation_speed(name, rand_range(1, 5))

return self
:bust_in_silhouette: Reply From: Gluon

if you need something to just repeat you have the function process which would perform the task each run but you might find this cycles through the animation very quickly.

Nonetheless you could do something as simple as this

func _process(delta):
    getFrames()

and this would call getFrames every cycle.

if you want to do it based on a timer (which I would suggest might be better) you can do something like this;

func _ready():
    timerSetup()

func timerSetup():
	var ti = Timer.new()
	ti.one_shot = true
	ti.autostart = true
	ti.wait_time = 1
	ti.connect("timeout", self, "getFrames")
	add_child(ti)

and then in getFrames add another call to timerSetup to create the next frame. This way you can easily control how quickly the frames change.