Ducktards
  • Home
  • Behind the Scenes
  • Daily Dev
  • Server stuff

Using the keyboard

18/7/2016

 
When you write a program, there's a fair chance you'll need the keyboard! This simple article will show how you can easily retrieve input from your keyboard! 
Picture


​


​Virtual keys
Picture

​Basically, these are all the keys that don't  type a character. Instead, they're used for commands and functions. 

GML
//The control key
vk_control

//Specifically the left control key
vk_lcontrol



​

​

​
​
Reading a key
Picture
 

GML
//If pressing right arrow

​if keyboard_check( vk_right )
    {
    //Move right 5 pixels

    x += 5;
    }







​
​

​

Other keys
Picture
Game maker uses unicode for the remaining keys. So to see if the A key is pressed, you'd need to check 65.
​





​

​However!
Picture
The developers have included a nifty little shortcut! It works on capital letters and numbers, but unfortunately not on symbols.

GML
//Remember to use a capital!
Key_A  =  ord( "A" );

Key_1   =  ord( "1" );





​


​



​Shorter code
Picture
If you wanted to, you could slot this function right into the check!

GML
//If pressing A

​if keyboard_check( ord( "A" ) )
    {
    //Move left 5 pixels

    x -= 5;
    }




​







Keybinds
Picture
This is also how you can offer rebindable controls. Just store the key in a variable, which can be changed at a later time!
​GML
​//Store the keybind to use

Key_Up = ord( "W" );

​if keyboard_check( Key_Up )
    {
    x -= 5;
    }




​

​





​

Other checks
Picture
There are a few other events you can check for when a key is pressed as well. These make life a bit easier!
​
​GML

//Pressed just now?
keyboard_check_pressed( Key );

//Being held?
keyboard_check( Key );

//Released just now?
keyboard_check_released( Key );

//Not currently pressed
!keyboard_check( Key );
​

Example of use:

If we were to use the "pressed" event for both keys, you'd have to press control and c at exactly the same time, so they both register simultaneously. If we used a general "hold" event for both, the event would constantly be triggering throughout the press. Neither are ideal, so this is the solution:

GML
if keyboard_check( vk_control )   and  keyboard_check_pressed(  ord( "V" )  )
     {
     //Single paste event  -->
     }









​


​Overriding input
Picture
You might also need to take control. Luckily, there's some good  functionality for that, to save time!
//Forces a key to be released
keyboard_key_release( Key );

//Clears the key without a release event
keyboard_clear( Key );

//Ignores above cancelations
keyboard_check_direct( Key );













​​The clipboard
Picture
Another way of retrieving text is from the clipboard! 

GML
//Get the text
​var
Text = clipboard_get_text();


//Empty the clipboard
clipboard_set_text( "" );













Enjoy this article?

    Only show:

    All
    Dev
    Documentation
    Networking
    Tutorial

  • Home
  • Behind the Scenes
  • Daily Dev
  • Server stuff