How to define `_unhandled_input` method in GDNative C++?

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

I was able to receive _ready and _process in my GDNative C++ class already and was trying to capture InputEvent in _unhandled_input. The method is declared as:

void _unhandled_input(InputEvent event);

And the compilation failed with errors. Compiler (MSVC) seems to complain about not being able to implicitly convert Variant to InputEvent. I assume this is because GDNative script try to pass every parameter of the function using Variant.

So, what is the correct way to define _unhandled_input method inside GDNative C++?

Try pointer?

void _unhandled_input(InputEvent* event)

molko824 | 2021-03-01 16:01

That method is part of Node.

I recommend that you look at the Node class where you have the input (), _ready () _process () among others.

_input

void _input(godot::Ref<godot::InputEvent> event);

_unhandled_input

void _unhandled_input(const Ref<InputEvent> event);

_unhandled_key_input

 void _unhandled_key_input(const Ref<InputEventKey> event);



To define it _input.

void YouClassName::_input(godot::Ref<godot::InputEvent> event) 
{
}

And don’t forget to register the method, otherwise it won’t work.

 void YouClassName::_register_methods() 
 {
    register_method("_input",&YouClassName::_input);
 }



An important issue, if you want to use the input event, you have to import the input.hpp library and implement it as follows.

#include "Input.hpp"

void YouClassName::_input(godot::Ref<godot::InputEvent> event) 
{
    Input* _input = Input::get_singleton();
    if(_input == nullptr) return;   

    if(_input->is_action_pressed("a"))
    {
        
    }
    if(_input->is_action_pressed("d"))
    {
       
    }
    if(_input->is_action_just_released("a") || _input->is_action_just_released("d"))
    {
        
    }
    
}

ariel | 2021-09-02 14:00

:bust_in_silhouette: Reply From: TheFamousRat

Hello logicor,
Haven’t tested this myself, so take it with a grain of salt. Usually those “can’t implicitly convert Variant to X” errors come from the fact that Godot passes everything as reference behind the scenes.

Try changing the prototype of the function to :

void _unhandled_input(godot::Ref<godot::InputEvent> event);