SDL2系列教程4-事件处理

事件循环

大多数多媒体程序依靠事件系统来处理输入。SDL为处理输入事件提供了灵活的API。本质上,SDL将来自设备(如键盘,鼠标或控制器)的输入记录为事件,将它们存储在“事件队列”中。您可以将此结构视为等待线 - 事件在线的后面排队并从线的前面取出。

在您的程序中,您将始终拥有一个事件(或“游戏”或“主”)循环来处理这些事件并根据输入运行您的程序。每次运行事件循环时,必须从事件队列中拉出每个事件(按顺序)以处理输入。这是通过函数SDL_PollEvent()完成的。此函数从队列中删除第一个事件,将值复制到SDL_Event类型的参数中。如果事件队列为空,则该函数将返回0。

轮询事件后,您可以在逻辑链中使用它来推断输入内容和响应方式。

 

SDL_Event ev;
bool running = true;

// Main loop
while ( running ) {
	// Event loop
	while ( SDL_PolLEvent( &ev ) != 0 ) {
		// Test members of ev
	}	

	// Wait before next frame
	SDL_Delay(100);
}

SDL_Event

SDL_Event包含任何子事件之一。这可以通过使用联合来实现。union描述了结构中的几个互斥数据成员。这意味着子事件类型都存储在同一个内存中,因此SDL_Event可以灵活而不浪费空间。但是,这个系统使语法稍微笨拙 - 访问子事件数据,首先必须访问SDL_Event中的子事件。

例如,访问SDL_KeyboardEvent ..

SDL_Event evt;
SDL_PollEvent( &evt );

if (evt.type == SDL_KEYDOWN) {
	switch ( evt.key.sym.sym ) { 	// Note evt.key accesses the real data, 
							// the SDL_KeyboardEvent 
		// ...
	}
}

退出

当用户希望关闭程序时, 您的事件循环将收到SDL_QUIT类型的事件。这包括按下窗口上的“x”,按ALT + F4,或以其他方式请求程序结束。这不包括结束进程或将CTRL + C发送到控制台 - 这些是不受控制的,立即中止。

因此,当您的程序收到SDL_QUIT事件时,它应该正常关闭(或提示用户提供更多信息)。事件的类型可通过其“类型”成员访问。

SDL_Event ev;
bool running = true;

// Main loop
while ( running ) {	
	// Event loop
	while ( SDL_PolLEvent( &ev ) != 0 ) {
		// check event type
		switch (ev.type) {
			case SDL_QUIT:
				// shut down
				running = false;
				break;
		}
	}	

	// Wait before next frame
	SDL_Delay(100);
}

键盘事件

键盘事件有两种形式 - SDL_KEYDOWNSDL_KEYUP。这两种类型都与SDL_KeyboardEvent相关联,后者包括键码和表示输入事件的标志。

是否按下/释放/重复键可以通过SDL_KeyboardEvent的状态和重复成员来确定,而键码和修饰键在keysym成员(SDL_Keysym)中指定

SDL_Event ev;
bool running = true;

// Main loop
while ( running ) {
	// Event loop
	while ( SDL_PolLEvent( &ev ) != 0 ) {
		// check event type
		switch (ev.type) {
			case SDL_QUIT:
				// shut down
				running = false;
				break;
			case SDL_KEYDOWN:
				// test keycode
				switch ( ev.key.keysym.sym ) {
					case SDLK_w: 
						break;
					case SDLK_s:
						break;
					// etc
				}
				break;
		}
	}	

	// Wait before next frame
	SDL_Delay(100);
}

查看SDL_KeyboardEvent以获取更多详细信息。

键盘轮询

有一种方法可以在没有事件系统的情况下获得键盘输入。这是通过直接轮询键盘。建议不要这样做,因为轮询键盘会为您提供当时的状态,而不是自上次轮询以来发生的每个事件的日志。但是,轮询仍然偶尔会有用,因此SDL提供了函数SDL_GetKeyboardState()。此函数返回包含键值的值数组。这个数组是持久的 - 它将在处理键盘事件时更新。

要访问密钥阵列中的数据,可以使用SDL_Scancode。扫描码类似于SDL_KeyboardEvent的键值,而是作为键盘状态数组的索引。

char* keys = SDL_GetKeyboardState(NULL);

// Test W key
if ( keys[SDL_SCANCODE_W] ) {
	// ...
}

鼠标事件

所有类型的事件都类似于键盘事件,因为它们具有包含多个描述输入的数据成员的事件类型。鼠标事件可以是SDL_MOUSEMOTIONSDL_MOUSEBUTTONDOWNSDL_MOUSEBUTTONUPSDL_MOUSEWHEEL类型

这些类型与SDL_MouseButtonEventSDL_MouseMotionEventSDL_MouseWheelEvent相关联。所有这些类型都包括鼠标事件的x和y坐标,以及额外的数据和修饰符。

SDL_Event ev;
bool running = true;

// Main loop
while ( running ) {
	// Event loop
	while ( SDL_PolLEvent( &ev ) != 0 ) {
		// check event type
		switch (ev.type) {
			case SDL_QUIT:
				// shut down
				running = false;
				break;
			case SDL_KEYDOWN:
				// test keycode
				switch ( ev.key.keysym.sym ) {
					case SDLK_w: 
						break;
					case SDLK_s:
						break;
					// etc
				}
				break;
			case SDL_MOUSEBUTTONUP:
				// test button
				switch ( ev.button.button ) {
					case SDL_BUTTON_LEFT:
						break;
					case SDL_BUTTON_RIGHT:
						break;
					case SDL_BUTTON_X1:
						break;
					// etc
				}
		}
	}	

	// Wait before next frame
	SDL_Delay(100);
}

其他事件

这些笔记还有许多其他类型的事件不会涵盖。我强烈建议您浏览SDL文档网站,了解如何使用这些其他类型。

活动类型:

 

 

 

用户事件

一个更短的部分 - 用户定义的事件。SDL 为此提供了结构SDL_UserEvent ; 它有任意数据成员供用户指定。此结构与SDL_RegisterEvents()SDL_PushEvent()一起使用。

SDL_RegisterEvents()用于为用户定义的事件类型分配一系列值。这些数字用作广义SDL_Event结构的“type”成员的值。SDL_PushEvent()允许您将事件添加到队列。这可以包括您的用户定义事件。

 

int userType = SDL_RegisterEvents(1);

if (userType == ((uint32_t) -1)) {
	// failure
}

SDL_Event ev;
ev.type = userType;

ev.user.code = someEvtCode;
ev.user.data1 = &someData;
ev.user.data2 = 0;

SDL_PushEvent(&ev);

 

实例代码:

    
#include <iostream>
#include <SDL2/SDL.h>

using namespace std;

bool init();
void kill();
bool load();
bool loop();

// Variables to hold our window and surfaces
SDL_Window* window;
SDL_Surface* winSurface;
SDL_Surface* image1;
SDL_Surface* image2;

int main(int argc, char** args) {

    if ( !init() ) return 1;

    if ( !load() ) return 1;

    while ( loop() ) {
        // wait before processing the next frame
        SDL_Delay(10); 
    }

    kill();
    return 0;
}

bool loop() {

    static bool renderImage2;
    SDL_Event e;

    // Blit image to entire window
    SDL_BlitSurface( image1, NULL, winSurface, NULL );

    while( SDL_PollEvent( &e ) != 0 ) {
        switch (e.type) {
            case SDL_QUIT:
                return false;
            case SDL_KEYDOWN:
                renderImage2 = true;
                break;
            case SDL_KEYUP:
                renderImage2 = false;
                // can also test individual keys, modifier flags, etc, etc.
                break;
            case SDL_MOUSEMOTION:
                // etc.
                break;
        }
    }

    if (renderImage2) {
        // Blit image to scaled portion of window
        SDL_Rect dest;
        dest.x = 160;
        dest.y = 120;
        dest.w = 320;
        dest.h = 240;
        SDL_BlitScaled(image2, NULL, winSurface, &dest);
    }

    // Update window
    SDL_UpdateWindowSurface( window );

    return true;
}

bool load() {
    // Temporary surfaces to load images into
        // This should use only 1 temp surface, but for conciseness we use two
    SDL_Surface *temp1, *temp2;

    // Load images
    temp1 = SDL_LoadBMP("test1.bmp");
    temp2 = SDL_LoadBMP("test2.bmp");

    // Make sure loads succeeded
    if ( !temp1 || !temp2 ) {
        cout << "Error loading image: " << SDL_GetError() << endl;
        return false;
    }

    // Format surfaces
    image1 = SDL_ConvertSurface( temp1, winSurface->format, 0 );
    image2 = SDL_ConvertSurface( temp2, winSurface->format, 0 );

    // Free temporary surfaces
    SDL_FreeSurface( temp1 );
    SDL_FreeSurface( temp2 );

    // Make sure format succeeded
    if ( !image1 || !image2 ) {
        cout << "Error converting surface: " << SDL_GetError() << endl;
        return false;
    }
    return true;
}

bool init() {
    // See last example for comments
    if ( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) {
        cout << "Error initializing SDL: " << SDL_GetError() << endl;
        return false;
    } 

    window = SDL_CreateWindow( "Example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN );
    if ( !window ) {
        cout << "Error creating window: " << SDL_GetError()  << endl;
        return false;
    }

    winSurface = SDL_GetWindowSurface( window );
    if ( !winSurface ) {
        cout << "Error getting surface: " << SDL_GetError() << endl;
        return false;
    }
    return true;
}

void kill() {
    // Free images
    SDL_FreeSurface( image1 );
    SDL_FreeSurface( image2 );

    // Quit
    SDL_DestroyWindow( window );
    SDL_Quit();
}

 

Makefile修改一下文件名即可;

 

按下键盘为

 

例程下载地址:

https://download.csdn.net/download/cyf15238622067/10697370

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dwyane05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值