[Game Maker] Grid Movement -PART 1- The Basics

If you find this tutorial helpful, please consider showing support by trying my latest game
Insane Number Run
Insane Number Run***

Accompanying video tutorial. Please watch at fullscreen with quality set to 480p or higher.

Note:
You can preview an implementation of grid based movement here
When you are finished, be sure to check out further lessons in this series for grid movement:
Part 2: Collision Detection
Part 3: Character Animation

And now to the lesson!

1) Start a new project

2) Add a new object and call it obj_player

3) Inside obj_player, Add Event -> Create create and add a piece of code code containing:

/*
   Initialize required variables
*/
gridSize = 32;     // Should be power of 2 (...8,16,32...)
isMoving = false;  // Keeps track of when player is moving
moveTimer = 0;  // Counts down from grid size each step
moveSpeed = 4;     // Do not set higher than grid size!
speedX = 0;
speedY = 0;

 

4) Inside obj_player, Add Event -> Step step and add a piece of code code containing:

/*
   When not moving, check to see if a direction key is held.
   If so, assign x/y speed and change status to moving.
*/
if (isMoving == false)
{
    if (keyboard_check(vk_right))
    {
        isMoving = true;
        moveTimer = gridSize;
        speedX = moveSpeed;
        speedY = 0;
    }

    if (keyboard_check(vk_up))
    {
        isMoving = true;
        moveTimer = gridSize;
        speedX = 0;
        speedY = -moveSpeed;
    }

    if (keyboard_check(vk_left))
    {
        isMoving = true;
        moveTimer = gridSize;
        speedX = -moveSpeed;
        speedY = 0;
    }

    if (keyboard_check(vk_down))
    {
        isMoving = true;
        moveTimer = gridSize;
        speedX = 0;
        speedY = moveSpeed;
    }
}

/*
   When moving, subtract from moveTimer our moveSpeed value
   and update location relevant to set speeds.
   Stop moving when moveTimer reaches zero.
*/
if (isMoving == true)
{
   x += speedX;
   y += speedY
   
   moveTimer -= moveSpeed;
   if (moveTimer == 0) isMoving = false;
}

 

5) Add obj_player to a room, preferably aligned to the grid size which you set in obj_player

There! You should now have a simple implementation of grid based movement. You can play around with changing gridSize to other values, such as 8 or 16 for tighter grid movement.

You can download the example gmk for this tutorial HERE

Incorporating what I discussed in my previous tutorial, you can also download a version which betters the 4 direction input HERE

Feel free to contact me about any questions or comments!

null

2 thoughts on “[Game Maker] Grid Movement -PART 1- The Basics

  1. Pingback: [Game Maker] Grid Movement -PART 2- Collision Detection « 8-Bit Warrior

  2. Pingback: [Game Maker] Grid Movement -PART 3- Character Animation « 8-Bit Warrior

Leave a Reply