Home Game Development GameMaker Cookbook

GameMaker Cookbook

By Brandon Gardiner , Julián Rojas Millán
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Game Plan – Creating Basic Gameplay
About this book
GameMaker: Studio started off as a tool capable of creating simple games using a drag-and-drop interface. Since then, it has grown to become a powerful instrument to make release-ready games for PC, Mac, mobile devices, and even current-gen consoles. GameMaker is designed to allow its users to develop games without having to learn any of the complex programming languages such as C++ or Java. It also allows redistribution across multiple platforms. This book teaches you to harness GameMaker: Studio’s full potential and take your game development to new heights. It begins by covering the basics and lays a solid foundation for advanced GameMaker concepts. Moving on, it covers topics such as controls, physics, and advanced movement, employing a strategic approach to the learning curve. The book concludes by providing insights into complex concepts such as the GUI, menus, save system, lighting, particles, and VFX. By the end of the book, you will be able to design games using GameMaker: Studio and implement the same techniques in other games you intend to design.
Publication date:
December 2015
Publisher
Packt
Pages
212
ISBN
9781784399849

 

Chapter 1. Game Plan – Creating Basic Gameplay

In this chapter, we'll cover the following:

  • Animating a sprite

  • Moving your player

  • Adding projectiles

  • Creating hazards

  • Programming basic enemies

  • Setting up player health and lives

  • Creating a scoring mechanism

  • Creating win/lose scenarios

 

Introduction


GameMaker is a great tool for people interested in various aspects of game development. It can be used to quickly create simple, playable games, or even churn out hits like Hotline Miami and Gunpoint. Want to take part in a game jam? GameMaker can save you hours of coding, and as many headaches. Have a game mechanic you want to visualize? GameMaker is great for prototyping; it can do that. Well, you will have to do the work. GameMaker will just make it faster and easier.

Let's take a look at just how quickly and easily we can make a game using GameMaker's drag-and-drop interface.

 

Animating a sprite


Animated sprites can be made by importing frames from a sprite sheet or by creating individual images in a 3rd party program. What happens, though, if you don't have access to these methods? GameMaker includes its own image editor that, while not as versatile as programs like Photoshop, has received some recent upgrades that can help you create some decent animations.

Getting ready

Let's make a player character sprite with a simple walk cycle. If you haven't already, now would be a good time to open GameMaker, start a new project, and create a sprite. Name the sprite spr_player_walk.

Tip

Using descriptive names like this allows you to categorize your assets, which makes finding the right asset much easier.

How to do it…

As mentioned before, you can use 3rd party art programs to create your own sprites and import them to GameMaker. If you're more interested in just making something that moves, I've included the files necessary to create an animated sprite; simply load them from sprite properties and you're almost good to go.

With that out of the way, let's look at using GameMaker's built-in Sprite Editor.

  1. With Sprite Properties open, click on Edit Sprite to open the Sprite Editor.

  2. Click the Create a New Sprite button near the top left; the icon looks like a blank document. The default size for a sprite is 32×32 (pixels) but let's change that to 64×64.

  3. Click on Animation and select Set Length from the menu. Set this animation to 12 frames. You should now have 12 blank images beginning with image 0 and ending with image 11. The numbering system here is important when it comes to coding, so keep that in mind.

  4. If you double-click on the first image the Image Editor will open; this is where you'll draw and edit your frames, thus animating the sprite. At first glance, the editor is reminiscent of simple bitmap editors that allow you to paint images using your mouse or tablet. If you open the Image menu, however, you'll find that you have access to more advanced options such as edge smoothing, alpha and opacity controls, and even shadows.

  5. If you open the View menu, you'll find you can toggle the visibility of a grid over the image. Each space in this grid represents one pixel in the image, making this tool perfect for creating pixel art in GameMaker. Using this and other tools available, here's the first frame I made for our character:

The Image Editor comes with another feature that is great for animating your sprites: Onion Skin. Onion Skin allows you to, while working on one frame of an animation, view the following and preceding frames. You can set how many frames you want visible, both backwards and forwards, and use the Onion Skin value to change the opacity of those frames to alter their visibility while working. This can help you paint each form and make the animation more fluid because you can see where you've been and where you're going. A useful addition to this is the Scratch Page. Simply hit the J key to be taken to and from a frame that doesn't actually exist in your animation, but allows you to cut and paste image elements. It's a big help when you want to move separate pieces of an image from one frame to another.

Note

The Scratch Page looks the same as the standard Image Editor window and holds whatever you paste in it.

There you have it; you've animated a sprite for use in a game. That's a great first step, but we're not finished. If you use this sprite on your character it will appear as though he's walking at all times. I don't know about you, but that's not what I want to see in a game. You could animate an idle sprite, which is ideal for a polished look, but we're going to speed this up by using a single-frame idle pose.

  1. Open up Sprite Properties for spr_player_walk and click Edit Sprite.

  2. Select whichever frame you feel looks best as an idle pose (I chose the first frame).

  3. Click Edit, then click Copy.

  4. Close Sprite Properties, create a new sprite, and call it spr_player_idle.

  5. Click Edit Sprite, press Ctrl + V on your keyboard to paste the copied frame, and close the editor and Sprite Properties window.

Done. You now have a second sprite for a single character.

How it works...

As we've just seen, it's possible to create fully animated characters without the use of a 3rd party program. While other programs give you many more options not found in GameMaker, such as layers, you still have access to the fundamentals you need to get the job done. The editor is great for pixel art and Onion Skin makes animating a lot smoother by showing you adjacent frames.

There's more...

Now, we've only made sprites for two states of our character's being: idle and walking right. There are many other sprites you may want to consider if you're looking to build a full game. Think about other games you've played; how many different movements and poses do they incorporate? Walking, running, jumping, rolling, punching, shooting, and so on, you get the idea. When designing a game, any actions you intend for your player character should be listed and planned out because you need to consider just how many sprites you'll need. Will they be animated? Will they look different depending on what direction the player is facing, or can they be mirrored? How long will it take for the animation to play out? These are all important questions, but they get easier to answer with each game you make.

See also

Sprites used for GUI will be discussed in Chapter 6, It's All GUI! – Creating Graphical User Interface and Menus, while sprite-based VFX are used in Chapter 9, Particle Man, Particle Man – Adding Polish to Your Game with Visual Effects and Particles.

 

Moving your player


There are many different types of games with different visuals and play styles. Some games are devoid of a visible player character but most, especially 2D games, have the player controlling a sprite or 3D model onscreen. We're going to take a quick look at putting a character in front of the player that he/she can control.

Getting ready

You've animated some sprites, but animated sprites won't do you any good without a character to which they can be applied. Create a new object and call it obj_player. Under Sprite, click the menu icon and select spr_player_idle.

How to do it...

  1. In obj_player's Object Properties window, click Add Event, then click Keyboard and select <Right> from the menu. This event will allow you to make things happen while you're pressing the right arrow key on your keyboard. What we want to have happen is for our player character to move to the right and to have his right facing walk cycle play while he is doing it, so let's do it.

  2. Under the Main1 tab on the right side of the Object Properties window, drag Change Sprite (it looks like a green Pac-Man) and drop it in the Actions box.

  3. The actions we want apply to obj_player, so select Applies to Self.

  4. Since we want to use spr_player_walk in this case, select the sprite from the drop-down menu.

  5. Subimage defaults to 0, but this tells GameMaker that we only want to show the first frame of the animation. Since we want to have the entire animation play, you'll need to set this value to -1, which tells GameMaker to ignore the subimage count.

  6. The sprite's play speed can be altered by setting the Speed option to a value between 0 and 1. Set the value to 0.8 so that the walk cycle will play at 80 percent of the room's frame rate and close this box.

    We want the player character to move right when the right arrow key is pressed but we don't want him to simply walk right off the screen. How mad would you be if the character you were controlling simply gave up, said That's it, I'm out of here! and disappeared off screen? Sounds like an entirely frustrating experience. Since we don't want this to happen, let's make sure it can't. For that, you'll need to add a variable check before your character goes anywhere.

  7. Under the Control tab, drag and drop Test Variable to the Actions box.

  8. We want to test the variable x, which is the player's x coordinate or horizontal position. Since we want to the player to stay on-screen, we'll set the value to room_width-16 and the operation will be less than.

  9. Close the Test Variable box and under the Move tab, drag and drop Jump to Position to the Actions box.

  10. Set x to 4, leave y as 0, and make sure Relative is checked. If you were to test this out now, your player will begin moving to the right as his walk cycle animation played. The problem is that now it doesn't stop.

  11. Add another event but this time choose Key Release <Right>. Add Change Sprite to the Actions box but this time select spr_player_idle from the menu. This time, if you were to run a test, your player would walk right when holding the right arrow key and go back to his idle pose when it is released.

    These same steps can be repeated for all directions using corresponding keyboard events but you need to take into consideration whether or not you need to mirror the sprites. If you've created separate sprites for each direction you'll simply choose which sprite you'll need at the time. If, however, you've opted to mirror the sprites, you'll need to add one more thing to each key event.

  12. Under the Main1 tab, drag and drop Transform Sprite into the Actions box for each key event (key release events included) and modify the xscale (for horizontal mirroring) or the yscale (for vertical flipping). Setting the value to -1 would flip the image and setting it to 1 would revert it to its original facing. If the image is already facing that way, no change is made. Avoid using the options in the Mirror menu, as these selections alter the image from its present state instead of assigning a value. This would mean that if you hit the left arrow key, and the character was already facing left, he would flip and face right. That would be confusing!

Tip

This and any other drag and drop function in GameMaker can also be used in code and scripts. In fact, coding them yourself often allows for greater control over how they work.

How it works...

The movement discussed in this section is quite simple. In this case, you've instructed GameMaker to make your character move left or right and play the walk animation (facing the proper direction) as he goes. Using jump to position allows you to move a character to any point in the screen or, as you did here, move the character relative to its current position, adding the entered values to existing coordinates. Using a negative value would subtract from the current coordinates, causing the character to move in the opposite direction. If you want your character to move up or down you would change the value of y and leave x as 0. I encourage you to play around with the values entered, as this will change the player's speed.

There's more...

It might seem like this section had a lot of text to set up very simple movement, but I can assure you it is all necessary. This section and the rest of the chapter set up some core ideas that will recur throughout your GameMaker experience and will be explored much further later on.

See also

Several methods of advanced player movement and controls will be demonstrated in Chapter 2, It's Under Control – Exploring Various Control Schemes, and Chapter 3, Let's Move It – Advanced Movement and Layout.

 

Adding projectiles


Now that our character can move, logically (or rather, illogically), we want to give him a gun. Though countless games offer projectiles as part of the gameplay, there are a great number of design choices to consider that will ultimately alter the way the player plays. We're going to create simple projectiles right now but later in the book we'll discuss different design choices for creating and controlling gameplay.

Getting ready

  1. Create a sprite, call it spr_projectile, and load the images you would like to use; you can use a single, static image, but it looks much better if your projectile has a brief animation. (I've provided a projectile animation in the downloaded project files. The sprite is 16px by 16px.)

  2. Now create an object for the projectile (obj_projectile) and assign the sprite you made.

We want to create a projectile at our character's location whenever the player hits the Spacebar. On creation of the projectile, we want GameMaker to verify the direction the player is facing and send it flying in that direction. Before GameMaker can check the direction, though, we need to create a variable that tells GameMaker which direction the object is actually facing. It sounds convoluted but in execution it's really fairly simple, so let's begin.

How to do it...

  1. Open the Object Properties for obj_player and add a Create event.

  2. Under the Control tab, drag and drop Set Variable to the Actions box.

  3. Name the variable dir and set the value to 1.

  4. In the Keyboard event for right, drag and drop Set Variable from the Control tab and have it set dir to 1.

  5. Do the same for the left keyboard event but have it set dir to -1.

  6. Now create a Key Press event and select <Space>.

  7. Under the Main1 tab, drag and drop Create instance to the Actions box.

  8. Select obj_projectile from the menu but leave the x and y values as 0.

  9. Open the Object Properties for obj_projectile and add a Create event.

  10. Under the Control tab, drag and drop Test Variable to the Actions box.

  11. Under Applies to select obj_player and have it test whether or not the variable dir is equal to a value of 1.

  12. Now, under the Move tab, drag and drop Move Fixed to the Actions box and have our projectile move to the right at a speed of 8.

  13. In the same Create event, repeat these steps but check dir for a value of -1 and have the projectile move to the left. The obj_projectile properties window should look like this:

There's one last thing we should look at, here, and that's how often our player character can shoot. As it is right now he can shoot every time the Spacebar is pressed. Imagine our character is holding a handgun. Now think about how quickly the player could potentially press the Spacebar, over and over. I don't know about you but I imagine a handgun that can shoot that fast must be magical; maybe a wizard made it. There is a way around this magical handgun made by wizards, and that way involves alarms and variables.

  1. Open up the properties for obj_player once more and, in the Create event, drag and drop another Set Variable to the Actions box.

  2. Call the variable shoot and set the value to 1.

  3. In the Key Press event for Space, drag Set Variable to the Actions box and set shoot to 0.

  4. Under the Main2 tab, drag Set Alarm to the Actions box and set Alarm 0 to 30.

  5. Now click on Add Event, select Alarm 0, and drag Set Variable to the Actions box and have it set shoot back to 1.

  6. There's just one final change to make, now. Go back to the Space key press event and drag Test Variable to the Actions box and have it test if shoot is equal to 1.

  7. Make sure this is the first thing GameMaker does when Spacebar is pressed by dragging it to the top of the list.

  8. Now, the rest of the actions here should only be carried out if shoot is equal to 1. To make sure this is the case, drag Start Block from the Control tab and drop it above Create Instance, and drag End Block to the bottom of the list. The Spacebar key press event should now look like this:

Congratulations! You now have a player that can shoot projectiles in the direction he is facing and do so at a realistic rate. This outcome is much more appealing than having a player who fires his gun wherever he pleases at incredible rates. You're a loose cannon, player!

How it works...

In order to make your character shoot projectiles, we've had to use several important elements of programming with GameMaker, namely variables and alarms. When the Spacebar is hit, GameMaker first has to check whether or not the variable shoot is equal to 1. If not, nothing happens. You could hit the spacebar as many times as you want, but unless shoot equals 1, you'll get nothing out of it. Now, assuming shoot does equal 1, GameMaker moves on to create a projectile in the same place as the player, which is (0, 0) relative to wherever the player object is sitting. If you want the projectile to be created near the player, say to give the appearance that the projectile is coming out of a gun, you could change the coordinate values for (x, y).

At the same time, GameMaker is setting shoot to 0 to prevent the player from shooting again right away, and setting an alarm to 30 steps. At the end of those 30 steps, shoot is set back to 1. Each step is the same as one frame in-game, meaning if the game is running at 60 frames per second, the player can fire every half-second.

Once the projectile is created, GameMaker is testing another variable we set: dir. This is simply to tell GameMaker in which direction the player is facing and GameMaker then sends the projectile off in that direction. Bam. Projectiles. No pun intended.

See also

Projectiles will be expanded on in Chapter 9, Particle Man, Particle Man – Adding Polish to Your Game with Visual Effects and Particles.

 

Creating hazards


So our player can move and shoot. That's great, but what fun is that when there are no obstacles? Hazards offer a great challenge and can even be the core of your gameplay. How boring would Mario Kart be without banana peels? Or Pitfall without…well, the pits? Video game hazards come in many forms and, if you play games, you've likely encountered most, if not all of them. Spikes, lasers, electrical traps, and falling objects are a few examples, but they have at least one thing in common: if your player character touches them, he/she will be hurt or killed. Now, in most games the latter isn't permanent, what with health bars and lives (we'll get into those later), but it remains a major part of the gameplay. Let's look at creating some simple hazards that can give your players a hard time.

Getting ready

In-game hazards can come in many forms and various visual styles. Like the projectiles we discussed previously they can be static images, but they look much better as animated sprites. We're going to build a spike trap; you can use your own art, but I've included an animated sprite in the downloadable files.

  1. Create a sprite, name it spr_hazard_spike, and load the necessary images. Before we move, on you're going to need to set up the sprite's collision mask. Sprites are assigned a collision mask by default but you can modify it to your own needs. We only want the trap to be activated and for the player to take damage when the spikes are actually touched, as opposed to the area around the trap.

  2. Under Collision Checking make sure Precise collision checking is selected.

  3. Click Modify Mask and, under Shape, select Precise. To the left of that is a slider that allows you to specify Alpha Tolerance. This is useful because it allows you to shrink and grow the mask according to the sprite's outline (the empty space around it being an alpha map).

Once you save your selections we're ready to get started.

How to do it...

  1. Begin by creating a new object called obj_hazard_spike and assigning the sprite you made previously.

  2. Add a Create event and drag and drop two instances of Set Variable. One will set image_speed to 0, the other will set trap_set to 1.

  3. Add a Collision event with obj_player as the target.

  4. Drag and drop Test Variable to the Actions box, checking that trap_set is equal to 1.

  5. Place both a Start and End Block in the Actions box. Within this block you'll need two Set Variables; one that sets trap_set to 0, and another that sets image_speed to 1.

  6. Still within the block, set Alarm 0 to 60. Your Actions box should now look like this:

    Tip

    Downloading the example code

    You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

  7. Create the event for Alarm 0.

  8. In the Actions box, drag and drop Set Variable, setting image_speed to 1.

  9. Drag and drop Set Alarm, setting Alarm 1 to 30.

  10. Add the event for Alarm 1, where you'll drag Set Variable and have it set trap_set to 1.

  11. Add a Step Event and drag Test Variable to the Actions box and have it test whether or not image_index is equal to 4.

  12. This should be followed by a Start and End Block. Within this block should be a Test Variable that checks whether or not alarm[0] is greater than 0, as well as another Start and End Block.

  13. Within this block you'll need a Set Variable that sets image_speed to 0. When you're done, the Actions box should look like this:

  14. Finally, click Add Event, then Other, and select Animation End.

  15. All you need in the Actions box here is a Set Variable that sets image_speed to 0.

Got all that? It's a lot to do all at once, but we'll go through what it does, step by step. The good news is that you now have a spike trap that springs when touched by the player and stays sprung for a bit before retracting. There's a good reason behind this that we'll explore a little further once we get into player health.

How it works...

The trap you've just made uses collision detection and alarms to set and reset variables that control the trap's state. On creation, GameMaker sets the image_speed to 0, keeping the animation on the 1st frame, and establishes the variable trap_set, which will only be used by this particular instance of the spike trap. Think of trap_set as a sort of on/off switch, using binary (0 or 1) to dictate its current state. When the player collides with the trap, GameMaker checks whether or not the trap is on. If trap_set is equal to 1 (on), GameMaker proceeds to set image_speed to 1 (so the animation will begin to play), set Alarm 0 to 60 steps, and reset trap_set to 0 so that the spike trap will not be activated over and over again. This is to give the player a chance to move away from the trap to avoid being injured a second time. The Step Event checks every single step to see whether or not the sprite's animation has advanced to frame number 4. If it has, it then checks whether or not Alarm 0 is still counting down. If it is, image_speed is set to 0, so that the animation remains on the 4th frame (in the up position) until Alarm 0 is finished counting down. When it has, the image_speed is set back to 1, allowing the animation to continue, and Alarm 1 is set to 30 steps. The animation can continue (retracting the spikes) but once it reaches the last frame, the Animation End event then sets image_speed to 0 again, preventing the animation from looping. The last thing to happen in this long list of events is the end of Alarm 1, which simply gives trap_set a value of 1, thereby resetting the trap to be used again.

It's a lot to take in at once, but creating this trap is a great demonstration of the programming logic we're going to get into later on. For now, enjoy your new spike trap!

 

Programming basic enemies


Enemies are more or less an extension of hazards; the basic idea is that if they touch (or shoot a projectile that touches) the player, the player is injured or killed. Only in games, though, not in real life. There is one difference here: enemies move. You can create enemies that will march to their deaths (think Goombas in the Mario Bros games), patrol a given area (think soldiers in the Metal Gear games), or even actively hunt the player (think ghosts in Pac-Man). For now, we're going to take a look at a simple enemy that will patrol a straight line.

Getting ready

As with everything we've done so far in this chapter, you'll need sprites to represent your enemy. You can make your own or you can use the one included in the downloaded files. It's acceptable to use the same sprite for different types of enemies but, from a game design perspective, it's a good idea to differentiate. This will make it easier for your player to identify the enemy types and react accordingly.

Create a sprite and name it spr_enemy_patrol. Load the associated images from the files provided, or create your own, and be sure to set up the collision mask.

How to do it...

  1. Create an object called obj_enemy_patrol and assign the sprite you just made.

  2. Add a Create event and drag and drop Set Variable that sets image_speed to 0.6.

  3. Drag and drop Set Variable, which will set dir as -1, and Transform Sprite, which will change the xscale to -1. Now, that's the simple part. The rest of the actions for (for the moment) will be handled by a Step event.

  4. Add a Step event. This is where you'll need to run several tests in order to dictate your enemy's movement.

  5. Drag and drop Test Variable and have it check whether or not dir is equal to -1.

  6. Beneath this, drag a Start and End Block, within which you'll add a Test Variable that checks whether or not x is greater than 16.

  7. Below this, you'll need a Start and End Block, between which you should place Moved Fixed, and set it to move left at a speed of 1.

  8. Under all of the preceding boxes, drag and drop another Start and End Block.

  9. Within this block, place a Test Variable that checks whether x is less than or equal to 16, followed by another Start and End Block.

  10. Within this block you will need a Set Variable that sets dir to 1, a Transform Sprite that changes xscale to 1, and a Move Fixed that sets the move direction to the right at a speed of 1.

You now have exactly half of the actions required for a patrolling enemy. At this point you can do one of two things: You could copy this entire set of actions, paste the copies directly below the existing actions, and go about changing the variables to their exact opposites, or you could drag and drop new blocks in the same order, but set the variables to their opposites. The former is much faster, but the latter will help you learn more about programming logic. In any respect, your Actions box should look like this:

How it works...

While this Step event contains a lot of actions, it is really doing something quite simple. GameMaker is checking, every game step, for the patrolling enemy's state and position. If headed left and his position on the room's x coordinate is more than 16, he'll continue on in that direction. Once he gets past this point, GameMaker switches his direction, flips the sprite and sends him off to the other side of the room until his x coordinate reaches the room width minus 16 pixels, rinse and repeat.

There's more...

This method of creating a patrolling enemy is a simple enough way to move your enemy in a set space. I chose to have him walk right across the entire room, but you could also have him walk within a smaller space. Another way to accomplish this is to create left and right boxes, remove their visibility by unchecking the Visible box in Object Properties, and placing them at either end of the area you want patrolled. In the enemy's properties, instead of having everything in the Step event, you can control when they change direction by when they collide with the invisible boxes. The same actions would apply; they would just be executed in a different way. This just goes to show you that there are many possible solutions to all of the problems you may encounter when making games; you just have to find them.

See also

Paths will be discussed in Chapter 4, Let's Get Physical – Using GameMaker's Physics System.

 

Setting up player health and lives


Any action game involving a player controlled character is likely to have some sort of "health" and "life" system. These are terms long used in video games that are used in conjunction with how your character is abstractly "alive" within the game itself. In reality, health and life in games are simply numbers whereby you lose a chance to play or even the game itself when they reach zero. GameMaker makes keeping track of these numbers quite easy when it comes to the drag and drop actions, so we're going to look at how we can add these elements to our player character.

Getting ready

Since this recipe involves making additions to your existing player character, you don't need to do much. You'll need a sprite to indicate your player's lives (call it spr_life) but other than that all you need to do now is open the obj_player Object Properties window.

How to do it...

  1. In the Create event, from the Score tab, drag and drop the Set Health action into the Actions box and set Health to 100.

  2. From the same tab, drag and drop Set Lives and set it to 3.

  3. Add a Set Variable to the Actions box and set hit to 0.

  4. Click Add Event, then Collision, and select obj_enemy_patrol from the menu.

  5. Add Test Variable to the Actions box and have it check for whether hit equals 0.

  6. Below, drag and drop Start and End Block, and within that block add Set Health with a relative value of -20.

  7. Add Set Variable, setting hit to 1.

  8. Add Set Alarm 1 and set it to 60 steps. Repeat these actions using obj_hazard_spike in place of your enemy.

  9. Add an event for Alarm 1 and drag Set Variable to the Actions box, setting hit to 0.

  10. Add the event Draw GUI and, from the score tab, drag Draw Health to the Actions box.

  11. Make sure Relative is checked and, under the appropriate headings, enter the following values:

    x1: -16
    y1: -24
    x2: 16
    y2: -34
    back color: black
    bar color: green to red
  12. Drag and drop Draw Life Images to the Actions box and enter the following values:

    x: room_width-64
    y: 64
    image: spr_life
  13. Create a Step event and add a Test Variable that checks if health is equal to 0.

  14. Below that, drag a Start and End Block and within that block add Set Variable lives to -1 relative, and Set Variable health to 100.

How it works...

Health and lives are very straightforward, with GameMaker doing a lot of the work for you when using the drag and drop actions. Essentially, GameMaker has created the variable health and you've set it to a value of 100. You've also created the variable hit, which you use to control when you can be injured. If hit is set to 0 (off) then you can be hit by an enemy or hazard. If you are hit by one of them you lose 20 health points and the variable hit is set to 1. This is to prevent contact with an enemy continuously draining your health, as it is being checked every step. An alarm is set to 60 steps and at the end of that countdown hit is set back to 0, meaning you can be injured once more.

The Step event is also constantly checking for when your health reaches 0. When it does, the lives variable is decreased by 1 and your health is reset to 100.

There's more...

In this case we set the health bar to a specific coordinate relative to the player's position. This was purely a design choice to show you that you have options. You can set the health bar to a static position on the screen, much like we did for the lives indicator. As for the lives indicator, using the Draw Lives action instead of Draw Life Images allows you to indicate the player's remaining lives with text and numbers.

 

Creating scoring mechanism


In the days of arcades, a high score was king. It wasn't enough to beat a game; you had to get in the top 10 highest scores in order to claim local fame. Once your score was high enough to knock someone out of the top ten, the victory could be finalized by putting your initials next to it. Or a dirty word. Not that I've ever done that….

Regardless, a lot of games today don't rely on a scoring system, but focus on the story, experience, or multiplayer rankings. Let's bring back a little piece of gaming history by creating a simple scoring mechanism.

Getting ready

This recipe does not involve any new sprites or other assets but does require a new object. Call the object obj_score and leave the sprite box blank.

How to do it...

  1. In the Object Properties for obj_score, add a Create event.

  2. Drag Set Score from the Score tab to the Actions box, and have it set the score to 0.

  3. Create a Draw GUI event and drag Draw Score to the Actions tab with the following values:

    x: 32
    y: 32
    caption: Score:
  4. Close the obj_score Object Properties window and open obj_enemy_patrol.

  5. Add a Collision event with obj_projectile and, from the Main1 tab, drag and drop Destroy Instance to the Actions box (Applies to: self).

  6. Drag Set Score to the Actions box and change the new score to 10 relative.

  7. Close the Object Properties window and open obj_projectile.

  8. Add a Collision event with obj_enemy_patrol and drag and drop Destroy instance at Position like you did previously.

How it works...

GameMaker is again doing a lot of the heavy lifting, here. You created obj_score to keep track of scoring. Not assigning a sprite to it will allow the object to be in a room, affecting the game, without being seen. The rest of the recipe is simply placing the score counter as a GUI element, checking for collisions between projectile and enemy, and adding points and destroying the two when they collide.

There's more...

In this recipe, obj_score acted as what's referred to as a controller object. These objects are often invisible and control specific aspects of the game. Since an object needs to be active in order for its actions and variables to be used, any aspect of the game that needs to be present without interruption should be assigned to a controller. I use controllers for music, HUD, global variables, and more.

See also

Most chapters going forward will deal with controllers and their various functions.

 

Creating win/lose scenarios


The term "game" has many different definitions, to the point where experts can't always agree what makes a game. Most definitions, though, determine that games are only such if they involve both win and lose scenarios. I mean, who wants to play a game you can't win or lose?

Getting ready

This recipe, again, does not necessitate new sprites or even objects. We'll be relying on existing objects but we'll be adding some new variables. Start by opening the Object Properties for obj_player.

How to do it...

  1. In the Step event you should already have the actions that check the value of health. Beneath all of that, drag and drop Test Variable and have it check whether lives equals 0.

  2. Below that, from the Main2 tab, drag Restart Game to the Actions tab.

  3. Close obj_player and open obj_score.

  4. Create a Step event and drag Test Variable to the Actions box and have it check whether score is equal to 100.

  5. Below that, drag Restart Game from the Main2 tab.

How it works...

As you may have guessed by the names of the actions, you are simply asking GameMaker to check the values of score and lives, and restarting the game when they reach a certain point. In previous recipes you set the score to increase by 10 whenever you shot an enemy. If you shoot 10 enemies, the game will restart. You set the lives variable to 3 but had it decrease by 1 every time your health reached 0. Once you have no lives left, the game restarts.

There's more...

Using Game Restart in this scenario is arbitrary; it is simply there to demonstrate that you can tell GameMaker to change the game's state based on your score, health, or number of lives. Under the Main1 tab in Object Properties you can find actions that take you to other rooms you may have created. This can be used to go from one level to another.

See also

The Chapter 6, It's All GUI! – Creating Graphical User Interface and Menus, deals with more advanced GUI and Chapter 7, Saving the Day – Saving Game Data, covers save systems and leaderboards.

About the Authors
  • Brandon Gardiner

    Brandon Gardiner is a game developer and designer living out his love of video games. Though he started his foray into games through 3D art and level design, he always kept a notebook of ideas for games and game mechanics he wished to see. When he discovered GameMaker: Studio, he found that he could bring these ideas to life. He is a graduate of the first iteration of the game development program at Toronto's George Brown College. In college, he worked as an artist and designer on several game projects for outside companies, including tie-ins for children's television shows and educational titles. After graduating, he founded MechaBee Studios where, being the sole developer of mobile and PC games, he is a jack of all trades. He also writes a blog at http://www.gamemakerhq.com, through which he hopes to build a resource for other independent developers. He lives with his wife in Toronto where he is a veteran of the annual Toronto Game Jam (tojam.ca), an active member of the International Game Developers Association.

    Browse publications by this author
  • Julián Rojas Millán
Latest Reviews (3 reviews total)
I love books for GameMaker:Studio and this one contains some stuff where my knowledge is still lacking. Or it teaches me different approaches that might be better or more elegant than mine.
I really like the format and the concise information present. The style is easy to read and enjoyable.
Excelente altamente recomendables.
GameMaker Cookbook
Unlock this book and the full library FREE for 7 days
Start now