MakeCode has something called an event bus that we use for propagating events through the game engine. This is a concept that is common to all of our editors, not just arcade.
Basically, you can think of the event bus as a way for different parts of the code base to talk to each other. Any piece of code can raise an event on the event bus which causes all code that has subscribed to that event to be triggered. Every event that’s raised on the bus has two values: an event id and a component id. The event id is just an arbitrary number unique to that event, and the component id is an id number that represents the hardware component that generated the event (e.g. the A button, the Up button, etc.)
All of the hardware inputs in Arcade are implemented using the event bus. We write some C++ code that pushes the events on to the event bus and some TypeScript code that then subscribes to those events and implements the actual APIs that you reference in your user project.
That’s all a little abstract, so let’s look at an example of what happens when a button is pressed.
When the C++ code detects that the button has been pressed, it fires the INTERNAL_KEY_DOWN event on the event bus. This has an event id of 2051. The A Button in arcade has a component id of 5. So, when the A button is pressed the event fired on the event bus will look like this:
eventId: 2051, componentId: 5
Inside of controllerOverrides.ts we create a Button object for the A button. This is the controller.A object that you may have seen if you’ve ever looked at the TypeScript in an arcade project. That Button object subscribes to the INTERNAL_KEY_DOWN event in controllerButton.ts and updates the state when the event comes in on the event bus.
Again, I get that this is a little complicated, so let’s try an experiment to make things a little clearer. Any piece of code can fire events on the event bus, not just C++, so what would happen if we wrote some code that fired an event with event id 2051 and component id 5? Try pasting this code into an empty project:
controller.A.onEvent(ControllerButtonEvent.Pressed, () => {
scene.setBackgroundColor(3)
})
control.raiseEvent(2051, 5)
If you run that, you’ll see that the A button event triggers without you actually pressing the button!