Skip to content

Event Handler

Nick McDonald edited this page May 17, 2020 · 1 revision

TinyEngine - Event Handler

The event class uses SDL2 to poll events. It then evaluates these inputs and stores them in an easily accessible format in the Tiny::event class.

Principle

Every tick, the Tiny::event.input() and Tiny::event.handle() functions are called first. The input function reads inputs and interprets them. The inputs are stored inside the relevant data structures inside Tiny::event. The handle function calls the user-defined event handler:

    Tiny::event.handler = [&](){ /* ... user defined event handler ... */ }

and additionally does some default event handling required for the function of TinyEngine. The default handling and how to define your event handler are described below.

Default Handling

By default, the event-handler does the following:

    - Checks and handles window-resize events
    - F11 fullscreen toggles
    - ESC key to toggle the interface visibility

Note that all of these events still set flags inside the Tiny::event class in case you need to handle these events too.

User-Defined Event Handler

The user-defined event handler can take the input state stored in Tiny::event and do whatever. This class uses SDL2 based enumerators.

Actively pressed keys can be accessed using:

    if(Tiny::event.active[SDLK_a])
            std::cout<<"Key A is being pressed"<<std::endl;

Key-press events (triggered on key-up) are stored in a queue:

    if(!Tiny::event.press.empty() && Tiny::event.press.back() == SDLK_a)
            std::cout<<"A was pressed"<<std::endl;

It is exactly analogous for mouse buttons (Tiny::event.click and Tiny::event.clicked).

Mouse movement events are tracked in a variable mouse. Whether the mouse position has been updated since the last tick is stored in a boolean mousemove.

    if(Tiny::event.mousemove){
            std::cout<<Tiny::event.mouse.x<<std::endl;
            std::cout<<Tiny::event.mouse.y<<std::endl;
            std::cout<<Tiny::event.mouse.relx<<std::endl;
            std::cout<<Tiny::event.mouse.rely<<std::endl;
    }

When a click event is registered, the current mouse position is accessible from Tiny::event.mouse.

Scrolling behavior is stored in a variable scroll, which contains four booleans posx, posy, negx and negy which determine at a tick what the scrolling behavior is.

Side-Note: The user-defined event handler can really do anything. It is conveniently called at a position in the standard game loop after inputs are received, before their flags are reset and before the user-defined game loop is executed and finally rendering occurs. Therefore, it is recommended to define input-event based behavior here.

Clone this wiki locally