Is there any good way to simplify this mega-if statement?

Godot Version

4.3 stable

Question

I’m making a snake clone game currently, but it’s just so unsatisfying to have a huge if statement in the middle of my code. Here it is for reference:

if Input.is_action_just_pressed("ui_left"):
		last_input = next_input
		next_input = LEFT
	elif Input.is_action_just_pressed("ui_right"):
		last_input = next_input
		next_input = RIGHT
	elif Input.is_action_just_pressed("ui_up"):
		last_input = next_input
		next_input = UP
	elif Input.is_action_just_pressed("ui_down"):
		last_input = next_input
		next_input = DOWN

Is there any realistic way to simplify this?

1 Like

You could maybe just make them 4 different if statements? They are all being activated from the key press right?

That could make it look a little bit neater and it would make it more like a movement script if that’s what your going for.

I had to set up a test scene with this script attached:

extends Node2D

enum Direction { NONE, LEFT, RIGHT, UP, DOWN }

var next_input = Direction.NONE
var last_input = Direction.NONE

func _input(_event):
	if Input.is_action_just_pressed("ui_left"):
		last_input = next_input
		next_input = Direction.LEFT
		print(Direction.keys()[next_input])
	elif Input.is_action_just_pressed("ui_right"):
		last_input = next_input
		next_input = Direction.RIGHT
		print(Direction.keys()[next_input])
	elif Input.is_action_just_pressed("ui_up"):
		last_input = next_input
		next_input = Direction.UP
		print(Direction.keys()[next_input])
	elif Input.is_action_just_pressed("ui_down"):
		last_input = next_input
		next_input = Direction.DOWN
		print(Direction.keys()[next_input])

Here if you just run that scene, when I press up, down, left, right etc it prints out the relevant direction. This is using your if statement but in a working scene I can test.

If you now add an input_map like this:

var input_map = {
	"ui_left": Direction.LEFT,
	"ui_right": Direction.RIGHT,
	"ui_up": Direction.UP,
	"ui_down": Direction.DOWN
}

Your if statement can be reduced to this:

func _input(_event):
	for action in input_map:
		if Input.is_action_just_pressed(action):
			last_input = next_input
			next_input = input_map[action]
			break

So the entire test scene script would look like this:

extends Node2D

enum Direction { NONE, LEFT, RIGHT, UP, DOWN }

var next_input = Direction.NONE
var last_input = Direction.NONE

var input_map = {
	"ui_left": Direction.LEFT,
	"ui_right": Direction.RIGHT,
	"ui_up": Direction.UP,
	"ui_down": Direction.DOWN
}

func _input(_event):
	for action in input_map:
		if Input.is_action_just_pressed(action):
			last_input = next_input
			next_input = input_map[action]
			print(Direction.keys()[next_input])
			break

I love these ‘simplify this’ type questions :slight_smile:

Hope that is in some way helpful.

2 Likes