How do I use match statement?

Godot Version



<I have made different set of animation based on which side the mouse is looking at and the player is moving at. Following code work fine but too many if statement. I would appreciate if you could teach me how to use match statement. thanks.


func run_flip2():
	if is_on_floor() and position2D.scale.x==1 and Input.is_action_pressed("move_right"):"PlayerRunForward")
	elif is_on_floor() and position2D.scale.x==1 and Input.is_action_pressed("move_left"):"PlayerRunBackward")
	elif is_on_floor() and position2D.scale.x==-1 and Input.is_action_pressed("move_right"):"PlayerRunBackward")
	elif is_on_floor() and position2D.scale.x==-1 and Input.is_action_pressed("move_left"):"PlayerRunForward")

I don’t think a match statement can help you in this situation. A match statement is designed to evaluate a single expression and test it against a list of possible values.

There are some optimisations possible regarding your code (for instance factoring the is_on_floor() condition at the beginning, and returning early if it’s false), but honestly i think it looks good like it is (dead simple and easy to understand is always superior to fancy and cryptic).


Not applicable here as @francois.delataste said, but here’s an alternative way to write this that may be clearer, depending on your preferences:

func run_flip2()
	# only play run animation when on floor
	if not is_on_floor():

	# if moving backwards, play that animation instead (will override, I believe)
	var x := position2D.scale.x
	if (x == 1 and Input.is_action_pressed("move_left")) or (x == -1 and Input.is_action_pressed("move_right")):"PlayerRunBackward")

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