2017-06-02 42 views
0

我想寫使用OpenGL和SDL2一個基本的遊戲,但每當我運行的程序窗口立即關閉SDL2 OpenGL窗口會馬上閉合

Window.cpp

#include "Window.h" 
#include <GL/glew.h> 

Window::Window(const char* title) 
{ 
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); 
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); 
SDL_GL_SetAttribute(SDL_GL_GREEN_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(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 900, 900, SDL_WINDOW_OPENGL); 
context = SDL_GL_CreateContext(window); 

GLenum status = glewInit(); 

} 


Window::~Window() 
{ 
SDL_DestroyWindow(window); 
SDL_GL_DeleteContext(context); 
SDL_Quit(); 
} 

    void Window::Input() 
{ 
SDL_Event e; 

while (true) 
{ 
    if (e.type = SDL_QUIT) 
    { 
     exit(0); 
    } 
} 
    } 

    void Window::Update() 
    { 
SDL_GL_SwapWindow(window); 
Input(); 
    } 

在window.h

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

    class Window 
    { 
SDL_Window* window; 
SDL_GLContext context; 

    public: 
void Input(); 
void Update(); 
Window(const char* title); 
~Window(); 
    }; 

Main.cpp的

#include <SDL.h> 
    #include <GL\glew.h> 
    #include "Window.h" 
    #include <iostream> 

    using namespace std; 

    int main(int argc, char* argv[]) 
    { 
Window window("Window"); 

while (true) 
{ 
    glClearColor(0, 1, 0, 0); 
    glClear(GL_COLOR_BUFFER_BIT); 

    window.Update(); 
} 

return 0; 
    } 

當我運行代碼時,我會看到一個綠色的窗口,然後立即崩潰。當我刪除輸入();從我的更新功能它的窗口不會崩潰,但它沒有響應。我曾試圖改變SDL_PollEVent到SDL_WaitEvent並添加延遲輸入功能,但沒有任何工程

回答

1

第一件事,您使用的是賦值運算符的時候,你可能要檢查等價:

if (e.type = SDL_QUIT) 

應該是:

if (e.type == SDL_QUIT) 

此外,您還有其他問題。您在測試之前聲明SDL_Event e;聯合,但不會將其初始化爲任何值。然後你繼續循環該變量,等待它被設置爲退出。沒有什麼可以改變該變量的值,那麼你的循環將如何退出?

+0

感謝它現在的工作 – Abdision

+0

@Abdision:使用[Yoda條件](https://en.wikipedia.org/wiki/Yoda_conditions),你應該! – genpfault