|Topic was automatically imported from the old Question2Answer platform.
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.
if is_key_pressed and another_key_pressed:
do another stuff
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.
Consider using Input Map (Project → Project Settings → Input Map) instead of checking keys. It will allow you to change keymappings without changing code.
hilfazer | 2018-07-01 13:03
Many games have this issue, even the simplest ones, regardless of the language used.
You could look at GDScipt’s ‘match’ GDScript — Godot Engine (3.0) documentation in English 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 .
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!
picnic | 2018-06-30 13:26
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++
picnic | 2018-06-30 18:03
Ooh, so wish me luck xD
Thank you again!
This is old, but this answer should appear on this thread.
in situations like this, given you want to commit to using this logic instead of the other solutions posted here, you can avoid nesting if statements by using the guard clause pattern. create a function for the logic, then check the value, if it’s not what you need, immediately return the function. the rest of the code will be skipped, which is what you want when the condition doesn’t match. using several in series gets rid of all the nests and makes the code cleaner and more legible.