基于上一篇文章的D3D框架,一个简单的例程。
按键功能:
W/S 向前/向后行走
A/D 向左/向右扫视
R/F 升/降
Up/Down 俯/仰
Left/Right 偏航
N/M 滚动
代码清单:
- //
- //
- // File: cameraApp.cpp
- //
- // by tianzhihen
- //
- // 2008.10.25
- //
- // VC++8.0 camera 例程
- //
- //
- #include "d3dUtility.h"
- #include "camera.h"
- //
- // 全局变量
- //
- IDirect3DDevice9* Device = 0;
- const int Width = 640;
- const int Height = 480;
- Camera TheCamera(Camera::AIRCRAFT);
- //
- // 框架函数
- //
- bool Setup()
- {
- //
- // 建立一个基本场景
- //
- d3d::DrawBasicScene(Device, 0.0f);
- //
- // 设置投影矩阵
- //
- D3DXMATRIX proj;
- D3DXMatrixPerspectiveFovLH(
- &proj,
- D3DX_PI * 0.25f, // 45 - degree
- (float)Width / (float)Height,
- 1.0f,
- 1000.0f);
- Device->SetTransform(D3DTS_PROJECTION, &proj);
- return true;
- }
- void Cleanup()
- {
- // 第一个参数传0
- d3d::DrawBasicScene(0, 0.0f);
- }
- bool Display(float timeDelta)
- {
- if( Device )
- {
- //
- // 更新场景
- //
- if( ::GetAsyncKeyState('W') & 0x8000f )
- TheCamera.walk(4.0f * timeDelta);
- if( ::GetAsyncKeyState('S') & 0x8000f )
- TheCamera.walk(-4.0f * timeDelta);
- if( ::GetAsyncKeyState('A') & 0x8000f )
- TheCamera.strafe(-4.0f * timeDelta);
- if( ::GetAsyncKeyState('D') & 0x8000f )
- TheCamera.strafe(4.0f * timeDelta);
- if( ::GetAsyncKeyState('R') & 0x8000f )
- TheCamera.fly(4.0f * timeDelta);
- if( ::GetAsyncKeyState('F') & 0x8000f )
- TheCamera.fly(-4.0f * timeDelta);
- if( ::GetAsyncKeyState(VK_UP) & 0x8000f )
- TheCamera.pitch(1.0f * timeDelta);
- if( ::GetAsyncKeyState(VK_DOWN) & 0x8000f )
- TheCamera.pitch(-1.0f * timeDelta);
- if( ::GetAsyncKeyState(VK_LEFT) & 0x8000f )
- TheCamera.yaw(-1.0f * timeDelta);
- if( ::GetAsyncKeyState(VK_RIGHT) & 0x8000f )
- TheCamera.yaw(1.0f * timeDelta);
- if( ::GetAsyncKeyState('N') & 0x8000f )
- TheCamera.roll(1.0f * timeDelta);
- if( ::GetAsyncKeyState('M') & 0x8000f )
- TheCamera.roll(-1.0f * timeDelta);
- //
- // 更新视点矩阵,由camera位置所得
- //
- D3DXMATRIX V;
- TheCamera.getViewMatrix(&V);
- Device->SetTransform(D3DTS_VIEW, &V);
- //
- // 绘制
- //
- Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 1.0f, 0);
- Device->BeginScene();
- d3d::DrawBasicScene(Device, 1.0f);
- Device->EndScene();
- Device->Present(0, 0, 0, 0);
- }
- return true;
- }
- //
- // WndProc
- //
- LRESULT CALLBACK d3d::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
- {
- switch( msg )
- {
- case WM_DESTROY:
- ::PostQuitMessage(0);
- break;
- case WM_KEYDOWN:
- if( wParam == VK_ESCAPE )
- ::DestroyWindow(hwnd);
- break;
- }
- return ::DefWindowProc(hwnd, msg, wParam, lParam);
- }
- //
- // WinMain
- //
- int WINAPI WinMain(HINSTANCE hinstance,
- HINSTANCE prevInstance,
- PSTR cmdLine,
- int showCmd)
- {
- if(!d3d::InitD3D(hinstance,
- Width, Height, true, D3DDEVTYPE_HAL, &Device))
- {
- ::MessageBox(0, "InitD3D() - FAILED", 0, 0);
- return 0;
- }
- if(!Setup())
- {
- ::MessageBox(0, "Setup() - FAILED", 0, 0);
- return 0;
- }
- d3d::EnterMsgLoop( Display );
- Cleanup();
- Device->Release();
- return 0;
- }