First we will need a project like described in Tutorial 3. I suggest you continue
with that project or create a new project the same.
Add the following function to the top of the main.cpp file:
#define DEVICE_LOST_OR_OPERATIONAL 0
#define DEVICE_NOTRESET 1
bool IsKeyDown(int key)
//Is key down?
return (GetKeyState(key) & 0x8000);
This function can be used to check at any time whether a key is pressed. To check if the up arrow key
on the keyboard is pressed call IsKeyDown(VK_UP); VK stands for virtual key.
Now I'd better explain how the camera movement will work before we look at the next bit of code.
The up arrow key will move the camera forward. Moving forward is the same as moving along
a vector that is pointing towards the Look At point, but ignoring the Y component, so
the camera doesn't move up or down, it just moves forward in the direction it is facing.
The left and right arrow keys will pivot the camera left or right around the point it is looking at, (The LookAt vector).
I have provided a function in the Camera class to do this so all you have to do is call camera1.Pivot(amount). You can
look at Camera.cpp to see how Pivot() is implemented if you are curious.
Ok, so that explains how the camera will be controlled.
Modify the Game::InitGame() function:
bool Game::InitGame(HWND render_window)
this->m_mainWindow = render_window;
D3DXVECTOR3 LookAt = Pos + LookDirection;
camera1 = Camera(Pos, LookAt);
The code above should make sense if you understand 3d vectors.
Now the only thing left to do is handle the keyboard input;
Here is the modified UpdateGame() function:
void Game::UpdateGame(float deltaTime)
//Handle device lost event.
HRESULT coop = m_d3dDevice->TestCooperativeLevel();
if(coop != D3D_OK)
if(coop == D3DERR_DEVICELOST)
if(m_deviceStatus == DEVICE_LOST_OR_OPERATIONAL)
else if(coop == D3DERR_DEVICENOTRESET)
if(m_deviceStatus == DEVICE_NOTRESET)
That's it for this tutorial! You can download the complete source here: