Nav: (Display/Hide) - Home - About the Author / this page

Current Projects: Americana Engine (Game Engine Development)

Tuesday, March 19, 2013

Programming Keyboard Movement

After days of figuring out the logic behind mapping key presses to moving backgrounds and sprites, I have a somewhat functional copy of the game engine - so called Banana Slug*. Characters can run using the shift key, although how many characters have running animations is strictly based on budget.

This code is so complex - maybe 150 lines to control basic map and character drawing functions. And we still have a variety of sprite overlays to draw as well as anything menu and dialogue related, as well as reading scripts from an external file. Lots of math involved in manually calculating the draw positions and figuring out an equation for this. Good thing I took those applied math courses.

Keyboard Movement Code

This modifies the dxinput.cpp and dxinput.h file found in the book Beginning Game Programming, 2nd Edition by doing the following:

  • Assigns key_lock[256] as a bool array.
  • Modify Poll_Keyboard() to be the following:
    void Poll_Keyboard()
     if (dikeyboard != NULL)
      HRESULT result; 
      result = dikeyboard->GetDeviceState(sizeof(keys), (LPVOID)&keys);
       if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED))
       for (int i = 0; i < 256; i++)
        if(!(keys[i] & 0x80) && (key_lock[i]))
         key_lock[i] = false;
  • Added a Key_Down_Once function:
    bool Key_Down_Once(int key)
     if ((keys[key] & 0x80) && (key_lock[key] == false))
     {key_lock[key] = true; 
     return true;}
     else return false;
  • Adding the function prototypes in the header file

When the keyboard is polled, it will check to see if the keyboard is acquired (via GetDeviceState) and if it isn't it will attempt to reacquire it. The keyboard is automatically unacquired when the program loses focus and without this addition, the program will no longer receive input from the keyboard. (Code regarding reacquiring input devices aren't covered in the 2nd edition in the Game Programming book, and although a similar function appears in the code on the CD in the 3rd edition, it isn't explained anywhere in the book.)

If the keyboard is already acquired it will check the state of the keyboard and will disengage the key_lock if it was set and the key was released.

Key_Down_Once will set the respective key to its locked state and register the button press, it will not register that key press again until the key is released. This was needed since the original Key_Down function will keep registering a button press as long as the key is held down (as in triggering it as fast as the program allows) - it doesn't register key presses in the same way or at the same speed as holding down a key on the keyboard (where there is a delay before key presses are repeated). Useful when you have keys toggle certain things.