how to combine enum, match state and array

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

I am an godot begginner ans is trying to create an effect for my game NPC that allows it to have different idle animation randomly, here are the codes:

extends KinematicBody2D
var state = five
var next_anime= 4
onready var knight = $knight_anime
enum{
	one
	two
	three
	four
	five
}
var choose = [one,two,three,four,five]
func _ready():
	knight.play("anime_5")
func _play_anime():
	match state:
		one:
			knight.play("anime_1")
			print("play1")
		two:
			knight.play("anime_2")
			print("play2")
		three:
			knight.play("anime_3")
			print("play3")
		four:
			knight.play("anime_4")
			print("play4")
		five:
			knight.play("anime_5")
			print("play5")

func _on_knight_anime_animation_finished():
		print("swap")
		next_anime = randi()%5
		print("next",next_anime)
		print("choose",choose[next_anime])
		state = choose[next_anime]
		print("state",state)

my plan is that everytime the previous animation finished, a random int gets generated and the variable related to this int is referenced from the array, which then match the state and plays the new anime. However, I think what I have done here is put string instead the state variables I need in the array. Please tell me the right way to do it.

:bust_in_silhouette: Reply From: Juxxec

There you go:

extends KinematicBody2D

enum Animations { ONE = 1, TWO = 2, THREE = 3, FOUR = 4, FIVE = 5 }

onready var knight = $knight_anime


func _ready():
    # Use a unique seed every time
    randomize()
    # Choose a random animation to play
    _play_random_animation()


func _play_random_animation():
    var anim = Animations .values()[randi() % Animations .size()]
    knight.play("anime_%d" % anim)


func _on_knight_anime_animation_finished():
        _play_random_animation

When you give the enumeration a name, you can use the methods it provides:

  • keys() - Gives you the names of the enum constants - ["One", "Two", ... ]
  • size() - Gives you the number of constants in the enum
  • values() - Gives you the values of the constants - [1, 2, 3, ...]

What I am doing here is a simple trick.

var anim = Animations .values()[randi() % Animations .size()]

This is a common way to get a random value from an array. You generate a random number between 0 and the size of the array minus one to get an index into the array.

knight.play("anime_%d" % anim)

I am using the % operator to create a string from the value of the constant that was chosen from the enum at random. %d means replace with an integer.

If we chose the third animation, then the constant would be THREE and the string for the animation would be anime_3.

I hope this explains it.

Thank you verymuch! This is waymore simpler than my code and solves the problem!

D.Q.Li | 2023-04-14 08:48