Navigation: DirectX 9.0

Tutorial 5 - Camera Control


In the last tutorial we loaded a cube into a program. This time we will load a terrain and let the user navigate the camera around the world with the keyboard.

Figure 12.


The only additional files you need for this tutorial are:
  • terrain.x
  • ground_tex1.jpg
  • sky.JPG
You can download them here:
Download Zip

Put them in the directory where your source code is located.

terrain.x contains the sky and the terrain.

The Camera and Terrain

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:

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;

		return false;

	D3DXVECTOR3 Pos(0,300,-100.0f);
	D3DXVECTOR3 LookDirection(0,-50,100);
	D3DXVECTOR3 LookAt = Pos + LookDirection;
	camera1 = Camera(Pos, LookAt);

	model1.Load(L"terrain.x", m_d3dDevice);
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:
Download Zip