Thursday, October 20, 2011

Tutorial 6: Using Mouse and DirectInput

The 2nd part of the user input tutorial deals with using the mouse.
   1: LPDIRECTINPUTDEVICE8    m_pdInputMouse;
2: bool m_bPressedButtons[4];
3: DIMOUSESTATE m_MouseState;
4: long m_lPosX;
5: long m_lPosY;
Most of the variables are self explanatory.

Like in the last tutorial, we will have to make sure the DirectInput Interface is created before we can bind the mouse.
1: void cInput::CreateMouse()
2: {
3: // create the mouse device
4: m_pdInput->CreateDevice(GUID_SysMouse,&m_pdInputMouse, NULL);
5: 
6: // set the data format to mouse format
7: m_pdInputMouse->SetDataFormat(&c_dfDIMouse);
8: 
9: // set the control over the mouse
10: m_pdInputMouse->SetCooperativeLevel(m_hWnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND);
11: 
12: // get the current position of the cursor
13: POINT pt;
14: GetCursorPos( &pt );
15: ScreenToClient( m_hWnd, &pt );
16: m_lPosX = pt.x;
17: m_lPosY = pt.y;
18: 
19: DetectMouseMovement();
20: }
The CreateMouse is used to get control over the mouse. We first create the mouse device by calling CreateDevice. We set the data format to mouse format. To get control over the mouse we now make a call to SetCooperativeLevel and set the flags DISCL_EXCLUSIVE and DISCL_FOREGROUND. This basically sets the access level to exclusive (i.e other applications can not access the mouse) and foreground access. By foreground access we mean that the device is automatically un-acquired when the game loses focus. We then get the current position of the cursor and use the ScreenToClient function to convert the screen coordinates to client-area coordinates.
1: void cInput::DetectMouseMovement()
2: {
3: m_pdInputMouse->Acquire();
4:
5: m_pdInputMouse->GetDeviceState(sizeof(DIMOUSESTATE), LPVOID(&m_MouseState));
6: 
7: m_lPosX += GetMouseXDelta();
8: m_lPosY += GetMouseYDelta();
9: 
10: ConstrainMouseCursor();
11: 
12: // Get pressed keys
13: for ( int i = 0; i < 4; i++ )
14: {
15: if ( m_MouseState.rgbButtons[i] &0x80 )
16: {
17: m_bPressedButtons[i] = TRUE;
18: 
19: }
20: else
21: {
22: m_bPressedButtons[i] = FALSE;
23: 
24: }
25:
26: }
27: }
The DetectMouseMovement function detects the mouse movement and which buttons have been pressed on the mouse. For this we first acquire the mouse and get the device state. We update the current position of the cursor using the deltas of the mousestate. We constrain the mouseposition to the client area.  Finally, we run through all the buttons and check which ones have been pressed.
1: void cInput::Cleanup()
2: {
3: m_pdInputMouse->Unacquire();
4: m_pdInputMouse->Release();
5: }
Lastly, we have a Cleanup function, which releases the input devices That's all that we need to use the mouse in our game.

No comments :