问题描述
我的 SDL2 应用程序中的主循环函数如下所示:
SDL_Event e;
while (win.Getopen()) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) win.Close();
}
}
而且它不起作用。在 SDL_QUIT std::cout
期间将 if
放入循环中不会打印任何内容。我在这里做错了吗?我的窗口类构造函数和析构函数是:
Window::Window(const char* title,int x,int y,int w,int h,SDL_Surface* icon = IMG_Load("icon.png")) {
this->Position.x = x;
this->Position.y = y;
this->Position.w = w;
this->Position.h = h;
this->Win = SDL_CreateWindow(title,this->Position.x,this->Position.y,this->Position.w,this->Position.h,SDL_WINDOW_SHOWN);
this->Renderer = SDL_CreateRenderer(this->GetWin(),-1,SDL_RENDERER_PRESENTVSYNC);
this->WindowIcon = icon;
SDL_SetwindowIcon(this->GetWin(),this->WindowIcon);
this->Open = true;
}
Window::~Window() {
SDL_DestroyWindow(this->Win);
SDL_DestroyRenderer(this->Renderer);
SDL_FreeSurface(this->WindowIcon);
}
这对我来说似乎很好,所以我不确定我的代码有什么问题。 Window::Getopen()
返回布尔值 Open
,Window::Close()
将 Open
设置为 false,从而结束游戏循环。
解决方法
我无法发表评论,但请尝试以下操作:
SDL_Event event;
while (running)
{
while (SDL_PollEvent(&event))
{
std::cout << "Polling events" << std::endl;
if (event.type == SDL_QUIT){
std::cout << "Quit program!" << std::endl;
}
}
}
看看你是否有任何输出。
编辑:创建一个新项目(是的,我知道这是一个巨大的痛苦,哈哈)并在单个文件中使用它,如果它可以正常工作,请使用 lmk
#include <SDL2/SDL.h>
#include <iostream>
int main(int argc,char* argv[])
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window = SDL_CreateWindow("Program",30,500,SDL_WINDOW_OPENGL);// | SDL_WINDOW_SHOWN);
SDL_Renderer *renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED );
SDL_Event event;
bool running = true;
while (running){
while (SDL_PollEvent(&event)){
if (event.type == SDL_QUIT){
running = false;
break;
}
}
SDL_SetRenderDrawColor(renderer,255,255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}