The choice between using events and state checking for mouse input depends on your specific needs. Let's explore the key differences.
An event-based approach might look something like this:
#include <SDL.h>
#include <iostream>
#include "Window.h"
void HandleMouseEvent(SDL_Event& E) {
if (E.type == SDL_MOUSEMOTION) {
std::cout << "\nMouse moved to: ("
<< E.motion.x << ", " << E.motion.y;
} else if (E.type == SDL_MOUSEBUTTONDOWN) {
std::cout << "\nButton pressed at: ("
<< E.button.x << ", " << E.button.y;
}
}
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
Window GameWindow;
SDL_Event E;
while (true) {
while (SDL_PollEvent(&E)) {
HandleMouseEvent(E);
}
GameWindow.Update();
}
SDL_Quit();
return 0;
}
Mouse moved to: 110, 102
Mouse moved to: 111, 102
Button pressed at: 111, 102
Mouse moved to: 106, 102
Implementing the same functionality using a state-based approach could look like this
#include <SDL.h>
#include <iostream>
#include "Window.h"
void CheckMouseState() {
int x, y;
Uint32 Buttons = SDL_GetMouseState(&x, &y);
std::cout << "Current mouse state - Position:"
" (" << x << ", " << y << ") ";
if (Buttons & SDL_BUTTON_LMASK) {
std::cout << "Left button pressed";
}
std::cout << "\n";
}
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
Window GameWindow;
SDL_Event E;
while (true) {
while (SDL_PollEvent(&E)) {
// Handle other events...
}
CheckMouseState();
GameWindow.Update();
}
SDL_Quit();
return 0;
}
Current mouse state - Position (0, 43)
Current mouse state - Position (1, 43)
Current mouse state - Position (1, 44) Left Button Pressed
Current mouse state - Position (1, 44) Left Button Pressed
Timing
Data Capture
Use Cases
Events are better for:
State is better for:
Performance
Choose events when you need to know about every change, and state checking when you just need to know the current situation at specific times.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to monitor mouse position and button states in real-time using SDL's state query functions