Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
GameMaker Cookbook
GameMaker Cookbook

GameMaker Cookbook: Over 50 hands-on recipes to help you build exhilarating games using the robust GameMaker system

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

GameMaker Cookbook

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:
    How to do it…

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.

How to do 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:
    How to do it...

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:
    How to do it...

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:
    How to do it...

    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:
    How to do it...
  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 to do it...

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.

Left arrow icon Right arrow icon

Key benefits

  • 1.Design and develop game elements that can be used alone or stacked to enhance your gaming experience
  • 2.Explore extensions that can unlock GameMaker: Studio’s true potential to create complex games
  • 3.A recipe-based, easy-to-follow guide to take your GameMaker skills to the next level

Description

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.

Who is this book for?

This book is intended for GameMaker: Studio enthusiasts who are looking to add more substance and improve their content. If know your way around the program and have some basic GML skills but want to take them further, then this book is for you.

What you will learn

  • Set up player control schemes of various types, such as touch controls and a gamepad
  • Create your own physics sandbox
  • Get accustomed to advanced player movement
  • Implement music and 3D sound in your games
  • Utilize GameMaker's GUI layers to create exciting games
  • Generate adjustable game settings and save systems
  • Add depth to your game with lighting and special effects
Estimated delivery fee Deliver to Slovenia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 23, 2015
Length: 212 pages
Edition : 1st
Language : English
ISBN-13 : 9781784399849
Vendor :
Yoyo Games
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Slovenia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Dec 23, 2015
Length: 212 pages
Edition : 1st
Language : English
ISBN-13 : 9781784399849
Vendor :
Yoyo Games
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 94.97
GameMaker Cookbook
€36.99
Gamemaker Essentials
€20.99
GameMaker Programming By Example
€36.99
Total 94.97 Stars icon

Table of Contents

11 Chapters
1. Game Plan – Creating Basic Gameplay Chevron down icon Chevron up icon
2. It's Under Control – Exploring Various Control Schemes Chevron down icon Chevron up icon
3. Let's Move It – Advanced Movement and Layout Chevron down icon Chevron up icon
4. Let's Get Physical – Using GameMaker's Physics System Chevron down icon Chevron up icon
5. Now Hear This! – Music and Sound Effects Chevron down icon Chevron up icon
6. It's All GUI! - Creating Graphical User Interface and Menus Chevron down icon Chevron up icon
7. Saving the Day – Saving Game Data Chevron down icon Chevron up icon
8. Light 'em up! – Enhancing Your Game with Lighting Techniques Chevron down icon Chevron up icon
9. Particle Man, Particle Man – Adding Polish to Your Game with Visual Effects and Particles Chevron down icon Chevron up icon
10. Hello, World – Creating New Dimensions of Play Through Networking Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Buyer 1982 Jan 14, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Nice size book easy to handle, application use and programmes are well explained and could be easily adapted if you have GameMaker 8 , 1.4 or the new 2 version.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela