Search code examples
typescriptdecentralanddecentraland-ecs

Fire an event with Decentraland SDK


I'm trying to fire a custom event in my Decentraland scene. According with the docs, I just need to do something like:

const events = new EventManager()
events.fireEvent(new MyEvent(field1, field2))

So, following that example I'm trying to simulate the E user input when users click on a UIImage. To accomplish that:

  1. I setted the onClick property of the button like this:
let btn = new UIImage(someContainer, new Texture('assets/images/btn.png'))
btn.onClick = () => { triggerPrimaryInput() }
  1. The triggerPrimaryInput function is like:
triggerPrimaryInput()
{
    const simulatedEvent: LocalActionButtonEvent = {
        origin: new Vector3(0, 0, 0),
        direction: new Vector3(0, 0, 0),
        button: ActionButton.PRIMARY,
        buttonId: 1,
        type: 1
    }

    const em = new EventManager
    em.fireEvent(simulatedEvent)
}
  1. When I do a click on the button, Chrome console shows the error:
Error: Error: The EventConstructor is not registered

Because of that, I created a new class using the @EventConstructor() decorator and I put the triggerPrimaryInput() function's logic in the constructor, but the error keeps the same.


Solution

  • Well, debuging Decentraland's Input.ts I finally solve my problem. I just needed to do:

    // Create the button and set the onClick property
    let btn = new UIImage(someContainer, new Texture('assets/images/btn.png'))
    btn.onClick = () => { triggerPrimaryInput() }
    
    function triggerPrimaryInput()
    {
        // Define the input event
        const simulatedEvent: LocalActionButtonEvent = {
            origin: new Vector3(0, 0, 0),
            direction: new Vector3(0, 0, 0),
            button: ActionButton.PRIMARY,
            buttonId: 1,
            type: 1
        }
    
        // Call this method using the simulated event
        Input.instance.handlePointerEvent(simulatedEvent)
    }
    
    

    With that, I can simulate the E keyboard input when the user clic over a button. Using this strategy I was able to create a custom UI allowing the user to interact with an NPC avoiding the use of the dialogs provided by NPC-Utils