2017-06-02 113 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