我正在开发 Windows 游戏,我有这个:
bool game_cont;
LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_QUIT: case WM_CLOSE: case WM_DESTROY: game_cont = false; break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
int WINAPI WinMain(/*lots of parameters*/)
{
//tedious initialization
//game loop
while(game_cont)
{
//give message to WinProc
if(!GameRun()) game_cont = false;
}
return 0;
}
我想知道是否有比让 game_cont
成为全局的更好的方法(暂时忽略计时器等)。简而言之,我需要能够从 WinProc
中退出 WinMain
中的 while,这样如果用户以不同于游戏的方式按下关闭游戏在游戏菜单中,程序不会在内存中继续运行。 (就像我在 WinProc
中没有 game_cont..
语句测试它时所做的那样。
哦,顺便说一句,GameRun
基本上是一个 bool 值,它在游戏结束时返回 false,否则返回 true。
最佳答案
是的,使用 PeekMessage ,这是游戏开发的标准。
我认为这是最好的方法:
int Run()
{
MSG msg;
while(true)
{
if(::PeekMessage(&msg,0,0,0 PM_REMOVE))
{
if(msg.message == WM_QUIT ||
msg.message == WM_CLOSE ||
msg.message == WM_DESTROY)
break;
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
else
{
//Run game code
if(!GameRun())
break;
}
}
}
另外,看看 this (特别是第一个答案)
关于c++ - 有没有更好的方法来创建这个游戏循环? (C++/Windows ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1800250/