Tutorial 3: Create a player object, movement & animation
- In the Asset Browser / Resource menu area, right-click Object and click Create object
- Name the object objPlayer – note: You should always prefix your objects with the letters obj
- Assign it the sprPlayer sprite you should already have created. To do this click on the 3 dots in the box beside No Sprite. See below
Add Player object to the room
- From the Assets Browser, double click room0 or whatever the default room setup is called in GameMaker.
- Make sure you are in the Instances layer of the room. This can be seen in the Room Editor’s Layers panel.
- Drag the objPlayer object into the room.
If you want to setup the game to work on most desktops and laptops, on the left side, under room settings change the width to 960 and the height to 640
Code the player object to move
- Open your player object again
- Click Add Event button in the Events box and add a Create event
- In the description comment change the description to Set up variables. Add the following code below the comment:
flySpeed = 5; //speed of the object imgSpeed = 5; //speed of the animation
- Add the following 4 events on the player object to represent arrow key presses and creates movement:
– Key Down Left – inside this event add this code:if(x - sprite_xoffset>0) x-=flySpeed;
– Key Down Right – inside this event add this code:
if(x+sprite_xoffset<room_width) x+=flySpeed;
– Key Down Up – inside this event add this code :
//this stops the ship from flying beyond half of the room height //you could set this to 1/3 the room height or whatever you want if(y>room_height/2) y-=flySpeed;
– Key Down Down – inside this event add this code
if(y+sprite_yoffset<room_height) y+= flySpeed;
Stop the player leaving the room
- Create a Step Step Event on the player object
- Add the following code:
//stops the ship leaving the room, assumes the sprites size if 64 x 64 x= clamp(x, 32,room_width-32); y=clamp(y,32,room_height-32);
Animate the player sprite on movement only
- In the Step event add the following code:
image_speed = 0; //stop the image animating on every step if keyboard_check(vk_up) //only check if the up key is pressed image_speed=imgSpeed; // if it is then set the animation to imgSpeed that you defined
Mapping the arrow keys to WASD keys
If you want to use WASD as your controls add the following code to your player objects Create event
keyboard_set_map(ord("W"), vk_up); keyboard_set_map(ord("A"), vk_left); keyboard_set_map(ord("S"), vk_down); keyboard_set_map(ord("D"), vk_right);
The above lines of code will map whatever code you have given the arrow keys to the WASD keys