SDL2 provides an event system that allows you to handle various types of events, including keyboard and mouse events. Here's an example of how to handle multiple event types in an SDL2Ā application:
#include <SDL.h>
#include <iostream>
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window{SDL_CreateWindow(
"Event Handling",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
800, 600, SDL_WINDOW_SHOWN
)};
SDL_Event event;
bool quit = false;
while (!quit) {
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
quit = true;
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym
== SDLK_ESCAPE) {
quit = true;
} else {
std::cout << "Key pressed: "
<< SDL_GetKeyName(
event.key.keysym.sym) << '\n';
}
break;
case SDL_MOUSEBUTTONDOWN:
std::cout << "Mouse button pressed: "
<< event.button.button << "\n";
break;
case SDL_MOUSEMOTION:
std::cout << "Mouse position: ("
<< event.motion.x << ", "
<< event.motion.y << ")\n";
break;
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
In this example, we use a switch
statement inside the event loop to handle different event types. The event.type
field determines the type of event thatĀ occurred.
SDL_QUIT
Ā event, we set theĀ quit
Ā flag toĀ true
Ā to exit the application.SDL_KEYDOWN
Ā event, we check if the pressed key is the Escape key ( SDLK_ESCAPE
) to quit the application. Otherwise, we print the name of the pressed key usingĀ SDL_GetKeyName
.SDL_MOUSEBUTTONDOWN
Ā event, we print the mouse button that was pressed usingĀ event.button.button
.SDL_MOUSEMOTION
Ā event, we print the current mouse position usingĀ event.motion.x
Ā andĀ event.motion.y
.You can extend this event handling code to include additional event types and perform specific actions based on your application'sĀ requirements.
Remember to include the necessary headers and initialize SDL2 properly before handling events. Also, make sure to clean up resources, such as windows and renderers, before quitting theĀ application.
Answers to questions are automatically generated and may not have been reviewed.
This guide walks you through the process of compiling SDL2, SDL_image, and SDL_ttf libraries from source