Page 1 of 1

key press and key release within script editor

PostPosted: Fri Sep 20, 2013 1:48 pm
by master0500
would it be possible for someone to create a brief tutorial with explanations about doing key press and key release events withing the script editor? thank you for your time :D

Re: key press and key release within script editor

PostPosted: Fri Sep 20, 2013 8:08 pm
by skydereign
I wrote a function that should make it easier to do (from the this topic http://game-editor.com/forum/viewtopic.php?f=4&t=12006&p=85407&).
Code: Select all
char*
GetKeys ()
{
  const int key_reg[] = {KEY_RIGHT, KEY_LEFT, -1}; // must end with -1
  // list of keys that can have keyup states
  // that way it doesn't need to loop through every key
  // because rarely do people want to catch gp2x keys

  // static variables are only initialized once
  static int protect = 0; // used to lock the function (only once per frame)
  static char key_prev[500] = {0}; // or however long GetKeyState is
  static char* key; // function remembers last key state
 
  if(frame%2==protect) // only update once per frame
    {
      int i;
      key=GetKeyState();
     
      for(i=0; key_reg[i]!=-1; i++) // loop through registered keys
        {
          if(key_prev[key_reg[i]]==1 && key[key_reg[i]]==0)
            { // if the key was pressed, but isn't anymore
              key_prev[key_reg[i]]=key[key_reg[i]]; // set key previous
              key[key_reg[i]]=-1; // set to keyup
            }
          else
            {
              key_prev[key_reg[i]]=key[key_reg[i]]; // set key previous
            }
        }

      protect=protect==0; // lock until next frame
    }
 
  return key;
}

Add that function into global code, and add all the keys you need to track into that first array. Then you can use GetKeys like you would GetKeyState. GetKeys though needs to be called every frame if it is to be accurate all the time, so I recommend putting it in the view's draw actor.