How we can use "Match" with "Input.is_action_pressed()"?

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

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

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

:bust_in_silhouette: Reply From: tastyshrimp

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

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

Your writing was really easy to follow, you make tutorials don’t you? :slight_smile: 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!

The_Black_Chess_King | 2019-12-26 01:35

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 :wink:

tastyshrimp | 2019-12-26 10:10