【问题标题】:SDL window closes after openingSDL 窗口在打开后关闭
【发布时间】:2017-07-16 11:20:38
【问题描述】:

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

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

ma​​in.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;
}

那么问题出在哪里?我很确定我错过了一个细节......

【问题讨论】:

  • 你不应该显式调用Window析构函数,当window对象在main返回时超出范围而被破坏时会自动发生。
  • 关于你的问题,能不能详细说明一下?它构建好,没有警告?当你运行你的程序时会发生什么?如果您在调试器中单步执行代码,它会按照您的预期执行吗?

标签: c++ sdl


【解决方案1】:

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

while(SDL_PollEvent(&E))

【讨论】:

  • 那是因为break 只会跳出内部while 循环。所以你应该用while(!have_to_quit)替换外循环,并在爆发前将have_to_quit设置为真。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多