How do I use match statement?

Godot Version

<3.5>

Question

<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.

Code:

func run_flip2():
	if is_on_floor() and position2D.scale.x==1 and Input.is_action_pressed("move_right"):
		_animation_player.play("PlayerRunForward")
	elif is_on_floor() and position2D.scale.x==1 and Input.is_action_pressed("move_left"):
		_animation_player.play("PlayerRunBackward")
	elif is_on_floor() and position2D.scale.x==-1 and Input.is_action_pressed("move_right"):
		_animation_player.play("PlayerRunBackward")
	elif is_on_floor() and position2D.scale.x==-1 and Input.is_action_pressed("move_left"):
		_animation_player.play("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).

2 Likes

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():
		return 

	_animation_player.play("PlayerRunForward")

	# 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")):
		_animation_player.play("PlayerRunBackward")
2 Likes

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