0 votes

I'm working on a quite complext game, and trying to implement the game logic to control the different behaviors of the player depending on different combinations of inputs.

Something like:

if is_key_pressed and another_key_pressed:
do stuff
elif
do another stuff
elif
do other stuff

It have lots of this structures, but worse, with ifs inside ifs, and seems messy, and I feel that should exist a better way to do that.
I think this is a question about design, but i'm new to godot so I cound't figure out how to deal with it.

in Engine by (53 points)

Consider using Input Map (Project -> Project Settings -> Input Map) instead of checking keys. It will allow you to change keymappings without changing code.

1 Answer

+1 vote
Best answer

Many games have this issue, even the simplest ones, regardless of the language used.

You could look at GDScipt's 'match' http://docs.godotengine.org/en/3.0/getting_started/scripting/gdscript/gdscript_basics.html#match which might enable you to simplify a bunch of if/elif tests.

It might also be cleaner, and easier to follow, if you used a top level 'if' to farm out the next level of tests to other functions and so on.

Two other solutions: a lookup table or a decision tree (Google them) but both would require more work to implement .

by (219 points)
selected by

Ooh so there's a "switch" for Godot haha, thank you!!!

I'll check the other two solutions, decision tree should be more efficient I guess?

I think it would be a lot harder to implement than a look-up table. I suppose it boils down to exactly how many tests for how many objects as to whether it's worth the effort and whether it will even perform well enough. Good luck!

I'm not familiar with this lookup table, but after some research I now have a notion. Do you recommend me some material so I can apply it to my project? I'm not really sure how I can apply it in Godot, couldn't find something in the documentation.

No, I'm afraid you'd have to implement it yourself from scratch either in GDScript or C++

Ooh, so wish me luck xD

Thank you again!

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.