http://wiki.libsdl.org/CategoryEvents
事件处理允许应用程序接收用户输入。事件处理是在调用
SDL_Init(SDL_INIT_VIDEO);
时随着视频子系统一起被初始化。
在内部,SDL把所有事件存放在一个等待处理的事件队列中去。使用SDL_PollEvent(), SDL_PeepEvents() andSDL_WaitEvent() 这些函数,你可以观察、处理 等待中 的输入事件。
事件队列自身是由一系列的SDL_Event结构体组成,一个SDL_Event对应一个等待事件。用SDL_PollEvent()函数可以读出SDL_Event结构体,然后由应用程序负责处理其中存储的信息。
http://wiki.libsdl.org/SDL_Event
typedef union SDL_Event
{
Uint32 type; /**< Event type, shared with all events */
SDL_CommonEvent common; /**< Common event data */
SDL_WindowEvent window; /**< Window event data */
SDL_KeyboardEvent key; /**< Keyboard event data */
SDL_TextEditingEvent edit; /**< Text editing event data */
SDL_TextInputEvent text; /**< Text input event data */
SDL_MouseMotionEvent motion; /**< Mouse motion event data */
SDL_MouseButtonEvent button; /**< Mouse button event data */
SDL_MouseWheelEvent wheel; /**< Mouse wheel event data */
SDL_JoyAxisEvent jaxis; /**< Joystick axis event data */
SDL_Event联合体是SDL所有事件处理中的核心数据结构。它是各种事件结构体的联合体。使用它是个简单的问题,只要知道了哪种事件类型对应哪种联合体的成员即可。
从事件队列读取事件
读取事件可以使用 SDL_PollEvent() 或者 SDL_PeepEvent()。
首先要创建一个SDL_Event结构:
SDL_Event test_event;
SDL_PollEvent() 从事件队列中移除下一个事件。如果队列中没有事件返回 0, 否则返回 1。
可以使用一个while循环依次处理事件
while (SDL_PollEvent(&test_event)) {
SDL_PollEvent()需要传入一个SDL_Event 结构指针,以便将事件信息填充进去。我们知道如果SDL_PollEvent从队列中移除一个事件,事件信息就会填充到test_event结构中,同时事件类型也会被赋值到test_event中的type成员。因此,为了处理每个事件类型,我们需要用一个switch语句。
如果要检测鼠标的移动,则需要判断事件类型是否是 SDL_MouseMotion ,若是则进一步处理SDL_Event结构中的SDL_MouseMotionEvent成员(motion)
typedef struct SDL_MouseMotionEvent
{
Uint32 type; /**< ::SDL_MOUSEMOTION */
Uint32 timestamp;
Uint32 windowID; /**< The window with mouse focus, if any */
Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
Uint32 state; /**< The current button state */
Sint32 x; /**< X coordinate, relative to window */
Sint32 y; /**< Y coordinate, relative to window */
Sint32 xrel; /**< The relative motion in the X direction */
Sint32 yrel; /**< The relative motion in the Y direction */
} SDL_MouseMotionEvent;
case SDL_MOUSEMOTION:
printf("We got a motion event.\n");
printf("Current mouse position is: (%d, %d)\n", test_event.motion.x, test_event.motion.y);
break;
default:
printf("Unhandled Event!\n");
break;
}
}
printf("Event queue empty.\n");
SDL事件处理详解:事件队列与事件类型解析
本文深入探讨了SDL事件处理机制,包括事件队列的管理、事件类型的分类及其处理方法。通过实例展示了如何读取并处理不同类型的事件,如鼠标移动、键盘输入等,为游戏开发和图形界面应用提供了实用的技术指南。
3581

被折叠的 条评论
为什么被折叠?



