0 votes

-Godot 3.1.1 Stable

Using currently:

if Input.is_action_pressed("ui_left"):
if Input.is_action_pressed("ui_right"):
if Input.is_action_pressed("ui_down"):
if Input.is_action_pressed("ui_up"):

It is possible to use match to eliminate these bunch of if?

match Input.is_action_pressed():
    "ui_left":#stuff
    "ui_right":#stuff

Couldn't figure it out as it needs a argument in is_action_pressed().

in Engine by (371 points)

1 Answer

+1 vote
Best answer

Looking at the docs for the Input I don't see a way to do like you mention, as there are not methods that would allow something like that. But I can see 2 different ways you could do it, but I'm not sure you should.

1) Forget everything about the Input and use InputEvent by implementing the _inputs method, by doing that you can catch open the event and use the to_text() to check what key was pressed. And since the to_text method returns a string it can be directly put into the match.
A warning, I wouldn't do this because you lose the entire InputMap thing and are basically processing the raw inputs manually and ignoring all the niceties Godot provides

2) You change the way you process entirely, you declare a Dictionary where the keys are the inputs and the value is the function that processes that input, ideally you would use a lambda for this but it seems to not be supported yet, github issue for tracking, so as a poor men replacement you can save the function name as the value.
Then whenever you are checking for inputs, you loop through the keys of the dictionary searching for a match and whenever there is one you use the call method to call the appropriate function. Something like this:

for key in inputsDictionary.keys():
    if Input.is_action_pressed(key):
        call(inputsDictionary[key])

This will probably work, but i'm not sure if it worth the effort.

by (566 points)
selected by

Your writing was really easy to follow, you make tutorials don't you? :) I got what you mean in point 1, will be looking more into what you elaborated in point 2, looks interesting, thank you for the complete response!

I don't make tutorials, but I work as a software developer and communication is key to make sure everyone understands you, so I got used to it ;)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.