Switch Input control from player to enterable vehicles or other interactive devices in GDScript

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

Hello, could you please help me with:

I want my player to be able to walk around on foot and also to enter vehicles and also to interact with various sprites/machines.

So, if I press, say, the Up key, I want my player to jump. But if the player then enters a vehicle or, say, is standing next to some sprite/machine, then I want to redirect the Input to that vehicle or machine/device in question, and not to the player. So within a vehicle, the player would completely ignore the Up key and only the Vehicle would consume it and, say, increase its speed.

With languages like Java, I would use an interface, say, “InputController” which all of : player, vehicles, machines would implement :

interface InputController {
   void handleInput(event);
}

Then, in my main GameController, I might have something like :

class GameController {
  InputController currentInputController;

  onKeyEvent(event) {
     currentInputController.handle(event)
 }
}

and then just set that “currentInputController” programmatically to whatever happens to be.

My question is : what is the preferred, clean and scalable, GDScript way, ideally strongly typed solution of achieving the same thing?

many thanks for your time

Have you thought of using a state machine? Check for when the user is walking around, using a car, or whatever, and then transition to that state.

Ertain | 2020-12-25 00:36

:bust_in_silhouette: Reply From: Lopy

I see two solution, but can’t help you with the “preferred” part, you would need some poll.

The first would be an adaptation of your Java code. Instead of using [_unhandled]_input(event: InputEvent) directly, you can define another function, and have them called by a GameController that knows which one is active.

Alternatively, you can use set_process[_unhandled]_input() to systematically disable your _input()s, and only activate them when needed. Just remember to add comments stating that they are likely disabled.

Since your different objects receiving inputs may not inherit from the same builtin Nodes, you may want to type using a child Node that you would be free to type in any way.

thank you very much for your reply and for your time!

gPer2020 | 2020-12-25 07:41