GameMaker Cookbook - Brandon Gardiner - E-Book

GameMaker Cookbook E-Book

Brandon Gardiner

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 296

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

GameMaker Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Game Plan – Creating Basic Gameplay
Introduction
Animating a sprite
Getting ready
How to do it…
How it works...
There's more...
See also
Moving your player
Getting ready
How to do it...
How it works...
There's more...
See also
Adding projectiles
Getting ready
How to do it...
How it works...
See also
Creating hazards
Getting ready
How to do it...
How it works...
Programming basic enemies
Getting ready
How to do it...
How it works...
There's more...
See also
Setting up player health and lives
Getting ready
How to do it...
How it works...
There's more...
Creating scoring mechanism
Getting ready
How to do it...
How it works...
There's more...
See also
Creating win/lose scenarios
Getting ready
How to do it...
How it works...
There's more...
See also
2. It's Under Control – Exploring Various Control Schemes
Introduction
Keyboard controls
Mouse controls
Gamepad controls
Touch controls
Tilt controls
Creating 2D movement
Getting ready
How to do it...
How it works...
There's more...
See also
Adding a Run button
Getting ready
How to do it...
How it works...
Making your character jump
Getting ready
How to do it...
How it works...
There's more...
See also
Using a point-and-click interface
Getting ready
How to do it...
How it works...
There's more...
See also
Following the cursor
Getting ready
How to do it...
How it works...
There's more...
See also
Setting up a controller
Getting ready
How to do it...
How it works...
Utilizing analogue joystick acceleration
Getting ready
How to do it...
How it works...
There's more...
See also
Adding tap control
Getting ready
How to do it...
How it works...
There's more...
Using swipes
Getting ready
How to do it…
How it works…
There's more…
Moving characters or objects by tilting a device
Getting ready
How to do it...
How it works...
There's more...
3. Let's Move It – Advanced Movement and Layout
Introduction
Drag and drop items/characters
Grid-based movements
Paths
Multiple inputs
Dragging onscreen objects
Getting ready
How to do it
How it works
Dragging objects on a grid
Getting ready
How to do it
How it works
Moving a character on a grid
Getting ready
How to do it
How it works
There's more…
Setting a path
Getting ready
How to do it
How it works
There's more
Creating enemy pathfinding
Getting ready
How to do it
How it works
There's more…
See also
Controlling a character with a mouse and keyboard
Getting ready
How to do it
How it works
There's more
See also
4. Let's Get Physical – Using GameMaker's Physics System
Introduction
Physics engine 101
Gravity and force
Physics in the environment
Advanced physics-based objects
Creating objects that use physics
Getting ready
How to do it
How it works
Alternating gravity
Getting ready
How to do it
How it works
There's more
Applying force via magnets
Getting ready
How to do it
How it works
Creating a moving platform
Getting ready
How to do it
How it works
Making a rope
Getting ready
How to do it
How it works
There's more
5. Now Hear This! – Music and Sound Effects
Introduction
Audio basics
Sound effects
3D audio
Importing and playing background music
Getting ready
How to do it
How it works
There's more
Implementing situational sound effects
Getting ready
How to do it
How it works
There's more
Adding sound emitters and listeners
Getting ready
How to do it
How it works
There's more
Adjusting the listener orientation
Getting ready
How to do it
How it works
Replicating the Doppler effect with emitters
Getting ready
How to do it
How it works
6. It's All GUI! - Creating Graphical User Interface and Menus
Introduction
GUI basics
Game screens and menus
Setting up a basic HUD with code
Getting ready
How to do it
How it works
Making your HUD scalable
Getting ready
How to do it
How it works
Using the GUI layer in full screen mode with views
Getting ready
How to do it
How it works
There's more
Adding a title screen
Getting ready
How to do it
How it works
Creating splash pages
Getting ready
How to do it
How it works
There's more
Adding a game over screen
Getting ready
How to do it
How it works
7. Saving the Day – Saving Game Data
Introduction
Background data
Save systems
Creating game settings
Getting ready
How to do it
How it works
There's more
Making a pause screen
Getting ready
How to do it
How it works
There's more
Saving player selection and score
Getting ready
How to do it
How it works
There's more
Encrypting and decrypting save data
Getting ready
How to do it
How it works
8. Light 'em up! – Enhancing Your Game with Lighting Techniques
Introduction
Basic lighting
Light transitions
Light effects
Creating a room with a light switch
Getting ready
How to do it
How it works
There's more
Lighting objects with a spot light
Getting ready
How to do it
How it works
There's more
Changing day to night
Getting ready
How to do it
How it works
There's more
Creating a flashlight
Getting ready
How to do it
How it works
Making a flickering torch
Getting ready
How to do it
How it works
9. Particle Man, Particle Man – Adding Polish to Your Game with Visual Effects and Particles
Introduction
Particles
Game feedback
Using particles to simulate kicking up dust
Getting ready
How to do it...
How it works...
There's more...
Simulating rainfall
Getting ready
How to do it...
How it works...
There's more...
Creating an explosion
Getting ready
How to do it...
How it works...
There's more...
Adding screen-shake
Getting ready
How to do it...
How it works...
Using slow motion
Getting ready
How to do it...
How it works...
There's more...
10. Hello, World – Creating New Dimensions of Play Through Networking
Introduction
Basic networking
Online play
Connecting a client to a server
Getting ready
How to do it...
How it works...
Setting up asynchronous play for a turn-based game
Getting ready
How to do it...
How it works...
There's more...
Index

GameMaker Cookbook

GameMaker Cookbook

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2015

Production reference: 1151215

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78439-984-9

www.packtpub.com

Credits

Author

Brandon Gardiner

Reviewers

Ryan Laley

John M. Walker, PE

Commissioning Editor

Nadeem N. Bagban

Acquisition Editor

Kirk D'costa

Content Development Editor

Siddhesh Salvi

Technical Editor

Madhunikita Sunil Chindarkar

Copy Editor

Rashmi Sawant

Project Coordinator

Nidhi Joshi

Proofreader

Safis Editing

Indexer

Hemangini Bari

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

About the Author

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.

About the Reviewers

Ryan Laley is an independent games designer. He has been a lecturer in video games design at South Essex College at further and higher education levels for over 5 years. He has been using GameMaker: Studio professionally during those years, and he continues to develop and publish games using it. He began his teaching career after graduating from university, and since then, he has covered every aspect of games development in his classes, including 2D and 3D.

In his spare time, he independently develops his own games and publishes them himself under the studio name of Friendly Fire games. His most recent projects focus on mobile phone platforms, with his latest release Blobb in 2015. His future projects will continue to expand on mobile platforms and eventually onto PCs.

I'd like to thank Jade for her continued support and allowing games to continue to be more than just a fun past-time, but a career as well.

John M. Walker, PE is a licensed professional engineer in industrial engineering and is currently a licensed full-time teacher in computer science and programing at Cleveland High School in Portland, Oregon. He has been teaching full time for the last 15 years for High School and Regional Professional Higher Ed conferences.

He has worked for more than 20 years as an information technology manager for high-technology firms dealing with systems administration and networking architecture and engineering. His favorite position was director of technology for the Portland Trail Blazers, while designing and constructing the Moda Center.

He has also reviewed GameMaker Essentials, Packt Publishing.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

Since 1999, GameMaker: Studio has enabled fledgling and experienced developers alike to help create video games quickly and easily. In the years since its initial release (as a program called Animo), GameMaker has grown and evolved into a viable commercial game engine that has helped developers release games for PC, Mac, mobile devices, and even the Microsoft Xbox and Sony PlayStation family of consoles.

During its progression, GameMaker has changed in many ways, adding new features and abilities to be taken advantage of by developers around the world. Though these features may be out of reach for new users, the goal of this book is to familiarize beginners and bring such elements within reach. This book is not just a how-to manual, it is an answer to the question "What can GameMaker do for me?"

By reading this book and completing the recipes therein, you will gain a greater understanding of GameMaker's capabilities as well as start them on the path to unlock their full potential.

What this book covers

Chapter 1, Game Plan – Creating Basic Gameplay, shows you how to create the basic elements of a game.

Chapter 2, It's Under Control – Exploring Various Control Schemes, helps you figure out how to implement user controls for a variety of devices.

Chapter 3, Let's Move It – Advanced Movement and Layout, teaches you more advanced ways to move players and non-player characters alike.

Chapter 4, Let's Get Physical – Using GameMaker's Physics System, introduces you to the physics system and demonstrates how GameMaker handles gravity, friction, and so on. You will also learn how to implement this system to make more realistic games.

Chapter 5, Now Hear This! – Music and Sound Effects, helps you pick up the ins and outs of GameMaker's audio system.

Chapter 6, It's All GUI! – Creating Graphical User Interface and Menus, discusses the most important element of the Graphical User Interface (GUI).

Chapter 7, Saving the Day – Saving Game Data, discusses how GameMaker handles how to save data as well as its various uses.

Chapter 8, Light 'em up! – Enhancing Your Game with Lighting Techniques, helps you understand how GameMaker's surfaces can add lighting effects to your game.

Chapter 9, Particle Man, Particle Man – Adding Polish to Your Game with Visual Effects and Particles, shows you how GameMaker handles particles and how you can draw players in with simple effects.

Chapter 10, Hello, World – Creating New Dimensions of Play Through Networking, teaches you how to create multiplayer games with GameMaker's networking capabilities.

What you need for this book

For this book, you will require the following software:

Windows XP or above512 MB RAM128 MB graphicsA screen resolution of 1024×600An Internet connection for some features

For a detailed platform-specific list of requirements, refer to http://www.yoyogames.com/studio/system-requirements.

Who this book is for

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

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Create a sprite and name it spr_enemy_patrol."

A block of code is set as follows:

x1: -16 y1: -24 x2: 16 y2: -34 back color: black bar color: green to red

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Click Add Event, then Other, and select Animation End."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

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.

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/9849OS_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Game Plan – Creating Basic Gameplay

In this chapter, we'll cover the following:

Animating a spriteMoving your playerAdding projectilesCreating hazardsProgramming basic enemiesSetting up player health and livesCreating a scoring mechanismCreating 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.

With Sprite Properties open, click on Edit Sprite to open the Sprite Editor. 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.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.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.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.

Open up Sprite Properties for spr_player_walk and click Edit Sprite.Select whichever frame you feel looks best as an idle pose (I chose the first frame).Click Edit, then click Copy.Close Sprite Properties, create a new sprite, and call it spr_player_idle.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...

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.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.The actions we want apply to obj_player, so select Applies to Self.Since we want to use spr_player_walk in this case, select the sprite from the drop-down menu.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.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.

Under the Control tab, drag and drop Test Variable to the Actions box.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.Close the Test Variable box and under the Move tab, drag and drop Jump to Position to the Actions box.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.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.

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

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.)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...

Open the Object Properties for obj_player and add a Create event. Under the Control tab, drag and drop Set Variable to the Actions box. Name the variable dir and set the value to 1.In the Keyboard event for right, drag and drop Set Variable from the Control tab and have it set dir to 1.Do the same for the left keyboard event but have it set dir to -1.Now create a Key Press event and select <Space>. Under the Main1 tab, drag and drop Create instance to the Actions box.Select obj_projectile from the menu but leave the x and y values as 0.Open the Object Properties for obj_projectile and add a Create event.Under the Control tab, drag and drop Test Variable to the Actions box. Under Applies to select obj_player and have it test whether or not the variable dir is equal to a value of 1.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.In the same Create event, repeat these steps but check dir