2017-07-16 131 views
1

我试图在GameState中创建一个游戏状态系统,我创建了窗口类和MainLoop函数,起初我相信这是因为循环不是主要的,但结果相同。SDL窗口在打开后关闭

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; 
} 

所以w ^这是问题吗?我很确定有一个细节,我想...

+0

你不应该明确地调用'Window'析构函数,当'window'对象被作为'main'返回时超出范围而被销毁时''window''会自动发生。 –

+1

至于你的问题,你能否详细阐述一下?它建立好了,没有警告?当你运行你的程序时会发生什么?如果你在调试器中逐步完成代码,它会做你期望的任何事情吗? –

回答

3

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

while(SDL_PollEvent(&E)) 
+0

谢谢!现在我又遇到了另外一个问题,我无法关闭窗口...... –

+0

这是因为'break'只会从内部'while'循环中突破。所以你应该用'while(!have_to_quit)'替换外层循环,并且在内层循环中将'have_to_quit'设置为true。 – VTT

+0

今天我太笨了,idk为什么...也许睡不着觉 –