打开后SDL窗口关闭

时间:2017-07-16 11:20:38

标签: c++ sdl

我尝试制作一个游戏状态系统,我在我的GameState中创建了窗口类和一个MainLoop函数,起初我认为这是因为循环不是主要的,而是相同的结果。

Window.cpp:

#include "Window.h"

using namespace std;

Window::Window(char* title, int width, int height, Uint32 flags)
{
    if (SDL_Init(SDL_INIT_EVERYTHING))
    {
        cerr << "SDL failed to init: " << SDL_GetError() << endl;
        throw;
    }

    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    window = SDL_CreateWindow("DirtyCraft", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags);

    if (window == NULL)
        throw;

    context = SDL_GL_CreateContext(window);


    GLenum error = glewInit();
    if (error != GLEW_OK)
    {
        cerr << "Glew: " << glewGetErrorString(error) << endl;
        throw;
    }

}


Window::~Window()
{
    SDL_DestroyWindow(window);

    SDL_Quit();
}

window.h中:

#pragma once
#include <iostream>
#include <SDL.h>
#define GLEW_STATIC
#include <GL/glew.h>

class Window
{
public:
    Window(char* title, int width, int height, Uint32 flags);
    ~Window();
    SDL_Window *window;
    SDL_GLContext context;
};

main.cpp 循环在哪里:

#include <iostream>
#include <SDL.h>
#define GLEW_STATIC
#include <GL/glew.h>

#include "Window.h"
#include "MainGame.h"

using namespace std;

#define WIDTH 640
#define HEIGHT 480

int main(int argc, char* argv[])
{
    Window window("DirtyCraft", WIDTH, HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI);

    //MainGame MainGame(window);

    //MainGame.MainLoop();
    while (true)
    {
        SDL_Event E;
        if (SDL_PollEvent(&E))
        {
            if (E.type == SDL_QUIT);
                break;
        }

        glClear(GL_COLOR_BUFFER_BIT);
        glClearColor(0.15f, 0.5f, 0.5f, 1.0f);

        SDL_GL_SwapWindow(window.window);
    }

    window.~Window();

    return 0;
}

问题出在哪里?我很确定有一个我想念的细节......

1 个答案:

答案 0 :(得分:3)

我认为你的消息拉环是错误的。您应该拉出所有事件,然后才执行交换等。现在很可能您的窗口没有正确显示,因为它没有完成处理初始化消息。所以你应该把它改成

while(SDL_PollEvent(&E))