2017-07-16 187 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爲什麼...也許睡不着覺 –