randommetadataspritegodotgodot4

Randomly Choose Animation in an Animated Sprite


Firstly, gotta make sure AnimatedSprite2D is the right node to use. I'm making one of those random clicker games where you click a button and get a random chance of getting different items. I need certain items to be rarer than others, and the sprite to show the item you get, but also be able to send info such as that item's rarity, name, etc.

Right now I was thinking of having a bunch of one frame animations on one animated sprite and then using the name of the animation to find the metadata.

If AnimatedSprite2D is the right thing to use, what would the script look like?


Solution

  • I'm not sure which node would be better for your case so I'm writing the solution for both AnimatedSprite2D & AnimationPlayer incase your preference changes in the future

    AnimatedSprite2D

    @onready var animated_sprite_2d:AnimatedSprite2D = $AnimatedSprite2D
    
    func play_random_animation():
        var animation_names := animated_sprite_2d.sprite_frames.get_animation_names()
        
        if(!len(animation_names)):
            return
        
        var random_ani_name = animation_names[randi() % animation_names.size()]
        animated_sprite_2d.play(random_ani_name)
    

    AnimationPlayer

    @onready var animation_player:AnimationPlayer = $AnimationPlayer
    
    func play_random_animation():
        var animation_names := animation_player.get_animation_list()
        
        if(!len(animation_names)):
            return
        
        var random_ani_name = animation_names[randi() % animation_names.size()]
        animation_player.play(random_ani_name)
    

    Note: Also you might want to look into randomize() for true randomness.

    Here are the relevant documentation links for classes used:

    1. AnimatedSprite2D
    2. SpriteFrames
    3. AnimationPlayer
    4. AnimationMixer