Step1: Find mouse position
//cursor position now in p.x and p.y
float x = static_cast<float>(p.x);
float y = static_cast<float>(p.y);
Step2: Convert positions to usable values
x = 2 * x / static_cast<float>(SCREEN_WIDTH) – 1;
y = 2 * y / static_cast<float>(SCREEN_HEIGHT) – 1;
You can multiply the above values with a ‘sensitivity’ factor to adjust the sensitivity of mouse.
Step4: Assign values to Camera rotation
CAMERA.rotation.x = sensitivity * x;
CAMERA.rotation.y = -sensitivity * y;
I set sensitivity to 5.
We shall use the ‘D3DXMatrixLookAtLH’ function in the camera to get the World to View matrix.
D3DXMATRIX* D3DXMatrixLookAtLH( _Inout_ D3DXMATRIX *pOut, _In_ const D3DXVECTOR3 *pEye, _In_ const D3DXVECTOR3 *pAt, _In_ const D3DXVECTOR3 *pUp );
pEye-> Camera’s position
pAT-> Look at position..A point in world co-ordinates where the camera will look at
pUp-> The Up vector..normally set to D3DXVECTOR3(0, 1, 0)
We need to find the pAt vector.
We have the rotation of the camera.
We can use trigonometry to calculate a point which is at unit distance away from the Camera’s position and which is at ‘x’ degrees in XZ plane and ‘y’ degrees in YZ plane.
We can do this as follows->
D3DXVECTOR3 lookForward = D3DXVECTOR3(0,0,0);
lookForward.x = sin(transform.rotation.x );
lookForward.z = cos(transform.rotation.x );
lookForward.y = sin(transform.rotation.y );
Step6: Calculate pAt point.
So ‘lookForward’ gives us the look At point with respect to the origin. Add this to the camera’s position to get the effective look at point.
lookForward += CAMERA_POSITION;
You can now calculate the forward vector of the camera. You can use this to move camera’s position in the direction it is looking at.
D3DXVec3Normalize(&transform.forward, &D3DXVECTOR3(lookForward – CAMERA_POSITION));
The final matrix creation will look like this
D3DXMatrixLookAtLH(&transform_worldToView, CAMERA_POSITION, &(lookForward), &D3DXVECTOR3(0, 1, 0));