Simulate mouse and keyboard events by code?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mateusak
:warning: Old Version Published before Godot 3 was released.

Something like JoyToKey, that translates the press of a button on the controller to the press of a button on the keyboard. Is it possible?

You want to send the event back to the OS?

vnen | 2016-07-06 16:02

Yes, that’s it.

mateusak | 2016-07-06 16:42

I don’t think that’s possible (not out of the box). Also, if you want to make a JoyToKey clone, Godot might be an overkill.

vnen | 2016-07-06 16:48

Not a JoyToKey clone, just to give the idea of what I want.

mateusak | 2016-07-06 17:51

:bust_in_silhouette: Reply From: jackmakesthings

You can create and dispatch an InputEvent for cases like this. Here’s the script for a function I use to simulate a click event at a given position, for example:

func fake_click(position, flags=0):
var ev = InputEvent()
ev.type = InputEvent.MOUSE_BUTTON
ev.pressed = true
ev.global_pos = position
ev.meta = flags

For a keypress, you might have something like this:

func simulate_key(which_key):
  var ev = InputEvent()
  ev.type = InputEvent.KEY
  ev.scancode = which_key

Note that this example would expect a scancode like KEY_F, not a simple string like F; those are all pretty much what you’d expect, but you can check the class reference for @GlobalScope if you need to look one up.

You should also take a look at the documentation and the demo for using the InputMap - which might be more what you’re looking for, depending on your use case. It provides a way to bind multiple types of input to one ‘action’ code, which can in turn be hooked up to whatever functions you want it to call.

I want to send key events to the OS. Thanks for your time though.

mateusak | 2016-07-11 23:25