写一个游戏引擎的头文件(.h);
写一个游戏引擎的实现文件(.cpp);
在编程中调用游戏引擎,制作用方向键控制地球上下左右乱跑的简单动作。
一 、在VS2015中新建一个 Visual C++ 常规空项目ball。
首先,添加游戏引擎的头文件GameEngine.h和实现文件GameEngine.cpp。详细步骤如下:
二 、游戏引擎的头文件 GameEngine.h 源代码:
#pragma once
#include
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR szCmdLine,
int iCmdShow);
LRESULT CALLBACK WndProc(HWND hWnd,
UINT msg,
WPARAM wParam,
LPARAM lParam);
BOOL GameInitialize(HINSTANCE hInstance);
void GameStart(HWND hWindow);
void GameEnd();
void GameActivate(HWND hWindow);
void GameDeactivate(HWND hWindow);
void GamePaint(HDC hDC);
void GameCycle();
void HandleKeys();
class GameEngine
{
protected:
static GameEngine* m_pGameEngine;
HINSTANCE m_hInstance;
HWND m_hWindow;
TCHAR m_szWindowClass[32];
TCHAR m_szTitle[32];
WORD m_wIcon, m_wSmallIcon;
int m_iWidth, m_iHeight;
int m_iFrameDelay;
BOOL m_bSleep;
public:
GameEngine(HINSTANCE hInstance,
LPTSTR szWindowClass,
LPTSTR szTitle,
WORD wIcon,
WORD wSmallIcon,
int iWidth = 640,
int iHeight = 480);
virtual ~GameEngine();
static GameEngine* GetEngine() { return m_pGameEngine; };
BOOL Initialize(int iCmdShow);
LRESULT HandleEvent(HWND hWindow,
UINT msg,
WPARAM wParam,
LPARAM lParam);
void ErrorQuit(LPTSTR szErrorMsg);
HINSTANCE GetInstance() { return m_hInstance; };
HWND GetWindow() { return m_hWindow; };
void SetWindow(HWND hWindow) { m_hWindow = hWindow; };
LPTSTR GetTitle() { return m_szTitle; };
WORD GetIcon() { return m_wIcon; };
WORD GetSmallIcon() { return m_wSmallIcon; };
int GetWidth() { return m_iWidth; };
int GetHeight() { return m_iHeight; };
int GetFrameDelay() { return m_iFrameDelay; };
void SetFrameRate(int iFrameRate) { m_iFrameDelay = 1000 /
iFrameRate; };
BOOL GetSleep() { return m_bSleep; };
void SetSleep(BOOL bSleep) { m_bSleep = bSleep; };
};
三 、游戏引擎实现文件 GameEngine.cpp 源代码:
#include “GameEngine.h”
GameEngine *GameEngine::m_pGameEngine = NULL;
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR szCmdLine,
int iCmdShow)
{
MSG msg;
static int iTickTrigger = 0;
int iTickCount;
if (GameInitialize(hInstance))
{
//初始化游戏引擎
if (!GameEngine::GetEngine()->Initialize(iCmdShow))
return FALSE;
//进入主消息循环
while (TRUE)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// 处理消息
if (msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
//确保游戏引擎不在休眠状态
if (!GameEngine::GetEngine()->GetSleep())
{
//查看是否已过游戏周期
iTickCount = GetTickCount();
if (iTickCount > iTickTrigger)
{
iTickTrigger = iTickCount +
GameEngine::GetEngine()->GetFrameDel