Hope Game
Logo Glusoft
Become a Patron! Buy me a coffee!

Catch events

There are multiple types of events to catch, corresponding to a lot of actions such as a key pressed, a mouse click or a mouse motion.
If you have a joystick SDL2 map the equivalent of a xbox controller to the In the previous tutorial we have seen SDL_QuitEvent emited when the user quit the program.
But in the SDL_Event structure there are informations about the event.

Quit Event

You can access the timestamp of this event with : event.quit.timestamp

if (event.type == SDL_QUIT) {
    std::cout << "Program quit after " << event.quit.timestamp << " ticks";

Keyboard events

The most common type of events are keyboard events.
The first thing to notice, there are two type of event for the keyboard :

You can access the keyboard event with event.key:

SDL_KeyboardEvent kbe = event.key;
Inside the keyboard event structure you have the fields:

We need to explain a little bit more the SDL_Keysym, in this structure we have:

The scancode and keycode identify the key, but what is the difference?
The scancode is the physical description from a qwerty keyboard point of view and the keycode is the virtual description of the key. For example if I press the letter 'A' on a azerty keyboard the SDL_SCANCODE_Q and the SDLK_a (keycode) will be detected.

Mouse events

For the mouse event you will need to use the types SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP and SDL_MOUSEMOTION

A mouse button down event occur when a mouse button is pressed :

if (event.type == SDL_MOUSEBUTTONDOWN) {
	if (event.button.button == SDL_BUTTON_LEFT) {
		std::cout << "The left click is pressed at the time " << event.quit.timestamp << " ticks\n";

This is the same thing when a mouse button is released, you will use SDL_MOUSEBUTTONUP

if (event.type == SDL_MOUSEBUTTONUP) {
	if (event.button.button == SDL_BUTTON_RIGHT) {
		std::cout << "The left click is release at the time " << event.quit.timestamp << " ticks\n";

The last event occur when the mouse cursor is moved:

if (event.type == SDL_MOUSEMOTION) {
	std::cout << "The coordinates of the mouse cursor are (" << event.motion.x << ", " << event.motion.y << ")\n";
Post Comments
Dark theme