Alternative/Best way to handle multiple is_action_pressed

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

I got into Godot engine yesterday and I’m now playing around with movement.

The problem is that as you insert more action keys via Inputmap the current way I’ve seen to handle this is:

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

I’ve tried to use an alternative to this, first with dictionaries but so far hasn’t found any good solution due to is_action_pressedreturning a bool and requiring a string.

:bust_in_silhouette: Reply From: Dooowy.

Use an override function

Heres an example in C#

This function was to be incredibly fast using the type caster. Your input right now is meta however to detect many keyboard presses would possibly require the use of an override instead of is_action_pressed. It would be incredibly messy to have an If statement check every single one. Instead we can just have a List to check each one.

public override void _UnhandledKeyInput(InputEventKey @event)
{
    if(@event is InputEventKey KeyValue)
    {
        _EscapeKey(@event);
    }
}
private void _EscapeKey(InputEventKey KeyValue)
{
    if(KeyValue.Scancode == (int)KeyList.Escape)
    {
        GetTree().Quit();
    }
}

I see, but from what I gather you can’t do override functions in gdscript like you can in C#.

piperun | 2019-07-09 15:31

Right now, your code is meta (most efficient tactic available with only GDScript). The problem is with GDScript you can’t use an override, you are indeed right. However, as the Document says (if you actually read them) C# is 3x faster than GDScript.

GDScript (Release)	13820
C#/Mono	48680
GDNative (Nim)	52780
GDNative (D)	57360
GDNative (C++)	58120

The above is a benchmark on the amount of Sprites loaded and called using a function by spawning in objects and setting their texture to the files recursively. C# is 2nd to best, While GDScript is insufficient. Please be aware than using both Languages (as many professional programmers use more than 1) is not a downside. In a Computer Science class it fails the basic algorithm design in the designing process because we’re striving to have most efficient and quickest algorithm available. So take the time to learn both of these languages it will be beneficial in the future!
Don’t be a one-trick.

Dooowy. | 2019-07-10 00:08

Thanks I’m well aware of C# being much faster than GDScript, technically C++ is the fastest for Godot :).

The question then becomes how do I use both C# and C++ in that case?

piperun | 2019-07-11 23:23