Code Keyboard Controls in GameMaker: Studio - dummies

Code Keyboard Controls in GameMaker: Studio

By Michael Rohde

You add code to Objects in GameMaker: Studio through an Execute Code Action from the Control tab. There is an infinite number of ways to use code in games. Here is sample code for keyboard controls for moving an Object left or right.

You can use the drag-and-drop Actions to create keyboard controls, but you can also write your own code for keyboard controls. The following procedures show you how to write code to make an Object move left and right.

  1. Create a Sprite that will represent what the player controls, such as the bat Sprite from the breakout tutorial.

    The Sprite should appear in the Resource tree.

  2. Choose Resources→Create Object.

    The Object Properties window appears.

  3. In the Name field, type something like obj_bat.

  4. From the Sprite drop-down list, select the Sprite, such as spr_bat.

    A thumbnail of the image appears in the Sprite section, and the name of the image appears in the field.

  5. Choose Add Event→Keyboard→Left.

    A Left Keyboard Event appears in the Events section of the Object Properties.

  6. Drag and drop the Execute Code Action from the Control tab into the Actions section.

    An empty code window appears.

  7. In the code window, type the following code:

    if place_meeting(x - 5, y, obj_wall) = false
    {
    x -=5;
    }

    The code first checks for a collision between the Object (an Instance of the Object during gameplay) and obj_wall (if there are fewer than 5 pixels separating the Object from the wall).

    If there is less than 5 pixels of space between the Object and the wall, GameMaker sets the X position of the Object to move 5 pixels over. In that way, the player can’t move the Object into the wall.

  8. Click the green check mark.

    The code window is saved and closed.

  9. Choose Add Event→Keyboard→Right.

    The Right Keyboard Event appears in the Events section.

  10. From the Control tab, drag and drop an Execute Code Action into the Actions section.

    An empty code window appears.

  11. In the code window, type the following code:

    if place_meeting(x + 5, y, obj_wall) = false
    {
    x +=5;
    }

    The code for the Right arrow key is the same as for the Left arrow key, except you’re checking for the right boundary (in this case, obj_wall). A good thing to remember is that +x is to the right and –x is to the left. In the same way, +y is down and –y is up.

  12. Click the green check mark.

    The code window is saved and closed.

You could test this code now by placing an Instance of the bat Object in the Room. Of course, you would need the wall Object created as well. To find out how to the create the wall Object, you can follow along with GameMaker’s coding tutorial.