SDL2教程(二):evevt driven programming

事件

上次我们采用SDL_Delay()函数来使窗口暂停一定时间
但这终究不是办法
游戏编程里总不能不让用户操作的把
今天我们就来讲讲事件

#define SDL_MAIN_HANDLED
#include "SDL.h"
#include<iostream>

using namespace std;

const int Window_WIDTH = 640;
const int Window_HEIGHT = 480;

SDL_Window* window = NULL;
SDL_Renderer* render = NULL;
SDL_Texture* tex = NULL;

bool Init()
{
    window = SDL_CreateWindow("my first SDL",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, Window_WIDTH, Window_HEIGHT,
        SDL_WINDOW_SHOWN);
    if (window == NULL)
    {
        cout << "creat window error\n";
        return false;
    }
    render = SDL_CreateRenderer(window, -1, 0);
    if (render == NULL)
    {
        cout << "creat render error\n";
        return false;
    }
    return true;
}

bool LOAD_Image()
{
    SDL_Surface* hello = NULL;
    hello = SDL_LoadBMP("hello.bmp");
    if (hello == NULL)
    {
        cout << "load bmp error\n";
        return false;
    }
    tex = SDL_CreateTextureFromSurface(render, hello);
    SDL_FreeSurface(hello);
    if (tex == NULL)
    {
        cout << "creat surface tex error\n";
        return false;
    }
    return true;
}

bool Put_Image()
{
    SDL_RenderCopy(render, tex, NULL, NULL);
    SDL_RenderPresent(render);
    SDL_Delay(1000);
    return true;
}

void Quit()
{
    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(render);
    SDL_DestroyTexture(tex);
    SDL_Quit();
}

int main(int argc, char *args[])
{
    if (Init())
    {
        if (LOAD_Image())
        {
            Put_Image();
            bool quit = false;
            SDL_Event event;
            while (!quit)
            {
                while (SDL_PollEvent(&event) != 0)
                {
                    if (event.type == SDL_QUIT) quit = true;
                }
            }
            //Put_Image();
        }
        Quit();
    }
    system("pause");
    return 0;
}

发现什么不同了吗?

加了一个evevt和SDL_Pollevent

这是一个主循环,几乎是所有游戏设计的核心,必须掌握

代码解释

中心代码为:

bool quit = false;
            SDL_Event event;
            while (!quit)
            {
                while (SDL_PollEvent(&event) != 0)
                {
                    if (event.type == SDL_QUIT) quit = true;
                }
            }

一行一行解释
开始定义一个boll类型的变量,为跳出循环的标志
在这个循环种代表退出事件(就是点窗口上的叉)
SDL_event创建一个事件

事件

就是诸如鼠标点击,键盘按键这一类的
它以队列的结构存储
每次PUSH一个出来
这是C/C++等语言里的知识
不要忘记这是面向C/C++的库
我们用SDL_Pollevent来将最早的那个事件展现出来

if (event.type == SDL_QUIT) quit = true;
我们用这个获取event的类别
如果是SDL_QUIT则quit为真
下一次循环将不再进行

事件
SDL_joybutttonevent
SDL_Mousementionevent
SDL_Keyboardevent


使用SDL_pullevevt之后,变为

事件
SDL_joybutttonevent
SDL_Mousementionevent


SDL_Keyboardevent 被Poll出来了

这就是队列的事件存储方式,先进先出原则

猜你喜欢

转载自blog.csdn.net/qq_40953281/article/details/80033599