GameMaker: Studio Manual

Version 1.4
by
YoYo Games Ltd.

Welcome to the GameMaker: Studio user manual! This document is divided into three parts with the aim of getting you introduced to the interface and basic workings of GameMaker: Studio before going on to more advanced usage and the functions available through GML (the GameMaker Language). New users should definitely start at the beginning with the Using GameMaker: Studio section as it has all the information you need to get started as quickly as possible, however users of previous GameMaker versions can probably skip to the Advanced Use section to see what's new in this version. Whatever your skill level, we hope that this manual helps you to realise the true power within GameMaker: Studio and make your gaming dreams become reality!

NOTE: Due to the modular nature of GameMaker: Studio there are certain things that are not included in the manual, particularly those aspects of setting up and connecting the different devices that can be supported. For up-to-date information and troubleshooting hints and tips, please see the YoYo Games Knowledge Base.

Using GameMaker: Studio

This section describes the basic use of GameMaker: Studio, explaining the idea behind the program and describing how to add sprites, backgrounds and sounds. It also covers how to define objects with events and actions, and how to add them into the rooms that you design. Please note that the availability of certain tools and the number of certain resources that you can create may be restricted depending on the version of GameMaker: Studio that you use (more information can be found here).

The following sections exist to help get you started:

  1. Introduction
  2. Installation
  3. Activation
  4. GameMaker: Studio Overview
  5. The Graphical User Interface
  6. Loading Sprites
  7. Sounds And Music
  8. Backgrounds
  9. Defining Objects
  10. Events
  11. Actions
  12. Creating Rooms
  13. Distributing Your Game

Advanced Use

The GameMaker: Studio IDE (integrated development environment) has a number of advanced options that are of great importance if you wish to get the most out of the product. These options include source control integration, project configurations, advanced debugging and a number of extra tools for changing and manipulating the game assets (please note that the availability of some of these advanced tools will depend on the version of GameMaker: Studio that you currently use). This section of the manual is split into the following three parts, each with its own subsection dealing with one particular aspect of the IDE:

Game Assets

  1. More About Sprites
  2. More About Backgrounds
  3. More About Objects
  4. More About Rooms
  5. More About Async Events

Resource Editors

  1. Fonts
  2. Paths
  3. Time Lines
  4. Scripts
  5. Shaders
  6. Constants
  7. Including Files
  8. Importing Resources

Game Settings

  1. Extension Packages
  2. Configurations
  3. Source Control
  4. Global Game Settings
  5. GameMaker: Studio Preferences
  6. Debugging

Reference

Here you can find references for many of the GameMaker: Studio features, as well as a rundown of all of the functions, variables and constants that make up the built-in programming language. This language gives you much more flexibility and control over your games than the standard actions and we will refer to it as GML (the GameMaker Language). You can find descriptions of all the functions available in GML as well as an overview of how they can be used along with examples of code using them. We also cover the constants and variables that GML has available to control all aspects of your game.

This section contains an overview of the GameMaker Language, with the rules for structure and syntax, as well as examples of how to use expressions and different operations:

  1. GML Overview

The following sections all detail the many different functions that are available to you when using GML. They have been split into different groups of associated functions and, where necessary, have been cross-referenced with related functions and sections.

Real Numbers And Strings

  1. Date and Time
  2. Maths
  3. Strings

Game Play

  1. Game Assets
  2. Mouse, Keyboard and Other Controls
  3. Movement and Collisions
  4. Objects and Instances

Drawing And Display

  1. Drawing
  2. Shaders
  3. Surfaces
  4. The Display, Windows And Views

Advanced Functions

  1. Data Structures
  2. Particles
  3. Physics
  4. File Handling
  5. Operating System
  6. Buffers
  7. Networking

Platform Specific

  1. HTML5
  2. Windows 8
  3. Social Gaming
  4. In App Purchases
  5. Push Notifications
  6. Asynchronous
  7. Cloud Services
  8. Steam API

Extras

  1. Debugging
  2. Miscellaneous
  3. Obsolete Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Using GameMaker: Studio

GameMaker: Studio is an easy to use program for creating your own computer games.

GameMaker: Studio by default only permits you to export games for Windows, while the Professional version also permits you to compile for macOS and Linux (Ubuntu) (as well as use additional functionality). If you have bought GameMaker: Studio through Steam, you will also have an additional target module to export your games to the Steam Workshop. You can get further additional modules which will permit you to export to other platforms like HTML5, Android and iOS.

  1. The HTML5 module enables you to produce ready-to-run HTML and JavaScript code that you can host or embed on any website
  2. The Android/Fire module enables you to create and distribute *.apk files
  3. If you have an iOS developer account then with the iOS module you can also publish to iPad, iPhone and iPod
  4. With the Mac OSX module you can target the Apple desktop market
  5. The Linux module permits you to make desktop games that run on the Ubuntu operating system

These modules are available only to those who have upgraded to the Pro version of GameMaker: Studio (more information on the different versions can be found here).

This section of the help file gives you all the information you need for creating your first games. Later sections will discuss more advanced topics, how to polish and distribute your game, and the built-in programming language GML that considerably extends the possibilities of the product.

Information on the basic use of GameMaker: Studio can be found in the following sections:

  1. Introduction
  2. Installation and System Requirements
  3. Activation
  4. GameMaker: Studio Overview
  5. The Graphical User Interface (GUI)
    1. - The File Menu
    2. - The Edit Menu
    3. - The Resources Menu
    4. - The Scripts Menu
    5. - The Run Menu
    6. - The Help Menu
  6. Loading Sprites
  7. Sounds And Music
  8. Backgrounds
  9. Defining Objects
  10. Events
    1. - Create Event
    2. - Destroy Event
    3. - Alarm Events
    4. - Step Events
    5. - Collision Event
    6. - Keyboard Events
    7. - Other Events
    8. - Draw Event
    9. - Asynchronous Events
  11. Actions
    1. - Move Actions
    2. - Main Actions, Set 1
    3. - Main Actions, Set 2
    4. - Control Actions
    5. - Score Actions
    6. - Extra Actions
    7. - Draw Actions
    8. - Using Variables and Expressions in Actions
  12. Creating Rooms
    1. - Settings
    2. - Backgrounds
    3. - Objects
  13. Game Information
  14. Distributing Your Game
Back: Contents
Next: Advanced Use

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Introduction

An introduction to GameMaker: Studio.

We all know that playing computer games is fun. But what many people don't realise is that it is actually more fun to design your own computer games and let other people play them! Now, making computer games is not normally a simple thing and the commercial games you buy nowadays typically take two or three years of development with teams of anywhere between 10 and 50 people and budgets that can easily reach millions of dollars. Not to mention the fact that all these people are highly experienced: programmers, art designers, sound technicians, etc.

But that's changed with the advent of GameMaker: Studio. With GameMaker: Studio you can start to prototype and create your own computer games quickly and easily without the absolute need to learn a programming language.

GameMaker: Studio offers an intuitive and easy to use Drag-and-Drop (referred to as 'DnD' from now on) interface of action icons that allow you to start on creating your own games very quickly. You can import and create images and sounds to use in objects, and then instantly see the results of your actions at the press of a button. Obviously, you want to get started as quickly as possible, so GameMaker: Studio is bundled with a number of tutorials and demos which you can import and use to get straight to work. These tutorials contain many sprites and graphics which are designed as "place holders" to get you going but they are not for use in any finished product. It should be noted here that GameMaker: Studio focuses on two-dimensional games (which isn't to say that it's not capable of 3D, as it is!) and many great games use 2D sprite technology, even though they look very 3D when playing.

As mentioned previously, you need to assign images (sprites) and other things to objects, which are easily defined in your game through the DnD action icons to give them properties and behaviour, after which you place them in rooms along with backgrounds and other things to give your game the look and feel you want. It's in these rooms that the game takes place, and they can be considered essentially as "levels" to your game. If you master the DnD interface and how it works to control basic things in objects, you can then move on to the easy to learn programming language GML which gives you much more control over every aspect of GameMaker: Studio.

This help file will tell you the most important things you need to know about GameMaker: Studio and how you can create your own games with it. Please realize that, even with a program like GameMaker: Studio, designing computer games is not completely effortless - so no "make a MMORPG" button here! Be aware too that there are many aspects to making games that are all equally important: game-play, graphics, sounds, user interaction, etc... but, the most important aspect of all, is patience. While GameMaker: Studio is a powerful tool, it cannot do everything for you at the touch of a button so start small with simple examples and you will realize that not only is creating games great fun, but that learning to use GameMaker: Studio to do it is also very rewarding!

For more information, examples, tutorials, ideas and links to helpful forums and other great sites, check out the website

http://www.yoyogames.com/

Soon you will become a master GameMaker yourself. Enjoy the experience!

Back: Using GameMaker: Studio
Next: Installation and System Requirements


Installation and System Requirements

Installing GameMaker: Studio for personal use.

If your version of GameMaker: Studio has not been bought through Steam, you will need to run the program GMStudio-Installer.exe and follow the on-screen instructions to install. You are given the option to install the program anywhere you like but it is recommended that you follow the default suggestions given. Once installation is completed, in the Start menu you will find a new program group where you can start GameMaker: Studio.

NOTE: If you have bought GameMaker: Studio through Steam, the program should install automatically, giving you the option to create a start menu icon and a desktop icon. Either of these can then be used to run the program on your computer, or you can run it through the Steam Client window library page too.

Basic Requirements

Any computer that is less than five years old should be able to run GameMaker: Studio without any problems, but here are the minimum specs for your PC to use the program, and then the necessary specs for each of the additional modules that you may have.

IMPORTANT: The required SDK and OS given for each platform may be different at the time of use due to changes made between updates to GameMaker. You can always find the latest requirements from the YoYo Games helpdesk here.

Windows

GameMaker: Studio requires a reasonably modern PC running Windows XP, Vista, 7, or later. A DirectX 9 (or later) compatible graphics card with at least 32MB of memory is required for most created games. It requires a screen resolution of at least 1024x768 and 65536 (16-bit) colours (but preferably 32-bit true colour). Also a DirectX 9 compatible sound card, or integrated sound chip, is required. It is always recommended that you make sure you have the most recent drivers installed for your system.

GameMaker: Studio requires DirectX version 9.0 or later to be installed on your computer. (You can download this version of DirectX from the Microsoft website at: http://www.microsoft.com.) When designing and testing games, the memory requirements can be pretty high (at least 128 MB and preferably more, but this depends on the operating system). When just running games, the memory requirements are less severe and depend a lot on the type of game as well as the resources being used.

NOTE: Although most modern PCs ship with DirectX 10 and higher, this does not mean that DirectX 9 is present on your machine, and you should still install it from the link given above!

Please note that Steam users also have an additional target for compiling games which is the Steam Workshop. While creating and testing your game, this target module will work exactly the same as the standard Windows module, however when creating your final executable you will be shown additional options to submit the game directly to Steam. More information can be found here.

Additional Modules

The above modules are included as standard for all versions of GameMaker: Studio but the following modules are available only to those who have upgraded to the Professional version (more information on the different versions of GameMaker: Studio can be found here).

Mac OS X

To use the Mac OS X target module, you will need to have a Mac computer with an Intel chipset and running Mavericks (OSX 10.9) OS or above. You will also need to download and install Xcode for your version of the OS (minimum Xcode version 6). It's generally recommended that you use the latest OS X and the latest Xcode (you can find the version your Mac has by clicking on the "Apple" logo in the top left and selecting the "About this Mac" option from the drop down menu).

Further information on setting up the Mac OS X module can be found on the YoYo Games Helpdesk.

Ubuntu (Linux)

The Linux module is designed to be compatible with the Ubuntu operating system, and although it should work with other Linux systems, it is only guaranteed to work with the latest versions of this popular Linux OS.

Further information on setting up the Ubuntu module can be found on the YoYo Games Helpdesk.

iOS

The GameMaker: Studio iOS module requires that you have a Mac computer (or at least access to one) and that it meets the minimum requirements for the MacOSX target module (see above) and you must be a registered Apple developer and have all certificates and licenses up to date. For more information on becoming a registered Apple Developer and how to get the necessary certificates, please visit the Apple Developer site here.

Nearly all iOS devices are compatible with GameMaker: Studio including:
  • iPhone 4, 4S, 5, 5C, 5S, 6, and 6plus
  • iPad 1 and above
  • iPod Touch 3rd Gen and above

It also doesn't matter if you are testing on an iPhone or an iPad as all iOS project builds created by GameMaker: Studio are, as standard, universal apps. This means that they will run on both iPhone and iPad devices without problems.

Further information on setting up the iOS module can be found on the YoYo Games Helpdesk.

Android and Amazon Fire

Before actually starting to work with GameMaker: Studio and Android or Amazon Fire, it is worth noting that the devices that will play your game vary immensely in capability. The GameMaker: Studio runner will only work with Android 2.3(Gingerbread) and above (API Level 9 and above in the Android SDK), which covers the majority of devices around at the moment but not all of them, so please check and make sure which version of Android your device uses. It is also recommended that your device have a dedicated GPU with OpenGL version 1.1 or above. Devices without a GPU will still run your GameMaker: Studio projects, but expect them to have a severe drop in performance. The Amazon Fire target supports all Fire TV devices, the Fire Stick, and all Fire Tablets.

You will also need to download the Android SDK as GameMaker: Studio requires some of the components of the different Android versions and the Platform Tools it installs. You can get a copy of the SDK here. if you are also using the YoYo Compiler (YYC) then you will also need to install a copy of the Android NDK which can be found here.

Further information on setting up the Android module can be found on the YoYo Games Helpdesk.

HTML5

The HTML5 export module requires only an HTML5 compliant browser. Note that although most modern browsers are capable of running HTML5 games, not all of them support the WebGL standard currently, so we recommend Chrome for testing as that shows all the features supported by the module.

Further information on setting up the HTML5 module can be found on the YoYo Games Helpdesk.

The YoYo Compiler (YYC)

The YYC takes the normal GameMaker: Studio output and then compiles that into native code for the target platform, "stripping out" unneeded functions and performing a host of other optimisation techniques to create a smaller and performance enhanced executable. This can increase your games performance by at least two or three times, especially on logic-heavy games, and gives an incredible overall boost to performance, ideal for those larger or CPU intensive games.

The YYC is really a number of separate modules, one for each available target, and will be made available to you when you get any supported target module. So if you have, for example, the iOS and Android modules, then you will see two new modules added to your target list apart from the standard ones - iOS (YYC) and Android (YYC). Should you get other modules at a later date, the YYC will update too and show an extra (YYC) module for that target platform.
NOTE: The YYC is not available for the HTML5 target, nor any of those that are JavaScript (JS) based.

The requisites for the YYC target module will depend on the original target modules that you have and wish to use it with, as they will need to be set up correctly before the YYC will work correctly. You can find further information about this from the YoYo Games Knowledge Base as well as on the individual target module Global Game Settings pages detailed in this manual.

For further information, advice and troubleshooting please consult the YoYo Games Knowledge Base where you will find detailed information of how to setup all platforms for use with GameMaker: Studio.

Back: Using GameMaker: Studio
Next: Activation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Activating GameMaker: Studio

GameMaker: Studio requires an internet connection to activate your licence before you can use it.

Once you have installed your version of GameMaker: Studio you will be shown the following Welcome Screen: From here you have three options:

  • GameMaker Studio 2 Trial - Here you can find a link to downloading GameMaker Studio 2 and setting yourself up a free trial (if your YoYo Account isn't already set up for this)

  • YoYo Account - If you have already set up your YYA (YoYo Account) then you can enter your Email and Password to licence GameMaker: Studio and start making games. Note that if you have a GameMaker: Marketplace account, then you can use the email/password that you set up for them here too.

  • Studio Licence - If you have an existing GameMaker: Studio licence and do not currently wish to register for a YYA (YoYo Account), then you can input your existing licence here.

After licensing you will be prompted to restart GameMaker: Studio. If your licence has any extra modules attached to it, you may be prompted to download additional files and then restart again before you can access them.

Important

While GameMaker: Studio itself does not require an internet connection to be used, it will require occasional access to maintain the license activated. If there is no internet connection when requested, your copy of GameMaker: Studio will not work except as the "free" version until such time as this is resolved.

Additional Modules

GameMaker: Studio 1.4 is no longer available for sale and as such you can not add extra modules onto your licence now. If you would like to purchase new platforms you would need to get GameMaker Studio 2 (which is a separate product and your current license would not carry over).

Back: Using GameMaker: Studio
Next: GameMaker: Studio Overview

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


GameMaker: Studio Overview

This section explains some of the some of the core concepts of how GameMaker: Studio works so you can start making games as quick as possible.

The Global idea

Before delving into the possibilities of GameMaker: Studio it is good to get a feeling for the idea behind the program. Games created with GameMaker: Studio take place in one or more rooms. Now, these Rooms are flat 2 dimensional spaces but they can contain 3D-looking graphics as well depending on how you use them. In these rooms you place objects, which you can define within the program. Typical objects can be walls, moving balls, the main player controlled character, enemies, and anything else you can think of from games that you have played! Some objects, like walls, just sit there and don’t do anything, while other objects, like the main player controlled character, will move around and react to the input received from the player using keyboard, mouse, or joystick. For example, when the main character meets an enemy he might die or he might fight the enemy and score points. As you can see, objects are the most important ingredients of games made with GameMaker: Studio, so let us talk a bit more about them.

An Overview of Objects and Rooms

First of all, most objects, when placed as instances within a room, need some image to make them visible on the screen. Such images are called sprites. A sprite is often not a single image but a set of images that are shown one after the other to create an animation and in this way it can look like a character is walking, or a ball is rotating, or an enemy is exploding, etc... During the game, the sprite of a particular instance of any object can be changed, so a character can look different when it walks to the left or to the right, for example. You can create your own sprites in GameMaker: Studio or load them from files and use them "as is" or edit them yourself with the powerful GameMaker: Studio sprite editor. Here is an example of how a typical object looks:

For an object to actually do something, we need to give it actions, but we also need to tell it when to complete these actions. To do that we use EVENTS. An EVENT is a special moment in which we can place certain actions and be sure that those actions will only happen when that EVENT is triggered. There are a large number of different events that can take place and a large number of different actions that you can let your objects take too. For example, there is a Create Event that is performed only when the object gets created. Actually, that's not quite true! Objects are never created, rather they are used to create instances... An instance is a copy of the base object, complete with all the same events and actions, and it's these that are used in your games. Think of an object as the blueprint, and the instance as a manifestation of that blueprint. For example, to add motion to a ball object when we create an instance of it in a room, we would add a motion action to the create event of the object.

Another example of an event is the Collision Event. This is triggered when two instances of any objects collide in the game room. In such a case you can make the instance stop or reverse direction or any number of other actions, like play a sound effect or add points to a score. Further events include the Keyboard Event (for when the player presses a key), Mouse Event to detect mouse buttons, and the Draw Event which is where we can tell each instance of an object to draw whatever we want. There are still more events for each object and these are covered further along in the manual.

Once you have defined your objects it is time to define the rooms in which they will be placed. Rooms can be used for levels in your game or to show information or even to hold a start menu. There are actions to go from room to room so that you can create button objects that, when pressed, will move the player from one room of the game to another. It should also be noted that if you do not have any rooms in your game then GameMaker: Studio will not run your game. But how do you create a room? GameMaker: Studio has a complete editor for creating these areas and in the editor you can add and change many aspects of how the room will look and play. For example, you can add backgrounds in that can be either a simple colour or an actual image. Such background images can be created in GameMaker: Studio with its own editor, or you can load them into the resources from files. Backgrounds can actually be made to do a lot of things but for the time being, just consider it as something that makes the rooms look nice. Next, you can place one (or multiple!) instances of any objects you have created into the room. For example, you want to have a large walled area in your game, so you would define one wall object and then place multiple instances of that object in your room to create large, complex walled areas. The same can be done for enemy objects too! Just make one enemy object, and then place multiple instances within your room to get a whole level created from only a few base objects. Here is an example of how the room editor typically looks:

Once you have completed the design of your rooms, you are ready to run the game. The first room to be shown is always the first room in the main list of rooms and it will be run at the start. Now the instances you have placed will come to life because of the actions defined in their object create events and they will start reacting to each other due to actions placed in the object collision events. They will also react to the player using the actions placed in any keyboard or mouse events.

That covers the two most important things in GameMaker: Studio, but there are a few more! All together they are called resources and assets, and in the main screen of GameMaker: Studio you can find them on the left-hand side in a space called the resource tree. Here is a list of them and you should know that they will all play a crucial role in creating your game:

  • Sprites: images (often animated) that are used to represent the objects

  • Sounds: can be used in games as either background music or as sound effects

  • Backgrounds: still images used as background for the rooms

  • Paths: these can be used to make instances move along a pre-defined path

  • Scripts: a script is a piece of code to which you give a name and use like a GML function

  • Shaders: a shader is a combination of two "programs" written in a shader language to create graphical effects

  • Fonts: to draw text in the game you can add fonts of many different styles

  • Time lines: can be used to control the precise moment in a game that things should happen

  • Objects: which are the building blocks on which your game is built

  • Rooms: the space (levels) in which the objects are placed

  • Included Files: files that your game will export to the chosen target for use

  • Extensions: the extensions included with your game to expand functionality

  • Constants: a per-configuration list of the constants that you define for your game

Note: To help you get familiar with GameMaker: Studio, it is strongly recommended that you follow some of the beginner tutorials that come bundled with the program. These can be found from the Tutorials tab on the start-up splash screen, and cover all basic functionality.

Back: Using GameMaker: Studio
Next: The Graphical User Interface

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Graphical User Interface

The Graphical User Interface (GUI)

This page outlines the options available to you from the GameMaker: Studio GUI.

On starting GameMaker: Studio the following form is normally shown which presents you with a selection of options to choose from (unless you use the Steam Client, see below):

If you have bought GameMaker: Studio through Steam, then on startup you will be presented with an options screen (shown below) from which you can select to Play games from the Steam Workshop, or to Make games with the program. If you select Play then GameMaker: Studio will close and the Steam Player will open, however if you choose Make then you will be presented with the standard GameMaker: Studio start-up screen.

At the top of the general start-up screen you can see that there are nine tabs: Welcome (always the initial start-up screen), Open, New, Import, Release Notes, Demos, Tutorials, News and Licences. Here is a brief overview of the function of each of those tabs:

  • Welcome: This is the start-up screen you see when opening up GameMaker: Studio. At the bottom you have a list of previously opened files.

  • Open: Here you can browse your computer for files to open.

  • New: This will ask you to select the directory you wish to use for a new project and prompt you to enter a name for this project which is then saved and opened in the main GameMaker: Studio runner.

  • Import: Here you can load up the compressed *.gmz project files and also import game files created with other versions of GameMaker, including GameMaker 6 (*.gm6), GameMaker 7 and 8 (*.gmk and *.gm81) as well as GameMaker 8.1 (*.gm81) and much older (*.gmd) files. It should be noted, that the older the file type, the less likely they are to run without a lot of rework due to the changes wrought in GameMaker through the years. Additionally, you can load up GameMaker backup files (*.gb1, *.gb2 etc) from this tab too.

  • Release Notes: If you click on this button you can see the release notes for each released version of GameMaker: Studio. These notes outline all the bug fixes and changes that have been incorporated into the program and tell you which version you are currently using.

  • Demos: This will allow you to view demo files that come with GameMaker: Studio. Demos are different to tutorials in that they focus on explaining just one function or concept rather than giving a general overview, and as such it is recommended that you have a working knowledge of GameMaker: Studio and GML before opening these. These demos are pulled from an RSS feed, so you will need an active internet connection to access them. You can also refresh the feed (to check for new files) by clicking the button at the bottom left of the window.

  • Tutorials: This tab shows you a selection of tutorials that come with GameMaker: Studio. These are designed as an introduction to using GameMaker: Studio and it is recommended that new users look them over before starting any new projects of their own. As with the Demos, these are pulled from an RSS feed, so you will need an active internet connection to access them. You can also refresh the feed (to check for new files) by clicking the button at the bottom left of the window.

  • News: This will display the most recent news from YoYo Games. This news includes information about GameMaker: Studio development, new versions, competitions and anything else that has been posted on the YoYo Games website.

  • Licenses: This tab will display the GameMaker: Studio license, as well as all the various third party licenses of products that are used.

Beneath the tabs, there is a section with hints, tips and offers related to GameMaker: Studio, which you can scroll through using the arrow icons on either side, and beneath that you will see listed any projects that you have previously opened so that you can quickly get back to work where you left off previously.

Creating Your First Project

To begin creating your first game project, you can click on either the New Project tab, where you can select to either load a previous project, or start a new one. When starting a new one, you can provide the directory to save the project files to (which will be saved using the *.GMX format), as well as assign a name to your new project. Clicking Create will then create and save the initial project files.

The GUI

Once you've loaded or created your project in GameMaker: Studio the main GUI is shown and looks something like this:

This is the main interface for GameMaker: Studio and it's here that you control every aspect of your current project. On the left, you can see the different resources mentioned in other sections of the manual: Sprites, Sounds, Backgrounds, Paths, Scripts, Fonts, Time Lines, Objects, Global Game Settings and finally, Extensions. At the top of the window there is the menu and a handy toolbar to access some of the most used commands when creating a game. We will briefly discuss the various menu items, buttons, etc... below, but they will be covered far more in-depth in the later sections of the manual. One thing you should realise at this point is that many of the same things can be achieved in various different ways when working with GameMaker: Studio, either by choosing a command from the menu, by clicking a toolbar button, or by right clicking on a resource. This redundancy is there so that you can get working with GameMaker: Studio in the easiest and most natural way, using whatever system you feel most comfortable with.

Steam users have three additional buttons on the toolbar:

This first button will open the Steam Player where you can play any games you have subscribed to or uploaded to the Steam Workshop.
This second button will open up the page of the GameMaker: Studio Steam Workshop in the Steam client window on your PC.
The final button available to you will open another version of the GameMaker: Studio IDE so you can have two (or more) projects open at one time.

The Resource Tree

At the left of the main form you find the resource tree. Here you will see a "tree" view of all the resources in your game. It works in the same way as Windows Explorer, and you are most likely familiar with how it should work. If an item has a + sign in front of it you can click on the sign to see the resources inside it (expand it). By clicking on the - sign these disappear again (collapse it). You can change the name of a resource (except the top level ones that show the type of resource contained within) by selecting it once with a single click, and then giving another single click on the name once again. Double clicking on a resource in quick succession will automatically open its properties form where you can edit and change things related to it. Use the right mouse button to call up a context specific window that contains most of the same commands as found in the Edit Menu where you can add, copy, remove or view the selected resource. You can find a full list of the resource tree right-click menus from the following section:

  1. Right Click Menus

You can change the order of the resources by clicking on a specific resource and then dragging it to the appropriate place within its resource group. You can also filter the resource tree to only show those things that are of interest to you using the search and filter options at the bottom:

The Toolbar

The toolbar in GameMaker: Studio contains buttons to create each of the resources you see present as well as a selection of additional buttons to create a new project, open an existing project, save a project, create an executable (export a final project), open the Global Game Settings and Extension Packages as well as opening the Help file. All these commands can also be accessed through the drop-down menus or by using certain "hot key" combinations.

There are two buttons of note here however, as they are not present anywhere else in the GameMaker: Studio GUI:

Stop Web Server

This button can be used to cancel the compilation of your games to the target module, or (on certain targets only) to stop the game while it is running after it has been compiled.

Clear Project Asset Compile Cache

Pressing this button will clear the current asset compiler cache. GameMaker: Studio stores images, sounds, scripts etc... between use in a cache so as to save time when testing your game as it will only re-compile those things that have been changed before testing. However, this cache may become corrupted over time, or you may wish to do a full test with no caching being done previously, in which case you can clear the cache by pressing this button.

The Compile Target

This drop-down menu allows you to choose which device to target when compiling and testing your game. In this way you can quickly change between the different modules that you have installed on GameMaker: Studio and make sure that your project works as it should on all of them. The available target modules are:

Windows | included in all versions
Steam WORKSHOP | included in all versions of GameMaker: Studio bought through Steam
MacOSX | additional module for the Professional Version
Windows 8 (Native) | additional module for the Professional Version
HTML5 | additional module for the Professional Version
Ubuntu | additional module for the Professional Version
iOS | additional module for the Professional Version
Android | additional module for the Professional Version
Windows Phone | additional module for the Professional Version

Please note that the additional modules can only be bought for the Professional Version of GameMaker: Studio, and if you have bought GameMaker: Studio through Steam, you will also have another target platform for your game which is the Steam Workshop. This target will permit you to publish your Windows games straight to Steam for others to download and play. For more information on this target please see here.

Configurations

Here you can find a drop-down menu that permits you to select the current configuration of GameMaker: Studio and beside this there is a button labelled "Manage". By clicking this you can open the Configurations Window which permits you to add, remove and rename configurations. For more information on configurations see this section:

  1. Advanced Use - Configurations

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

The Workspace

This is the area where you will be editing your resources, setting up rooms and working with your objects, code and all other resources.

The Main Menus

At the very top of the GUI you will find the drop-down menus. As there are a number of them and each has its own selection of options, you can find out more about them from the pages listed below:

  1. The File Menu
  2. The Edit Menu
  3. The Windows Menu
  4. The Resources Menu
  5. The Scripts Menu
  6. The Run Menu
  7. The Help Menu

Searching The Knowledge Base

There is one final feature of the GameMaker: Studio GUI which is worth noting, and that is the search box that can be found to the top right of the IDE: If you are looking for more detailed information on a subject and the manual doesn't cover it (there are many things outside of the scope of this document) or you think there may be a bug, then you can type a few keywords here and it will search the YoYo Games Knowledge Base then open a tab in your browser showing you a list of the topics that are available. For example, if you require further information on advertising, simply typing "ads" into this search box and hitting "Enter" will take you to the following page: List Of Ads Tutorials.

Back: Using GameMaker: Studio
Next: Loading Sprites

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Loading Sprites

In this section of the manual you can learn about sprites and how to create them with the GameMaker: Studio sprite editor.

Sprites are generally the visual representations of objects within the game you are creating. As such, a sprite is either a single image, drawn with any drawing program you like, or a set of images that, when played one after another, looks like a looping animation. For example, the following 10 images form a sprite for a character who is waving his arms while skydiving.

And the actual finished animation would look like this when placed in a game:

That looks pretty good, eh? Most games need you to make sprites like this for all the things in your game world, from enemies to power-ups, from walls to menus, and when you start to make a game you normally collect or create a set of nice sprites for the objects you are going to use. A considerable number of useful sprites can be found on websites such as Open Game Art, which can be used as "place holders" until you have enough confidence to make your own or get together with an artist.

To create a sprite, choose the item Create Sprite from the Resources menu, or use the corresponding button on the toolbar. Either will cause the following window to open:

As you can probably see, the top left of the window has a field for the "Name" of the sprite. All sprites (and all other resources) must have a name given to them so that you (and GameMaker: Studio!) can identify them easily, although you should note that the actual name itself is really just a variable which holds a number that "points" to the resource, in this case a sprite. It's best to give each sprite a descriptive name so that you can identify at a glance whether a particular resource is a sprite or an object or anything else, and many people do this by prefixing or suffixing the resource with the letters "spr". For example, the above sky diver sprite could be called spr_SkyDiver or SkyDiver_spr. Even though this is not strictly required, you are strongly advised to use only letters and digits and the underscore symbol (_) in a name of a sprite (and any other resource) and to let it start with a letter, not a number as this will become very important once you start using code.

To load a sprite, click on the button Load Sprite. A special file dialog window opens in which you can choose the sprite you want to import into GameMaker: Studio:

The left part is a fairly standard file selector in which you can navigate around your computer and select the sprite that you want to import. On the right you have a preview of the sprite image you select and some basic information about its size. Here you can also indicate a couple of things that you'd like GameMaker: Studio to do when you import the sprite, like make opaque (remove any transparent parts), remove the background colour (if it has one) making it transparent, or whether to smooth the edges of the sprite (only if it is transparent), which can greatly improve its appearance. When you have found the sprite you need and selected the transparency options you like, press Open to load the sprite into GameMaker: Studio.

GameMaker: Studio can load many different formats of graphic files - with JPG, BMP, PNG and GIF being the most common bitmap formats, although you can also import SWF vector sprites and JSON skeletal animation sprites (made with Spine). There are a couple of things that should be noted when loading the different bitmap files:

  • When you load an animated gif, the different images of the animation automatically form the sprite subimages.

  • When the file name ends with _stripXX, where XX a number, it is considered to contain a strip of XX subimages next to each other, and GameMaker: Studio will import it as such. For example, an image file with the name ball_strip4.png is assumed to contain 4 subimages and will be split up as such when loaded.

  • If you have a sprite strip image that you wish to load into GameMaker: Studio which does not have the above-mentioned format, this must be done from the Sprite Editor File Menu.

  • Although JPG images are supported, it is best to avoid using this file type as, due to the compression used, the images are generally of poorer quality than either PNG or BMP.

Once the sprite is loaded you are returned to the sprite properties window where the first subimage is shown on the right of the screen. When there are multiple subimages, you can cycle through them using the arrow buttons that appear beside the part of the window labelled "Show", and, should you make any changes to the sprite, you can then save it again using the "Save" button.

For a more in-depth look at the sprite editor in GameMaker: Studio, as well as details on the SWF and JSON formats, you can go to the Advanced Section of this manual.

Back: Using GameMaker: Studio
Next: Sounds And Music

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Sounds And Music

This section explains how to add a sound resource to your game.

To add a sound resource to your game, use the Resource menu or right-click on the resource tree and select Create Sound, or you can use the corresponding button on the toolbar. Any of those will bring up the following window: To load a sound, press the Load Sound button to the right of the sound name. A file selector dialogue pops up in which you can select the sound file, which can only be either a wave file or an MP3 file. In general, Wave files (*.wav) are used for the short sound effects as even though they are generally larger files they will play instantaneously due to the fact that they do not need any type of decoding for playing. You can also have multiple wave files playing at once, which is why you should use these for all the sound effects in your game.

MP3 (*.mp3) files should be used for background music as GameMaker: Studio only permits you to play one music track at a time. These files are much smaller than a wave file would be but have a small CPU overhead as they have to be decoded before being played, hence the limit of only one MP3 file being played at time (however, you can have multiple music tracks in your game, and you would just switch between them when necessary).
Once you have loaded your file you can preview the sound by using the play button which will loop it continuously. This is very handy as it means you can make changes to the volume using the slider at the bottom of the window and hear what the effect it will have on the sound. There is a stop button too, so you can stop the preview at any time.

NOTE: Previous versions of GameMaker accepted MIDI file format but that is not the case with GameMaker: Studio. You cannot use MIDI any longer and any imported files from legacy versions which use these may cause the program to crash. These files should be removed or changed before testing!

The sound window also has other options which are explained below.

Audio Groups

You can assign your audio file to a specific Audio group. These are created from the Global Game Settings Audio Groups Tab and are used to to group audio assets together for easier memory management and volume control. Once an audio file has been assigned to a group you can then use the specific audio group functions to change them and lo load/unload them from memory. See the section on Audio Functions for further information. Note that while the rest of the audio properties are configuration specific, the audio group setting is not and a sound will belong to the same group on all configurations that you use.

NOTE: Audio groups can only be used when working with the normal audio system, but will not work with legacy audio.

Compression

The above rules for file types are for the default configuration of Uncompressed audio. However, you can select to Compressed audio should you wish to use that. What this will do is force all your sound files (irrespective of whether they are *.wav or *.mp3) to be compressed down to Ogg Vorbis *.ogg format files for all platforms.

These sounds are smaller on disc, but will have a slight CPU overhead due to the need to be uncompressed before being played, so you should keep that in mind if you wish to use compression in an already CPU intensive game.

Streaming

If you have chosen compressed audio, you can then also choose to have your sound as streamed or not streamed. A streamed sound will be one that is uncompressed and played in real time, streamed from the disc. Streaming is ideal for music as it reduces the one off overhead of uncompressing the whole file, which may cause a pause in the game, but is not recommended for simple sound effects where the hit on the CPU is much less.

Quality And Volume

If you have loaded an *.ogg file or an *.mp3 file into the IDE, you will be presented with a "quality" slider. Changing this will change the encoding that is used and therefore reduce (or improve) the final quality of the sound. Note that the better the quality, the larger the file, and that increasing this on a low quality audio file will not improve the quality noticeably and only bloat the final game. In general the default value is fine for most games.

Beside the quality bar for all file types, you can set the maximum volume for a sound, ie: if the slider is at 0.5 then the max volume for that sound when the gain is 1, will be half the recorded volume for the sound. Note that if you are using the legacy audio system to play the sound (or are working on the HTML5 target), this slider is simply the initial volume of the sound and can be changed by setting the volume using the appropriate legacy function.

Target Options

The Target Options panel is where you set the conversion rates for your game. These settings will affect how the sound is exported for the target platform, and GameMaker: Studio will automatically convert your sound files for you - you simply control the final quality of those sounds when converted. Generally the default settings of 16 bit, 44100kHz and 192kbps are perfectly adequate, but it may be that you wish sound effects (for example) to have a lower quality and music to have a higher quality, in which case these settings can be changed.

You can also choose whether the conversion should be mono, stereo or 3D. If you plan on using the audio emitter functions to create 3D sound effects, you should indicate this here, otherwise choose mono or stereo depending on the use that the sounds are going to be put to.

NOTE: The higher the quality, the larger the file, and this should be taken into account when deciding what bitrate to choose.

External Editor

GameMaker: Studio does not have a built-in sound editor. But, in the Editor Preferences, you can indicate external editors that you want to use for editing sounds. If you selected these you can press the button labelled Edit Sound to open the chosen editor and change the current sound. The GameMaker: Studio window will be hidden while you edit the sound and returns when you close the sound editor (you must save the sound in the editor first otherwise it will not be saved in GameMaker: Studio).

Back: Using GameMaker: Studio
Next: Backgrounds

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Backgrounds

Backgrounds are another of the basic resources that you can use in GameMaker: Studio.

These are usually large images that are used as backgrounds (or foregrounds) for the rooms in which the game takes place, but they can also be large images composed of many smaller ones called tiles which you can then place individually in your room to create complex visual designs for levels with far less processing overhead than you would get with objects and sprites.

To create a background resource in your game, use the Create Background option from the drop-down Resources menu or use the corresponding button on the toolbar. Either of those will cause the following window to open: As with all resources, you must give a name to your backgrounds for reference within GameMaker: Studio and so you can identify them easily, although you should note that the actual name itself is really just a variable which holds a number that "points" to the resource, in this case a background. It's best to give each background a descriptive name so that you can identify at a glance whether a particular resource is a background or an object or anything else, and many people do this by prefixing or suffixing the resource with the letters "bck". For example, the above image could be called bck_Horizon or Horizon_bck.

Below the "Name" section are the buttons that enable you to load, save or edit a background image. If you select "Load Background", you will get the standard file selector where you can choose supported image file (PNG, GIF, BMP, JPG.) and also tell GM to make that image opaque (remove transparency), or make it transparent (this takes the colour from the bottom left hand corner pixel as the base colour to make transparent) or to smooth the edges of the background (only when it is transparent). Once you have selected the file and the options, clicking the "Open" button will load the background into GameMaker: Studio ready to be used in your games. Editing the background can be done within GameMaker: Studio too, and we have a whole section in the Advanced Use part of the manual that deals with this here.

Be careful with using large backgrounds, especially if your target device is HTML5 or one of the smaller mobile devices, as large backgrounds need more memory and this could be a problem later when you try to compile your game. You should also be aware that backgrounds in GameMaker: Studio are designed to tile and this means they have overlapping pixels on either side, so if you see any strange artefacts (transparent lines, extra pixels, etc.) then you should possibly be using sprites instead for the graphical effect you wish to achieve.

Editing Backgrounds

For editing backgrounds, GameMaker: Studio has its own included Image Editor which is quite powerful, although not as complete as many dedicated art packages available. For information on how to use it, please see the section More About Sprites: Editing Subimages as there is exactly the same set of tools available for backgrounds as for sprites.

Backgrounds as Tiles

Sometimes you want to have a background image broken up into a set of tiles, which basically means, one large image composed of different sub images that can all be linked together. When creating rooms you can then add these subimages at different places to create beautiful levels with graphical effects that are "cheap" in that they use very little processing power to draw. Please note that tiles are purely graphical and do not have most of the properties you would find in an object or a sprite which is why they are fast. To use a background as a tile set, check the box labelled Use as tile set and the background window now changes to look as follows: Now you can indicate a number of settings for the tile set, like the width and height for each tile (only one size can be given, so better make sure that all tiles in the set have the same size. If you have different sizes, create two or more tile sets). You can also indicate an offset (in pixels) where the top left-most tile starts as well as a separation between the tiles (in pixels) between the tiles themselves. For more information on tiles see the section in the Advanced Use part of the manual More About Backgrounds, and for information on how to use tiles in the room editor you can go to the section More About Rooms.

Back: Using GameMaker: Studio
Next: Defining Objects

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Defining Objects

Objects are the fundamental "building blocks" within GameMaker: Studio.

With the resources you have seen so far you can add some nice images and sounds to the game resource tree, but they don't do anything in the game itself yet! For that we need the most important resource of GameMaker: Studio, the objects. Objects are a special resource that we use to control aspects of a game and to do specific things. Most of the time they have a sprite associated with them so that you see them in the game rooms, but sometimes they are used as a "behind the scenes" controller to do things related to the user or for timing, etc... They can be given behaviors and they can react to certain events as well as to each other, and most of the things you see in a game are based on objects and their interactions. Now, I say "based on" because you don't actually place objects directly into the game rooms, but rather you place instances of these objects which are basically copies (or clones if you prefer) of the object resource. This is a very important thing to remember as instances and objects are not the same thing and each have their own set of functions that can affect them.

Objects and Instances

In a game made with GameMaker: Studio, the characters, monsters, balls, walls, etc... are all instances copied from a basic object template that is found in the resource tree and then placed in a room. So when we talk about something affecting or changing an instance, we mean that one particular copy of an object in a room is being affected while all the rest are not, but when we talk about affecting or changing an object we mean that anything we do to it will be reflected in all the instances created from that point on too. So, the object is the template for the instance, and the instance is what we place in a room to make our game.

Creating an Object

To create an object in your game, choose Create Object from the Resources menu (or click the equivalent button on the toolbar) and the following window will open:

At first glance this may seem rather confusing, but the window is split into sections and we shall cover each one individually so you can get an overview of what they are for. Starting on the left, there is some general information about the object, then in the middle there is the list of events (moments in time) for the object and the window to place the actions that are to be performed in those events, and finally on the right there are the actions themselves which you can select for the object to perform, grouped under different tabs for ease of use. Events and actions will be discussed in more detail in following sections of the manual. If you have "Uses Physics" selected then there will be another part visible in this window related to the physics options, but more on that later!

As you would expect, you can (and should always) give your object a name. This should never contain spaces nor unauthorized characters and should be short but memorable so that you can easily identify resources later when you may have many of them, for example may people use a prefix or a suffix to identify the differences between resources, like "obj_Ship" or "Ship_obj". Next you can choose the sprite for the object should you wish it to have one. To this end, click with the left mouse button on the sprite box or the menu button next to it and a pop-up dialogue will appear with a list of all the available sprites from the resource tree, then just select the one you want to use for the object. You can also drag a sprite resource from the resource tree and drop it onto the object sprite properties and it will be added to the object that way.

If you do not have an appropriate sprite yet, you can click the button New to create a new sprite resource and edit it as you wish, just as if you had created the resource through the standard creation options, only now when you click "Ok", it will automatically be assigned to the object that you had open when you started to create it. Once you select a resource there will be an additional Edit button here that you can use to change the sprite too. This can be faster than first finding the resource in the list of resources and then indicating you want to edit it.

Below this there are many other options which are all outlined below:

Visible

Visible indicates whether instances of this object are visible when the room starts. Normally most instances are visible but sometimes it is useful to have invisible ones - for example, you can use them for way-points to control a moving monster, or to keep track values and perform certain timed actions. Invisible objects will still react to events and if they have a sprite or a mask assigned to them, they will also react should other instances collide with them... they just can't be seen and do not perform their draw event.

Solid

By checking solid you are indicating to GameMaker: Studio that it should consider instances of this object to be a solid object (like a wall). Collisions with instances of solid objects are treated differently from collisions with non-solid objects and as such you are strongly advised to use Solid only for objects that are not moving.

Depth

You can set the Depth of the instances of an object, which basically controls whether they go below or above other objects at other depths. When instances are drawn on the screen they are drawn in order of depth, with instances that have the highest depth being drawn first and instances with the lowest depth being drawn last. The following image illustrates this behaviour: It should be noted here that instances of the same depth that overlap each other in the room editor (or in game) have no guaranteed priority over which one will be "on top" of the other and. If you want to guarantee that an object lies on top of the others then you must give it a negative (or low) depth. Conversely If you want to make sure it lies below other instances then you have to give it a positive (high) depth. Depth can also be changed in-game as it has its own variable that can be changed and manipulated by actions or in code.

Persistent objects

Below depth there is the option to make an object persistent. A persistent object is one that does not go away when the room is changed, but rather it "persists" and is carried over into the new room. It will only disappear when you explicitly destroy it, either with a destroy action or in code. This means that if you place a persistent object in one room, it will still be available in all subsequent rooms and will continue to perform any actions assigned to the events in its object properties. This is handy for when you have, for example, a main character that moves from room to room and you want to maintain the variables within that object the same, but unless you take great care to create and destroy persistent objects correctly, you can easily get errors creeping into your project.

Note too that a persistent object will still have its Game Start, Game End, Room Start and Room End events triggered, however if you restart the game (with, for example, the game_restart() function) all persistent objects will be removed and only exist when created again by the game. Also note that if you deactivate a persistent object, it will no longer pass from one room to another unless re-activated before the Room End event is triggered.

Parents

One of the most powerful options within the object properties is the ability to assign a parent. Every object in the game can have a parent object, but what does this mean? Well, when an object has a parent, it can share code, actions and events with that parent. This is called "inheritance" and an object that has a parent is called a "child". But that's not all! You can also do checks and run code on parent objects which automatically include the child objects too which saves a lot of time and energy. Another way to look at a parent object is as a way to "group" objects together under the same umbrella and have them share certain things without losing their own identity. For more information on parents (and other advanced object properties) see More About objects.

Please note that you can click the Parent button to automatically open the assigned parent object, and you can also see a list of "child" objects for the object if it is selected as the "parent" of anything else. Double-clicking on the object name from this list will open its properties window for editing. You can also drag an object from the resource tree onto the Parent option or the Child option and it will be added as a parent or child as required.

Masks

When an object has a sprite, it also has a mask. This is usually defined by the sprite itself (and can be changed in the sprite editor) but sometimes you may want an object to have a different shaped mask to its sprite, or even have no sprite but still a mask. Why? Well, masks are what govern collisions in GameMaker: Studio. When two instances come together, GameMaker: Studio has to decide whether a collision has occurred and to do this it relies on the mask of the object, either the one defined here or the one that is defined in the sprite properties. If you have no mask then you have no collision! It should also be noted that if you have assigned a sprite to the object and then assign a mask, GameMaker: Studio will always base collisions off of the assigned mask and NOT the sprite. For example, if you make an isometric game, objects typically have a height (to give them a 3D view), but for collisions you only want to use the "feet" part of the sprite. This can be achieved by creating a separate sprite and then assigning that to be used as the collision mask for the object. Please note that you can click the Mask button to automatically open the assigned mask sprite.

Information

The button Show Information gives an overview of all information for the object that can also be printed out or saved as an HTML file. This is particularly useful when you want a loose overview of all your actions, code and events or if you want to debug something within the object.

Uses Physics

When you check this box you are telling GameMaker: Studio that this object should be part of a physics world. This will also open another part of the object window where you can define the physical properties of all instances of this object. More information on this can be found in the Advanced Use section of the manual under More About objects.

Back: Using GameMaker: Studio
Next: Events

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Distributing Your Game

Here we talk about how you can distribute your finished game.

With the information in the preceding sections of this manual you can begin to create your games, but when your game is finished you obviously want other people to play it. You can of course export a *.gmz file and let them use GameMaker: Studio to play it but this is normally not what you want! First of all, you don't want others to be able to change the game or get access to all your hard work, and secondly you also want people to play the game even if they do not have a copy of GameMaker: Studio. So you would like to create a stand-alone application or package of your game, or upload it as HTML5 to a site on the internet so that everyone can play it!

Creating Your Stand Alone Game

Creating stand-alone applications is very easy with GameMaker: Studio. First you have to choose the "target" for the files to be made which means choosing whether you wish to create an *.exe for Windows, generate JavaScript and HTML for use in a browser, or create a package for one of the other target modules. Each of the individual targets has their own settings and you must ensure that they are correctly configured in the Global Game Settings and Preferences before you continue.

Once everything is correct, you then go into the File menu and select the item Create Executable or you can press the following button, found on the main IDE toolbar beside the Play and Debug buttons:
Create Executable For Target
Either option will open a save window where you can give the final name that you wish to use for your game file. Once you have done this, the necessary files will be generated so that you can distribute it as you wish.

NOTE: Before doing a final build of your project for release, you should always clear the Asset Compiler Cache (using the green "broom" icon at the top of the IDE) to ensure that all cached files are recreated and no stale files corrupt your final game.

Target Platform Formats

Each target option saves to a platform specific format:

  • If you have the setting as "Windows" in the main GameMaker: Studio window, then only a Windows compatible file will be made. This can be an installer, a stand-alone *.exe or a *.zip. The export file type is chosen from a drop-down menu within the "Save" dialogue itself, as shown by the image below: Please note that the "Single Runtime Exe" is designed for use only for quick testing and should not be used for distribution (use the Zip or Installer options). When creating a single EXE you can get issues when saving files and it may not run on certain machine conficurations.

  • If you have chosen to build HTML5, then an index.html (default name, but you can give your own name too) along with a folder containing your game's files will be created and saved to the specified location. For your game to work you will need both of these to be uploaded to a server. The index.html can also be customised to show your game with a different background colour, or at a different position etc... but a knowledge of the HTML language is necessary for this (see the HTML5 Tab of the Global Game Settings).

  • For Android devices, a *.apk file will be generated which can be used directly on any Android devices or uploaded to the Google Play or Amazon stores (or any other site that accepts Android apps).

  • For an iOS or Mac build you will need all the appropriate developer permissions and an Apple Mac computer. GameMaker: Studio will create a *.dish file which you will then need to prepare in the Application Oven app on a Mac. This will then generate your iOS or Mac app for you.

  • If you have bought GameMaker: Studio through Steam then you can also compile to the Steam Workshop. For more information see here.

Please note: GameMaker: Studio uses a C++ runner to create all final games and apps. The previous GameMaker versions used Delphi, so this means that any game imported from previous versions may not work without certain changes.

For further information on how to compile a final game for your target platform, and for details on how to upload these to the various app stores available, please see the YoYo Knowledge Base.

Distribution

Once you have created a stand-alone application or package for your game you can then give the file to other people or place it on your website to download. You can also upload these files to the different hosting services for individual distribution or to online stores (like Google Play, iTunes or the MS Store) for general distribution and retail.

Further information on these formats and file creation can be found on the YoYo Knowledge Base.

You are free to distribute the games you create with GameMaker: Studio in any way you like, and this means that you can even sell them! Of course, this assumes that the sprites, images, and sounds you used to make it can be distributed or sold as well and that you have the legal rights to all assets. See the enclosed license agreement for more information on this (available on the Licences Tab).

Back: Using GameMaker: Studio

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Game Information

This section deals with the Game Information window.

Beneath the resource tree on the left of the main GameMaker: Studio IDE you have the Game Information. Clicking on this will bring up a rich text editor as shown in the following image: The game information is basically a scratch pad for you, where you can draught out ideas, to-do lists, contact details and any other information that you may need at a later date or that you don't want to forget. Unlike previous versions of GameMaker this form cannot be shown to the player and as such it is the ideal place to store snippets of information and to plan your game.

Back: Using GameMaker: Studio
Next: Distributing Your Game

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Right Click Menus

This page lists each of the different right-click sub-menus for each section of the resource tree.

The above image shows the sub-menu that opens when you right-click one of the resources in the resource tree. All resources have the same menu with the same items except the Extensions resource which has an extended sub-menu (see the section on Creating Extensions). The options available to you from this menu are:

  • Insert Resource: Insert a new resource in the resource tree and open the editor associated with it.

  • Add Existing Resource: This will open the file explorer so you can add a resource from another project file. You can then select any *.gmx format file and it will be added as another resource to the tree with the same properties and name as it had in the previous project. NOTE: Adding an existing resource does not add any extra resources associated with it. For example, adding a room resource will not also add the objects that were present within the room - although it may reference them which will cause an error when the game is run - or if you add an object resource it will not also add the sprite that was assigned to it. therefore when adding existing resources you should be sure to follow the hierarchy of resources and add the sprites first, the backgrounds next, then the objects, etc... until you finally add the rooms.

  • Duplicate: This will make a duplicate of the selected resource in the resource tree, which you can then re-name and use.

  • Sort By Name: This will sort the resources in the section (or group) selected in alphabetical order.

  • Delete: This will delete the resource from the resource tree. before this happens you will be prompted to check if you are sure, and GameMaker: Studio will perform a resource check to see if the resource is referenced in the project anywhere still. If the item being deleted is referenced - for example, you delete a sprite which is used in an object - then you will be alerted and asked if you want to continue.

  • Rename: You can rename the selected resource from this option.

  • Check References: You can use this option to check and see if any hard references to the resource exist. A hard reference is when the resource is used as part of another resource or has been called in a DnD action - for example, checking the references for a sprite will show all the objects that have that sprite assigned, but will not show any scripts that call the sprite in code.

  • Properties: This will open the context specific properties window for the given resource, ie: the sprite editor for sprites, the path editor for paths, etc...

  • Open In Explorer: Clicking this will open Windows Explorer at the folder where the *.gmx file for the resource is stored.

  • Open In External Editor: Clicking this will launch any external editors associated with the resource, loading the resource in them ready for editing. You can set which editors are assigned to which resource from the Preferences Window

Back: The Graphical user Interface

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Steam Player

Here you can find all the information about the Steam Player.

If your copy of GameMaker: Studio has been bought through Steam, you will see that when you start GameMaker: Studio you are presented with a splash screen containing two buttons - Play and Make. Pressing the Make button will open the standard GameMaker: Studio User Interface where you can begin to create your own games, but pressing the Play button will open the Steam Player:

This player will be empty to start with as you must first visit the Steam Workshop and subscribe to the games that you wish to play. Once this has been done, they will be visible in the Player (you may need to close and restart the Player for these changes to be visible) listed on the left hand side and selecting any one of them will show a screenshot, user information and also permit you to download them by clicking on the "Download" button. Once they have been downloaded, this button turns into a "Play" button and clicking it again will start the game. Beneath the Download/Play button is the Subscribed button. This can be used to unsubscribe the selected game from the player simply by clicking on it, which will turn the button into a green Subscribe button. You may click this again to re-subscribe to the game, but bear in mind that this option is only available until you close the player. Once closed all unsubscribed games will be removed from the playlist and to re-subscribe you must search for them on the Workshop pages.

Finally, on the left of the player is the "Workshop" button and the "Back" button. The "Workshop" button will open up the Steam Workshop for you in your default browser, while the "Back" button will take you back to the main start-up screen where you can choose to start GameMaker: Studio, or restart the player again (this button is only available when the player has been launched from the splash screen and not from GameMaker: Studio).

Back: Steam Workshop

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Steam Workshop

Here you can find all the information about the Steam Workshop target module.

If your copy of GameMaker: Studio has been bought through Steam, you will see that there is an additional target module for compiling to apart from the standard Windows and Mac OS X targets: When running your game through GameMaker: Studio normally (or in debug mode), this target module functions exactly the same as the standard Windows compiler and will permit you to play and test your game in the Windows workspace. However, when you decide to compile you game using the Create Executable command from the file menu or the icon from the toolbar you will be creating a special file which will be uploaded directly to the Steam Workshop.

What Is Steam Workshop?

Steam Workshop is basically a platform for user-generated content, where you can upload your games and have others play them, rate them and comment on them. The games you upload can be works in progress or finished games, but they cannot be for sale as the nature of the Workshop is to offer user created content for free. You should also be aware that the games uploaded to the workshop cannot make use of extensions in any form as Steam consider them to be a security risk. You can have included files however, and you need not worry about whether your games will work on Mac OS X, Ubuntu (Linux) or Windows as that side of things is handled by Steam.

Uploading To The Steam Workshop

When you select the Create Executable for Steam Workshop, a new window will open where you must specify certain details that Steam require for you to upload to their site: At the top of the window, you should add the name of your game (this is what people will see displayed on Steam), then upload a screenshot to show something of your game itself. The screenshot may appear stretched or distorted in this window, but once uploaded it will appear as it should to those that visit the Workshop page for your game. You should then select the visibility of your game which can be either:

  • Private - The game will only be visible to you, Steam administrators, and anyone marked as co-creator.

  • Friends Only - The game will only be visible in searches to you, your friends, and Steam administrators. However, anyone with a direct link may also view it.

  • Public - The game is available to the general public through the Steam Workshop.

After that you can add a description of your game, which can be as long or short as you wish, and finally, at the bottom, you can add search tags too. The search tags are limited to a maximum of three, where the first one must be the "Genre" of the game which you select from a drop-down menu. The other two tags are used for giving the description and can be custom tags that you input (click the box and write the tag) or they can also be selected from a long list of pre-made descriptive tags accessed through another drop-down menu.

When you are happy with the information, you can click on the button labelled Create and your file will be sent to the Steam server automatically. In a few minutes (depending on your internet speed) you should be able to access the file on your Steam account page where you can also modify all the details that you have included when uploading, including adding more screen shots, changing the visibility and editing the description (if you have the Steam client open, you can get to your files through the Community > Workshop > Your Workshop Files).

IMPORTANT! the Steam Workshop does not permit any games that make use of extensions, other than pure GML extensions, as they consider them a major security risk. So if your game requires a DLL or DyLib, etc... it will not be uploaded to the Workshop and you will get en error, probably complaining of an "unknown function". This is because the extension has been stripped from the game and so won't compile correctly.

Playing Your Games

Once you have uploaded a game, to be able to play it you must first subscribe to it by clicking on the Subscribe button of the Steam Workshop page for your games, which can be found in the Community section of the Steam Client, on the right under the Actions menu. To play other games that are available on the Workshop from other users you must also subscribe to them, and all subscribed games will then appear in the Steam Player, which will update as you subscribe to them to show all the available games.

Updating Your Games

Once you have uploaded your game to the Workshop, you may need to update it or wish to change the screenshot chosen for the description, etc... This can be done easily by loading the game into GameMaker: Studio and then choosing the Steam Workshop compile target and hit the Create Executable just as you would when you originally created the game. This time however you should press the button marked "Update Game", which will download all the details of the games you have already uploaded to the Workshop (this may take a few moments depending on the number of games that you have there). The following dialogue will show you the progress: Once all game details have been downloaded the previous "Update Game" button will now show a drop-down list of all of your games. Selecting any one of them will show the previously uploaded screenshot, description and tags which you can then change as you wish. Once finished you should then press the Create button to re-upload the game to the Workshop.

Back: The Graphical User Interface (GUI)


Versions

This section lists the differences between versions of GameMaker: Studio.

There are a number of different versions of GameMaker: Studio available for you to use, and each one is designed to scale to the level of programming experience of the end-user, either with the GameMaker product or in general. All versions can compile to Windows, but apart from these compile targets each available version is different as detailed below.

Should you wish to upgrade your current version of GameMaker: Studio, you can do so through the YoYo Games web site.

GameMaker: Studio

This version is free to download and use, as it is designed to permit the end-user to test the functions of the product before upgrading to a more powerful version. If you have used previous GameMaker products and are thinking about upgrading to Studio then you can use this version to see the differences between it and previous versions, or if you have never used GameMaker before (or are new to programming) then this version is an excellent place to start.

The following limits are present in the FREE Standard version of GameMaker: Studio:

  1. No Configurations
  2. No Extra Target Modules
  3. No Texture Groups
  4. No Audio Groups
  5. No Source Control
  6. Missing features in the image editor:
    • no spare page
    • no creating, saving nor loading of custom palettes
    • no onion skinning

GameMaker: Studio Professional

With the professional version of GameMaker: Studio all limitations are removed and you can experiment with all the features of the program:

  1. Configurations for specific clients or builds
  2. Texture Group and Audio Group control for optimising your games and apps
  3. Source Control for working in teams using Subversion
  4. Android test target for testing your project on Android devices before buying the appropriate target module
  5. Mac OSX and Ubuntu targets as well as the Steam Workshop (requires the Steam version of GameMaker: Studio)
  6. The possibility of buying extra target modules, currently:
    • HTML5
    • iOS
    • Android/Amazon Fire
    • UWP (requires the Master Collection)

Back: Contents

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Actions

This section of the manual outlines what actions are and how to use them in GameMaker: Studio.

One of the things that makes GameMaker: Studio so unique is the ease with which simple commands and functions can be made to manipulate your game world using actions. These actions come in the form of action sets, with each set having a number of icons that you can drag and drop into an object event to create behaviours for that object (this is commonly called just "DnD", in reference to the drag'n'drop aspect). Here are the action sets in full:

All the actions are found in the tabbed pages at the right of the object property form, and as you can see there are seven tabs full of actions for you to use to help create your games. If you require a brief reminder of what each action does while working with GameMaker: Studio you can place the mouse over any of them and a short descriptive text will pop up, and for a more in-depth explanation each tab is explained elsewhere in the manual (see the end of this section).

Adding Actions To An Event

To put an action in an event, just drag it from the tabbed pages to the action list in the object as shown in the image below:

From there you can then edit the details of the action, change the order of actions within the list (by clicking and dragging), copy, paste and even delete actions too. You can also select multiple actions if need be and they can also be dragged or copied from one object's action list to that of another!

Now, as you can see above, when you drop an action in the action list, normally a window will pop-up in which you can fill in certain parameters for the action, and you can find a description of each of these actions and parameters in the sections of the manual listed at the end of this page. However, almost all of them have a two things in common which we will deal with here, the first of them being the box at the top that says "Applies To:". This is to tell GameMaker: Studio which instances are to be considered as "running" this action and the default is self, which is the instance of the object that has the action in its action list. Most of the time, this is what you want, but in the case of a collision event, you can also have an action that applies to the other instance involved in the collision, and for that you would change "Applies to:" to other (this is only valid for the collision event). Finally you have object which means that the action will be applied to all instances of a particular object that are active in the current room. In this way you could change all obj_red_balls into obj_blue_balls, for example.

The consistent part of most actions is the check-box labeled Relative. When you check this box you are telling GameMaker: Studio that the values you input to the fields of the action are to be relative to the original value rather than being absolute. Here is an image to further explain what this means, and as you will see, checking "relative" can have a big influence on the result of the action!

Information on the individual actions found in each set can be found in the following sections:

  1. Move Actions
  2. Main Actions, Set 1
  3. Main Actions, Set 2
  4. Control Actions
  5. Score Actions
  6. Extra Actions
  7. Draw Actions
  8. Using Variables and Expressions in Actions

Bookmarking Actions

When you add actions to a chosen event, these are numbered down the left hand side of the action list. This is just like when working with code, where each line gets its own line number, and is designed to make debugging and finding your way around complex constructions and action lists. You can "bookmark" a position within the action list too so that with the press of a number key on your keyboard you are taken directly to the action that was previously bookmarked, as long as the object has not been closed (closing the object properties will clear all current bookmarks).

To bookmark an action, simply click on it once to select it with the mouse, then press <CONTROL> + <NUMBER> to add a bookmark at that point (The number is from 1 - 9 and is any one of the number keys at the top of your keyboard). It should be noted that the bookmarks are on a "per object" basis, so each object can have ten bookmarks as long as it is open for editing. From the moment you create a bookmark onwards, you can simply press the number key and you will be taken to the action that the bookmark references, and if you wish to remove a bookmark, then you can simply press <CONTROL> + <NUMBER> again which will clear the number specified.

This functionality can be switched off in the Scripts Preferences, but note that doing so will also switch off line numbering for code boxes and the script editor.

Debugging Actions

Apart from the numbers that you can use for bookmarking the actions used, you can also add break-points to your action list. Break-points are where you can set the game stop running while in debug mode, and the Debug Module will show you details of the current action being run, the variables being used and a whole host of other details. In this way you can stop your actions from being performed and then "step" through them to identify the exact source of the error.

You can add a break-point (or multiple break-points) by selecting the action from the list and either right click and select toggle break-point or by pressing F9 (see image above). The action will now be marked with a red dot, which means that the debug module will stop at that point in your game.

For further information on how to use the debug module, please see the section on Debugging.

Back: Using GameMaker: Studio
Next: Creating Rooms

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Move Actions

The first set of actions consists of those related to the movement of instances.

The following actions can all be found on the first tab that you see when you open an object and has the label "move". These actions are all related in some way to the movement and position of an instance within the room.

Move

Move Fixed
Use this action to start the instance moving in a particular direction. You can indicate the direction using the buttons with the arrows on it. Use the middle button to stop the motion. Also you need to specify the speed of the motion. This speed is given in pixels per step. Preferably don't use negative speeds. You can specify multiple directions. In this case a random choice is made. In this way you can let a monster start moving either left or right.

Move Free
This is the second way to specify a motion. Here you can indicate a precise direction. This is an angle between 0 and 360 degrees. 0 means to the right. The direction is counter-clockwise. So for example 90 indicates an upward direction. If you want an arbitrary direction, you can type random(360). As you will see below the function random gives a random number smaller than the indicated value. As you might have noticed there is a checkbox labeled Relative. If you check this, the new motion is added to the previous one. For example, if the instance is moving upwards and you add some motion to the left, the new motion will be upwards to the left.

Move Towards
This action gives a third way to specify a motion. You indicate a position and a speed and the instance starts moving with the speed towards the position. (It won't stop at the position!) For example, if you want a bullet to fly towards the position of the spaceship you can use as position spaceship.x, spaceship.y. (You will learn more about the use of variables like these below.) If you check the Relative box, you specify the position relative to the current position of the instance. (The speed is not taken relatively!)

Speed Horizontal
The speed of an instance consists of a horizontal part and a vertical part. With this action you can change the horizontal speed. A positive horizontal speed means a motion to the right. A negative one means a motion to the left. The vertical speed will remain the same. Use relative to increase the horizontal speed (or decrease it by providing a negative number).

Speed Vertical
In a similar way, with this action you can change the vertical speed of the instance.

Set Gravity
With this action you can create gravity for this particular object. You specify a direction (angle between 0 and 360 degrees) and a speed, and in each step this amount of speed in the given direction is added to the current motion of the object instance. Normally you need a very small speed increment (like 0.01). Typically you want a downward direction (270 degrees). If you check the Relative box you increase the gravity speed. Note that, contrary to real life, different objects can have different gravity directions.

Reverse Horizontal
With this action you reverse the horizontal motion of the instance. This can for example be used when the object collides with a vertical wall.

Reverse Vertical
With this action you reverse the vertical motion of the instance. This can for example be used when the object collides with a horizontal wall.

Set Friction
Friction slows down the instances when they move. You specify the amount of friction. In each step this amount is subtracted from the speed until the speed becomes 0. Normally you want a very small number here (like 0.01).

Jump

Jump to Position
Using this action you can place the instance in a particular position. You simply specify the x- and y-coordinate, and the instance is placed with its reference point on that position. If you check the Relative box, the position is relative to the current position of the instance. This action is often used to continuously move an instance. In each step we increment the position a bit.

Jump to Start
This action places the instance back at the position where it was created.

Jump to Random
This action moves the instance to a random position in the room. Only positions are chosen where the instance does not intersect any solid instance. You can specify the snapping used. If you specify positive values, the coordinates chosen with be integer multiples of the indicated values. This could for example be used to keep the instance aligned with the cells in your game (if any). You can specify a separate horizontal snapping and vertical snapping.

Align to Grid
With this action you can round the position of the instance to a grid. You can indicate both the horizontal and vertical snapping value (that is, the size of the cells of the grid). This can be very useful to make sure that instances stay on a grid.

Wrap Screen
With this action you can let an instance wrap around, that is, when it leaves on one side of the room it reappears at the other side. This action is normally used in the Outside event. Note that the instance must have a speed for wrapping to work, cause the direction of wrapping is based on the direction of the motion. You can indicate whether to wrap only horizontal, only vertical, or in both directions.

Move to Contact
With this action you can move the instance in a given direction until a contact position with an object is reached. If there already is a collision at the current position the instance is not moved. Otherwise, the instance is placed just before a collision occurs. You can specify the direction but also a maximal distance to move. For example, when the instance is falling you can move a maximal distance down until an object is encountered. You can also indicate whether to consider solid object only or all objects. You typically put this action in the collision event to make sure that the instance stops in contact with the other instance involved in the collision.

Bounce
When you put this action in the collision event with some object, the instance bounces back from this object in a natural way. If you set the parameter precise to false, only horizontal and vertical walls are treated correctly. When you set precise to true also slanted (and even curved) walls are treated correctly. This is though slower. Also you can indicate whether to bounce only against solid objects or against all objects. Please realize that the bounce is not completely accurate because this depends on many properties. But in many situations the effect is good enough.

Paths

Set Path
With this action you can specify that the instance should follow a particular path. You indicate the path that must be followed and the speed in pixels per step. When the speed is positive the instance starts at the beginning of the path. If it is negative it starts at the end. Next you specify the end behavior, that is, what should happen when the end of the path is reached. You can choose to stop the motion, restart from the beginning, restart from the current position (which is the same when the path is closed), or reverse the motion. Finally you can indicate that the path must be seen as absolute, that is, the position will be as indicated in the path (this is useful when you have designed the path at a particular place in the room) or relative, in which case the start point of the path is placed at the current location of the instance (end point when speed is negative). See the chapter on paths for more information.

End Path
Use this action to stop the path for the instance.

Path Position
With this action you can change the current position of the instance in the path. This must be a value between 0 and 1 (0=beginning, 1=end).

Path Speed
With this action you can change the speed of the instance on the path. A negative speed moves the instance backwards along the path. Set it to 0 to temporarily stop the motion along the path.

Steps

Step Towards
With this action you indicate a position and a speed and the instance starts moving with the speed towards the position. There is also the possibility of assigning an object for this instance to check for while moving, and if any instances of the specified object are encountered along the way, the instance with the action will stop moving. If you check the Relative box, you specify that the x and y position is relative to the current position of the instance (this does not affect the speed).

Step Avoid
This action is similar to the "Step Towards" action, above. However, with this the instance will not only move towards the specified x and y position at a given speed, it will also actively try to avoid the specified instances that it encounters on the way. The instances to avoid can be either only the ones flagged as "solid" or all instances in general, and in this way you can create a basic type of Ai for your instance. If you check the Relative box, you specify that the x and y position is relative to the current position of the instance (this does not affect the speed).

Back: Actions
Next: Main Actions - Set 1

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Main Actions - Set 1

This section deals with some of the main actions you will use when working with GameMaker: Studio.

The main action sets are full of the most important actions that you will need when working with GameMaker: Studio, and the first set, marked "main1" in the object properties tab, deals with instances, sprites, sounds and moving from room to room.

Instances

Create Instance
With this action you can create an instance of an object. You specify which object to create and the position for the new instance. If you check the Relative box, the position is relative to the position of the current instance. Creating instances during the game is extremely useful. A space ship can create bullets; a bomb can create an explosion, etc. In many games you will have some controller object that from time to time creates monsters or other objects. For the newly created instance the creation event is executed.

Create Moving
This action works the same as the action above but with two additional fields. You can now also specify the speed and direction of the newly created instance. Note that if you check the Relative box, only the position is relative, not the speed and direction. For example, to make a bullet move in the direction of the person shooting you have to use a little trick. As position use 0,0 and check Relative. As direction we need the current direction of the instance. This can be obtained by typing in the word direction. (This actually is a variable that always indicates the current direction in which the instance is moving.)

Create Random
This action lets you create an instance of one out of four objects. You specify the four objects and the position. An instance of one of these four objects is created at the given position. If you check the Relative box, the position is relative to the position of the current instance. If you need a choice out of less than four objects you can use No Object for some of them. This is for example useful to generate a random enemy at a location.

Change Instance
With this action you can change the current instance into an instance of another object. So for example, you can change an instance of a bomb into an explosion. All settings, such as the motion and the value of variables, will stay the same. You can indicate whether or not to perform the destroy event for the current object and the creation event for the new object.

Destroy Instance
With this action you destroy the current instance. The destroy event for the instance is executed.

Destroy at Position
With this action you destroy all instances whose bounding box contains a given position. This is useful, for example, when you use an exploding bomb. When you check the Relative box the position is taken relative to the position of the current instance.

Sprites

Change Sprite
Use this action to change the sprite for the instance. You indicate which new sprite. You can also indicate with subimage must be shown. Normally you would use 0 for this (the first subimage) unless you want to see a particular subimage. Use -1 if you do not want to change the current subimage shown. Finally you change the speed of the animation of the subimages. If you only want to see a particular subimage, set the speed to 0. If the speed is larger than one subimages will be skipped. If it is smaller than 1 subimages will be shown multiple times. Don't use a negative speed. Changing sprites is an important feature. For example, often you want to change the sprite of a character depending on the direction in which it walks. This can be achieved by making different sprites for each of the (four) directions. Within the keyboard events for the arrow keys you set the direction of motion and the sprite.

Transform Sprite
Use this action to change the size and orientation of the sprite for the instance. Use the scale factors to make it larger or smaller. The angle gives the counter-clockwise orientation of the sprite. For example, to make the sprite oriented in the direction of motion use as a value direction. For example, this is useful for a car. You can also indicate whether the sprite should be mirrored horizontally and/or flipped vertically.

colour Sprite
Normally the sprite is drawn as it is defined. Using this action you can change the colour of the sprite. This colour is blended with the sprite, that is, it is combined with the colours of the sprite. If you want to draw a sprite in different colours you better define the sprite in black and white and use the blend colour to set the actual colour. You can also indicate an alpha transparency. With a value of 1 the sprite is opaque. With a value of 0 it is completely transparent. With a value in between you will partially see the background shine through it. This is great for making explosions.

Sounds

Play Sound
With this action you play one of the sound resources you added to your game. You can select the sound you want to play and choose whether it should play only once (the default) or loop continuously. Multiple sounds can play at once.

Stop Sound
This action stops the indicated sound. If multiple instances of this sound are playing all are stopped.

Check Sound
If the indicated sound is playing the next action is performed. Otherwise it is skipped. You can select Not to indicate that the next action should be performed if the indicated sound is not playing. For example, you can check whether some background music is playing and, if not, start some new background music. Note that this action returns true when the sound actually plays through the speakers. After you call the action to play a sound it does not immediately reach the speakers so the action might still return false for a while. Similar, when the sound is stopped you still hear it for a while (e.g. because of echo) and the action will still return true.

Rooms

Previous Room
Move to the previous room, as defined by the order of the room assets in the resource tree. If you are in the first room of the game and call this function you will get an error.

Next Room
Move to the next room, as defined by the order of the room assets in the resource tree. If you are in the last room of the game and call this function you will get an error.

Restart Room
This will restart the current room.

Different Room
With this action you can go to a particular room, selecting the room to go to from the drop-down list.

Check Previous
This action tests whether the previous room exists. If so, the next action is executed.

Check Next
This action tests whether the next room exists. If so, the next action is executed.

Back: Actions
Next: Main Actions - Set 2

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Main Actions - Set 2

This section deals with some of the main actions you will use when working with GameMaker: Studio.

The main action sets are full of the most important actions that you will need when working with GameMaker: Studio, and the second set, marked "main2" in the object properties tab, deals with timing, showing information, game control and resource control.

Timing

Set Alarm
With this action you can set one of the twelve alarm clocks for the instance. You select the number of steps and the alarm clock. After the indicated number of steps, the instance will receive the corresponding alarm event. You can also increase or decrease the value by checking the Relative box. If you set the alarm clock to a value less than or equal to 0 you switch it off, so the event is not generated.

NOTE: An alarm with no actions in it will not run. However, even with just a comment and no code, the alarm will count down.

Set Time Line
With this action you set the particular time line for an instance of an object. You indicate the time line and the starting position within the time line (0 is the beginning). Also you indicate whether the time line should start immediately and whether it should loop at the end.

Time Line Position
With this action you can change the position in the current time line (either absolute or relative). This can be used to skip certain parts of the time line or to repeat certain parts.

Time Line Speed
With this action you can change the speed of the time line (either absolute or relative). A speed of 1 is the normal speed. When you e.g. set it to 2 the actions will happen twice as fast and when you set it to 0.5 twice as slow. You can also set a negative speed, in which case the time line is played backwards.

Start Time Line
This action starts the time line from its current position (if it is paused or stopped).

Pause Time Line
This action pauses the time line. Use the start action to let it continue.

Stop Time Line
This action stops the time line and sets the position back to 0.

Info

Display Message
With this action you can display a message in a dialog box. You simply type in the message. If you use a # symbol in the message text it will be interpreted as a new line character. (Use \# to get the # symbol itself.) If the message text starts with a quote or double quote symbol, it is interpreted as an expression. See below for more information about expressions.

URL Open
With this action you can tell your game to open a web page. You need to specify the complete URL for this to work.

Game

Restart Game
With this action you restart the game from the beginning.

End Game
With this action you end the game.

NOTE: If the target module for your game is HTML5, this function will end the game but will not close the tab or browser.

WARNING: If the target module for your game is iOS then this action may block your device, and as such it is strongly recommended that you do not use it for that platform except as a dev tool. Your final game will also be rejected if this action is used when submitting to the respective app store.

Save Game
With this action you can save the current game status. You specify the filename for saving (the file is created in the working directory for the game). Later the game can be loaded with the next action. (Please realize that only the basic game status is save. Things that are for example not saved are the current sound that is playing, and advanced aspects like the contents of data structures, particles, etc.)

Load Game
Load the game status from a file. You specify the file name. Make sure the saved game is for the same game and created with the same version of GameMaker. Otherwise an error will occur. (To be precise, the game is loaded at the end of the current step. So some actions after this one are still executed in the current game, not the loaded one!)

Resources

Replace Sprite
This action can be used to replace a sprite from the contents of a file. You indicate the sprite you want to replace, the filename and the number of subimages in the sprite. Many different images file formats are supported, e.g. .png, .jpg, .tif, and .gif. For a gif file the number of subimages is automatically decided based on the number of subimages in the gif file. Other settings for the sprite, e.g. whether it is transparent or not, are not changed. You can use this action to avoid storing all sprites in the program itself. For example, at the beginning of a level you can replace sprites by the actual character sprites you want to use. DON'T change a sprite that is at that moment being used in an instance in the room. This might give unwanted effects with collisions.

Replace Sound
With this action you can replace a sound by the contents of a file (.wav, .mid, or .mp3). You specify the sound and the filename. This avoids having to store all the sounds in the game itself. For example, you can use different pieces of background music and pick the one you want to play. DON'T change a sound while it is playing.

Replace Background
With this action you can replace a background by the contents of a file. Many different images file formats are supported, e.g. .png, .jpg, .tif, and .gif. You specify the background and the filename. This avoids having to store all the backgrounds in the game itself. DON'T change a background that is visible.

Back: Actions
Next: Control Actions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Control Actions

The control actions are actions which ask questions, add code or check conditions.

The third tab in your object properties action list is the "control" tab. This tab has all the main actions that are needed to control the more complex workings of your game like asking questions, checking conditions or adding GML code. These actions are generally used in groups as outlined in the following image: In the above example, the actions check to see if a position is collision free and if it returns true (there is no collision) then a "code block" is opened and in that we have another two actions. These two actions work together, with the first one generating a random 1 in 2 chance of running the second action, which will create an instance of "obj_Enemy" and then the code block is closed. However, should the very first action that checks for a collision return false (there is a collision), then the second code block is started after the "else", and this block bursts some particles and plays a sound. Note that the code blocks are indented as this gives a better overview of the actions, in particular when you use blocks inside blocks for more and more complex programs.

Questions

The following actions are dealing with conditional checks (ie: questions) which are normally to see if something exists, or if there is a collision, or if two values are the same as each other (or greater, or less). For all conditionals there is a check box labeled NOT. If you check this, the result of the question is reversed so that if the result was true it becomes false and if it was false, it becomes true. If you look at the action "Check Empty", you can have it without checking the "NOT" box, which means it is asking "if the place that I put the instance is empty", but if you have "NOT" checked then you are asking "if the place that I put the instance is not empty". This allows you to perform certain actions when a question is not true, or not equal to or even not greater or not less than!

Another thing to watch when dealing with these conditionals is that you can indicate whether they should apply to all instances of a particular object or not. If you choose to apply them to all instances of an object, the result will be true (or whatever) only if it is the same for all instances of that object. For example, you can check all instances of an object to see if the position slightly to the right is collision free.

Check Empty
This question returns true if the current instance, placed at the indicated position does not generate a collision with an object. You can specify the position as either absolute or relative and you can also indicate whether only those instances flagged as solid should be taken into account or all instances. This action is typically used to check whether the instance can move to a particular position.
Note: This action requires that the instance doing the check has a mask index or a sprite with a valid collision mask assigned to it.

Check Collision
This is the opposite of the previous action. It returns true if there is a collision when the current instance is placed at the given position and, again, you can choose to check for only those instances flagged as being solid or all instances.
Note: This action requires that the instance doing the check has a mask index or a sprite with a valid collision mask assigned to it.

Check Object
This question returns true if the instance placed at the indicate position meets an instance of the indicated object. These collisions will be precise if both instances have the mask index or sprite mask defined as being precise otherwise they will be based on whether their bounding box overlaps or not.
Note: This action requires that both the instance doing the check and the instance being checked has a mask index or a sprite with a valid collision mask assigned to it.

Test Instance Count
For his action you specify an object and a number. If the current number of instances of the object is equal to the number the question returns true, otherwise it returns false. You can also change the check to test whether the number of instances is greater than or less than the value you input. This type of check is typically used to check whether all instances of a particular type are gone, and so influence things like score, health or the game state.

Test Chance
This action takes the result of a "one in X" chance, where "X" is the number you input to test. For example, if you set the number to 20, then it's as if you have rolled a 20 sided dice and only if the side numbered 1 comes up will you get a "true" result, and the action will perform the next one below it. The larger the number of "sides" of the dice, the smaller the chance of 1 being true and the next action being carried out, and the number being checked doesn't actually have to be an integer as you could check for a 1 in 2.5 chance, or a 1 in 35.75 chance etc... However, fractions of 1 will not work as you can't have a 1 in 0.5 chance of something happening! This has many, many uses when making games as it can add a controlled, yet random chance of something happening, for example in each step you could have a bomb check to see if it should explode, or an enemy check to see if it should change direction.

Check Question
Here you can specify a question for the player to answer either yes or no to, with the subsequent actions running (or block of actions) if the result is yes (true). The question is shown in an independent pop-up dialogue.

Test Expression
This is the most general question action whereby you can enter an arbitrary expression and evaluate it. If the expression evaluates to true (that is, a number larger or equal to 0.5) then the next action (or block of actions) is performed. For more information on expressions see this section of the manual - Using Expressions and Variables in Actions.

Check Mouse
This action will return true if the indicated mouse button is pressed. For example, in the step event of an object you can check whether a mouse button is pressed and, if so, move the instance to that position (you would use the jump to a point action with values mouse_x and mouse_y).

Check Grid
Returns true if the position of the instance lies on an imaginary grid, made up of spaces defined by you in action when you add values to the vertical and horizontal spacing parameters. A common use for this action is to do a check and only let the player move if his character is aligned to the grid (think how a game like PacMan works).

Other

Start Block
This indicates the start of a block of actions. Using the start and end block markers you are able to group a series of actions together so that if a conditional results as true, then all the actions are performed and not just the one directly below the question. the following image illustrates this: End Block
Indicates the end of a block of actions. See the above image and "Start Block" action for more information.

Else
When you ask a question you may often wish to have a reply for if the answer is true or false, and so GameMaker: Studio provides you with the "else" action so you can re-create this with actions. Basically, you have your conditional, then the block of actions if it is true, then "else", then the block of actions for if it is false. See the image at the top of the page for an example of how this looks.

Repeat
Another useful action is the "Repeat" action. With this action, all you do is specify the number of times you wish the next action (or block of actions) to repeat and it will be done without you having to copy and paste the actions yourself many times over. This can be used for many things, for example spawning number of pickup objects, or adding a value many times onto another or any manner of things.

Exit Event
When this action is encountered no further actions in this event are executed.
Call Parent Event
This action is only useful when the object has a parent object as it calls the corresponding event in the parent object. When working with parents, any event that the parent object shares with the child object is over-ridden by the child, so you can call this action to force the child object to run the parent objects event as well as any actions it has for the event.

Code

If you want more control over what is happening in the game you can use code as GameMaker: Studio has its own language called GML (The GameMaker Language). This can give far more flexibility than using the standard DnD actions as it covers far more things , but code and actions are not mutually exclusive and can be mixed in events to get the behaviours you require.

Execute Code
When you add this action, a window will open showing the GM Script Editor where you can write the code that you wish the event to execute. This code can be for anything from a single simple function to a full blown AI, however it is recommended that you use scripts (see Advanced Use: Scripts) for longer pieces of code as it makes structuring your game far easier.

Execute Script
With this action you can execute a script that you have previously added to the game resources, passing a maximum of five arguments to it. For more information on scripts you can go to this section of the manual - Advanced Use: Scripts.

Comment
Use this action to add a line of comment to the action list. A comment is usually a short sentence to remind you of what a particular set of actions is meant to do and a comment in itself does not actually affect the normal running of GameMaker: Studio. However, even though it does nothing, it is still recognised as an action and can be (for example) placed in a collision event so that it will trigger that collision even when no code is present.

Variables

Variables are an essential part of game making. They are the base on which almost all a game is built as you need them to hold the values that govern the behaviour of your objects, for example, score, lives and health are all internal variables that GameMaker: Studio creates for you (see Variables And Variable Scope). However, in-built variables are certainly not enough to build your game around, and so you will need to use the following actions (or code) to set, test and change variables as your game progresses.

Set Variable
This action sets a variable to a value. If that variable does not exists then it creates it and gives it the specified value. This action can also change the many in-built variables that GameMaker: Studio has. To use it you specify the name of the variable and the new value it should have. Bear in mind that when you check the Relative box, the value is added to the current value of the variable, but please note that this can only be done if the variable has already been created and has had a value assigned to it!

Test Variable
With this action you can check what the value of a particular variable is. If the value of the variable is equal to the number you have provided then the question returns true, otherwise it returns false. You can also indicate that the check should be whether the value is smaller than or greater than the value specified and you can even use this action also to compare two expressions or variables to see if they are the same as, greater than or equal to each other.

Draw Variable
With this action you can draw the value of a variable at a particular position on the screen. Note that this can only be used in the draw event of an object.

Back: Actions
Next: Score Actions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Score Actions

The score actions are actions which deal with things related to score, lives and health.

In most games there is a score of some type and the player will usually have either health or lives (or both). Now, you can use the variable and question actions to set this up yourself, but GameMaker: Studio comes with a series of in-built variables that deal with these things, and these variables have their corresponding actions, which are detailed in this section.

Score

Set Score
With this action you can set the score to a value of your choice. Note that "score" is a global variable (see this section for more information: Variables And Variable Scope) and as such, this action can be placed in any object, meaning that (for example) you could have a destroy event for an enemy object that sets the score to 10 relative. Why relative? Well, as outlined in the introduction to actions, this will add 10 to the current score whereas if you do not check the relative flag it will just set the score to 10! You would normally un-check the relative flag and place this action at the start of a game to set the score to 0, for instance.

Test Score
This action will check the value of the score against the value you input and return true if it meets the condition. The condition can be either equal to, greater than or less than and in this way you can have specific behaviours for an instance depending on the current value of the score variable.

Draw Score
You can use this action to draw the score variable anywhere on the screen, just provide the position and the caption to be shown beside the value. Please note that this action will only be valid when used in the Draw Event.

Clear Highscore
With this action you are telling GameMaker: Studio to clear the high score table. Warning! This cannot be undone!

Lives

Set Lives
Another global variable included with GameMaker: Studio is the one for lives (for more information on global variables see: Variables And Variable Scope). Normally you would set it to some value like 3 at the beginning of the game and then decrease or increase the number depending on what happens as the player progresses. Don't forget to check the Relative box if you want to add or subtract from the number of lives. At the moment the number of lives becomes 0 (or less than 0) a "no more lives" event is generated.

Test Lives
With this question action you can check whether the number of lives has reached a particular value. You indicate the value and whether the number of lives should be equal to, be smaller than, or be larger than the value. This can be used, for example, to limit the lives that a player can pickup while playing a game and so keep them from going above a maximum value.

Draw Lives
You can use this action to draw the number of lives directly to the screen. You provide the position and the caption that must be placed in front of the number of lives, and then number of lives is drawn in the current font. Please note that this action will only be valid when used in the Draw Event.

Draw Life Images
Many games prefer to represent lives with some sort of graphic rather than straight text, and so GameMaker: Studio provides this action so you can get the same effect. You specify the position and the sprite image to be used for each life and at the indicated position the number of lives is drawn as images. Please note that this action will only be valid when used in the Draw Event.

Health

Set Health
GameMaker includes a built-in health global variable (for more information on global variables see: Variables And Variable Scope), and like the previous actions for score and lives, you can use this action to set and change the health value. To set the health to a specific value, leave the "relative" flag un-checked, but if you wish to add or subtract from the health value, then make sure that it is checked. Please note that this variable is clamped to be within the range of 0 to 100 (where 0 is no health and 100 is full health) and that when the health becomes less than or equal to 0 an "out of health" event is generated.

Test Health
With this question action you can check whether the health has reached a particular value. You indicate the value and whether the health should be equal to, less than or greater than the value. One use for this is that when the player health gets below a certain amount you could make some object flash to draw their attention to the fact.

Draw Health
We have all seen a players health drawn in the game in the form of a bar that increases or decreases as the status of the player changes, well, this action permits you to draw the health variable in this way too. When the health is at 100 the full bar is drawn and when it is at 0 the bar is empty, and you can indicate the position and size of the health bar as well as the colour of the bar and its background.

Score Caption
Normally in the window caption the name of the room and the score is displayed, but with this action you can change this to show the score, lives, health and what the caption for each of these must be, or not, as you wish. This functionality is only valid for Windows, Ubuntu (Linux) and MacOS targets.

Back: Actions
Next: Extra Actions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Extra Actions

This tab contains a few extra actions to help create effects for your game.

The extras tab is dedicated mainly to the creation and use of Particles in your game, but there is one other action at the bottom which we will describe first before going into a bit more depth about particles.

Other Actions

Set Mouse Cursor
This function allows you to set the cursor for the game to a sprite that you can choose from the resource tree. You are also given the option to hide the standard mouse cursor as well. This functionality is only valid for Windows, Linux (Ubuntu), MacOS and HTML5 targets.

Particles

Now, above that one we have a whole host of actions related to creating particle systems, types and emitters... but, what is a particle? Basically, a particle is a graphics resource which is created with a base set of properties set by you beforehand. Unlike objects, backgrounds and tiles, once a particle has been created you no longer have any control over it and it will continue to exists until it reaches the end of its "life", which is defined by you using these actions. You can also define its colour, speed, direction and if it will be affected by gravity or not, as well as how many of them you want to be created and how often. As particles are purely graphical, they are also very fast to process and you can have lots of them on screen at any one time with no noticeable lag, making them ideal for many special effects, like smoke trails, blood splatters and debris. Below you can find a list of all the actions available to create a particle system and define types and emitters.

Particle System Create
Before you can create any particles, you have to create the "system" that they are created in. This action will create that system and ask you for the depth that any particles you create will be drawn at. As with objects and tiles, this depth can be a positive or a negative integer, with a high negative value placing it "above" other things and a high positive value placing it "below".

Particle System Destroy
Particle systems take up memory space and if they are not managed properly, they can slow down and even crash your game. To prevent this you must destroy them when not in use with this action. Normally it would go in the destroy event of the object that has the Particle System Create action, or in the room end event if there is nothing going to destroy it sooner (or even both events).

Particle System Clear
This action will clear a system of all particles in it making all those that are visible on the screen disappear. This does not destroy the particle system, nor the particles and emitters, it only clears the screen until more particles are emitted.

Particle Type Create
Before you can see any particles in a system, they have to be created and defined, first with this action, and then (if necessary) with the other actions listed below. In this action you are able to specify the name of the particle (type0 - type15), and choose whether to use your own custom sprite or one of the included particles which are shown in the image below: You then have the options "min size" and "max size" which enable you to set a minimum and a maximum initial size for your particle. All this means is that your particles will be created a random size within these limits that you set and if you want them all to be the same size then set both parameters to the same value. Finally there is the "size increment" option which enables you to specify whether you wish a particle to grow (positive number) or shrink (negative number) after it has been created on the screen. Normally this value is kept pretty low, 0.1 or -0.05 for example.

Particle colour
With this action you can set the colours of the particles as well as the alpha (transparency, with 1 being fully opaque and 0 being fully transparent) and how the colours are to be used, either fading over the life of the particle from colour1 to colour2 (changing) or having each particle choose a permanent colour from those specified (mixed). Note that "alpha" has a start and end value so you can make particles fade out or in over their lifetime on the screen.

Particle Life
The lifetime of a particle is the time it takes, in steps, from the moment it is created to the moment it disappears from the screen. With this action you specify the particle and a minimum and maximum lifetime or your particles, with each individual particle having a life somewhere within that range. If you wish them all to have the same lifetime then set both values to be the same.

Particle Speed
This action not only sets the speed of the particle but also its direction and whether or not it is affected by friction (causing it to slowdown over time). As with all other particle actions, you must first select a particle type for the action to work on and then set the maximum and minimum speeds for the particles to be created with. Finally you set a directional range too, based on the standard GameMaker: Studio angles system, with 0 being right, 90 up, 180 left and 270 down and you can also set the friction for your particle (normally a small value like 0.05).

Particle Gravity
Particles can be affected by gravity too, so with this action you can select the particle type it has to affect and also the amount and the direction that it should "pull". The direction is based on the standard GameMaker: Studio angles system, with 0 being right, 90 up, 180 left and 270 down.

Particle Secondary
This action allows you to tell a particle to emit other particles at different times. The options are outlined below:

  • type id: The type name of the initial particle that will have this action.
  • step type: This is the type name of the particle you wish to emit each step if the option below is greater than 0. Normally this is a different particle to that specified in the "type id" above.
  • step count: This is the number of particles to emit every step of the lifetime of the initial particle.
  • death type: This is the type name of the particle you wish to emit when the initial particle defined in the "type id" parameter reaches the end of its lifetime. This is only effective if the option below is greater than 0, and normally this is a different particle to that specified in the "type id".
  • death count: This is the number of particles (whose type is defined by the above parameter) that are to be emitted when the initial particle reaches the end of its lifetime.

Create Emitter
Once you have created your particle you will want to see it in the room, and when using actions the only way to do that is to use an emitter. An emitter is just another part of the particle system whose sole purpose is to emit particles based on the parameters that you have defined for it. These parameters are the name (id) of the emitter, the shape of the emitter (an ellipse or a rectangle) and the coordinates within the room of the emitter. The coordinates are defined by four parameters, and xmin and an xmax, and a ymin and a ymax, so for example, if you want to emit particles over your whole room you would have the xmin equal 0, the xmax equal the room width and the ymin equal 0 and the ymax equal the room height.

Destroy Emitter
Like other things in a particle system, emitters take up memory and when one is no longer needed it should be destroyed using this action.

Burst From Emitter
Particles can be either burst or streamed from an emitter, which means that they are all created at once (burst) or they are created over a set number of steps (streamed). This action controls the bursting of particles and should be placed in any event where you need to create a group of particles at once (like in a mouse button event, for example). You choose the emitter to use, the particle type to burst and the number of those particles that should be emitted. Note too that you can use a negative number for the amount of particles to burst, which means that, for example, if you have a value of -10 then there is a one in ten chance that a particle will be emitted.

Stream From Emitter
Particles can be either burst or streamed from an emitter, which means that they are all created at once (burst) or they are created over a set number of steps (streamed). This action controls the streaming of particles and should only normally be used once in any instance. You choose the emitter to use, the particle type to stream and the number of those particles that should be emitted every step of the game while the emitter exists. Note too that you can use a negative number for the amount of particles to stream, which means that, for example, if you have a value of -10 then there is a one in ten chance that a particle will be emitted each step.

Back: Actions
Next: Draw Actions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Draw Actions

The draw actions are actions which draw things to the screen.

The following actions are all related to the act of drawing things to the screen. As such, most of them can only be used in the draw event of an object, and even then they will not be performed if the object has been flagged as invisible through code or through the object properties "visible" setting being un-checked.

Drawing

Draw Self
When you add any type of action or code to the draw event of an object, you are telling GameMaker: Studio that you are taking over the draw event and that you will tell it what to draw from now on. This means that any assigned sprite will no longer be drawn unless you explicitly say so, which when you would use this action. This simply draws the assigned sprite for the object with any transforms that may have been set in previous events (like scaling, blending or changes in alpha) at the current sub-image.

Draw Sprite
This will draw a sprite somewhere in the room. You specify the sprite, the position (either absolute or relative to the current instance position) and the subimage of the sprite (The subimages are numbered from 0 upwards). If you have an animated sprite and you want it to draw the subimages as normal, use number -1. This action will not draw the sprite transformed, even if you have changed the image blend or scale.

Draw Background
This will draw a background resource somewhere within the room. You indicate the background image, the position (absolute or relative) and whether the image should be tiled all over the room or not.

Draw Text
With this action you can draw text anywhere in the room. You specify the text and the position to draw, but please note that there are certain conventions to follow when drawing text:

  • A # symbol in the text is interpreted as going to a new line, so typing this - Hello world!#Nice day - would draw the text over two lines.
  • If you need to draw the # symbol itself, use \# ie - this is foobar \#3.
  • You can mix text and expressions to draw values of variables. The text you want to draw must be in quotes (either ' or ") and the variable to draw must use the string() function. For example, if you wish to draw the value of the in-built object variable direction, you would have this - 'Current Direction = ' + string(direction)

Draw Scaled Text
This action is similar to the previous action but this time you can also specify a horizontal and vertical scaling factor to change the size of the text and you can also specify an angle to rotate it.

Draw Rectangle
You specify the coordinates of the two opposite corners of the rectangle, either absolute or relative to the current instance position, and you can tell GameMaker: Studio to draw either a solid filled rectangle, or just the outline. The colour of the rectangle depends on the currently selected draw colour (see the Set colour action below).

Horizontal Gradient
This action also draws a rectangle but this time using a colour gradient that changes from left to right. You can specify the size and position of the rectangle, either absolute or relative to the current instance position, and the two colours to use in the gradient.

Vertical Gradient
This action also draws a rectangle but this time using a colour gradient that changes from top to bottom. You can specify the size and position of the rectangle, either absolute or relative to the current instance position, and the two colours to use in the gradient.

Draw Ellipse
With this action you can draw an ellipse. You specify the coordinates of the two opposite corners of the rectangle that would border the ellipse, either absolute or relative to the current instance position, and you can tell GameMaker: Studio to draw either a solid filled ellipse, or just the outline. The colour of the ellipse depends on the currently selected draw colour (see the Set colour action below).

Gradient Ellipse
As above, you draw an ellipse, but this time you can select a gradient of two colours to fill it from the center out to the border.

Draw Line
This simply draws a line between the two points that you specify in the action, either absolute or relative to the current instance position. The colour of the line depends on the currently selected draw colour (see the Set colour action below).

Draw Arrow
With this action you can draw a simple arrow. Much like the Draw Line action, you specify the coordinates of the two endpoints of the arrow, either absolute or relative to the current instance position, and the size of the arrow tip. The size is in pixels and is measured backwards from the end of the line, so that the point of the arrow adds nothing to the overall length. The colour of the line depends on the currently selected draw colour (see the Set colour action below).

Settings

The following actions do not need to be called from the draw event, and are usually only called once in a specific event (like the create event or a mouse event) due to the fact that they only need to set their action once in a game.

Set colour
Lets you set the colour used for drawing shapes, lines, and text. This does not influence in any way sprites and backgrounds are drawn.

Set Font
You can set the font that is from this moment on used for drawing text, but this must be one of the font resources you have defined previously in the resource tree. If you choose No Font a default 12 point Arial font is used.

Set Full Screen
With this action you can change the screen mode from windowed to fullscreen and back. You can indicate whether to toggle the mode or whether to go to windowed or fullscreen mode, making it an ideal action for use in any kind of options menu for your game.

Other

The following actions do not need to be called from the draw event.

Take Snapshot
With this action you can take a snapshot image of the game while it is being played and store it in a .png file, the name of which you specify in the action.

Create Effect
With this action you can create all sorts of basic effects in a very simple way. You specify the type of effect, e.g. an explosion or smoke, its position, its size and its colour and whether it should be shown below the objects (at a depth of 100000) or on top of them (at a depth of -100000). The rest is done automatically for you by the in-built GameMaker: Studio particle system (for more information on particles see - Extra Actions and Reference: Particles). Note that for rain and snow the position is irrelevant as it always falls down from the top of the screen and that to get continuous rain you should create it in each step.

Back: Actions
Next: Using Expressions And Variables In Actions


Using Expressions And Variables In Actions

This section covers how to use expressions and the in-built instance variables in actions.

When using many of the actions in GameMaker: Studio you are expected to input a value as one of the parameters, but sometimes that is not enough and you may find it necessary to input a formula or an expression to get the required result from the action. this is perfectly valid and GameMaker: Studio permits the use of any of the in-built instance variables, constants or global variables as well as the use of your own (previously defined) variables and even mathematical formula! The image below shows how this can work: As mentioned before, GameMaker: Studio also has a great number of in-built variables that are unique to each and every instance created in a room. These instance variables are created for you automatically when you create an object and can be used, set and changed just as you would any other variable. Below is a list of all these variables:

  1. x: the x-coordinate of the instance in the room. Changing this will position the instance elsewhere in the room along the x-axis.

  2. y: the y-coordinate of the instance in the room. Changing this will position the instance elsewhere in the room along the y-axis.

  3. hspeed: the horizontal speed (in pixels per step) at which the instance is moving. A positive value means movement to the right and a negative value means movement to the left.

  4. vspeed: the vertical speed (in pixels per step) at which the instance is moving. A positive value means movement to the bottom and a negative value means movement to the top.

  5. direction: the current direction of motion in degrees (0-360), where 0° is right, 90° is up, 180° is left and 270° is down.

  6. speed: the current speed of motion in the current direction. For a "forward" motion (ie: facing the direction) this is a positive value, and for a "backwards" motion it should be negative.

  7. visible: this is the flag that sets an object as being visible (the draw event is performed) or invisible (the draw event is skipped).

  8. image_index: this variable indicates which subimage in the current sprite is currently shown. When the animation speed (image_speed, see below) is set to a value greater than 0, this variable changes each step to reflect the sub-image being shown of the animation .

  9. image_speed this variable indicates the speed with which the subimages are shown, with the default value being 1 (meaning 1 frame per step). If you make this value larger than 1 some subimages are skipped to make the animation faster, and conversely, if you make it lower than 1, then some sub-images are repeated over various steps to make it animate slower.

  10. id: the unique identifier (an integer) of the instance. This value is assigned to the instance when it is created and cannot be changed.

  11. object_index: this is the index (not the name) of the object that the instance has been created from. This value is assigned to the instance when it is created and cannot be changed.

Further information on in-built instance variables can be found in the following sections:

  1. Reference: Movement Variables
  2. Reference: Instance Variables
  3. Reference: Physics Variables

Apart from the in-built instance variables, we also have a number of global variables that can be used in actions too (see Variables And Variable Scope for more information on global variables). Here are a few of those available:

  1. score: the current value of the score
  2. lives: the current number of lives
  3. health: the current health (0-100)
  4. mouse_x: x-position of the mouse
  5. mouse_y: y-position of the mouse

Back: Actions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Drop Down Menus

This section lists the various menus that are in the GUI.

At the very top of the GUI you will find the drop down menus. As there are a number of them and each has its own selection of options, you can find out more about them from the pages listed below:

  1. The File Menu
  2. The Edit Menu
  3. The Window Menu
  4. The Resources Menu
  5. The Scripts Menu
  6. The Run Menu
  7. The Help Menu

Back: The Graphical User Interface (GUI)


The Edit Menu

Here you can find out all about the various options available to you from the drop down edit menu.

The edit menu contains a number of commands that relate to the resource currently selected from the resource tree on the left of the main screen (object, sprite, sound, etc.). Depending on the type of resource selected, some of the commands may not be visible.

  • Insert...: inserts a new resource of the type currently selected. A form will then open in which you can change the properties of that resource (more on this in the following sections of the manual)

  • Duplicate: This makes a copy of the currently selected resource in the resource tree. The new resource is given a default name and a form is opened in which you can change the properties of that resource.

  • Insert Group: Inserts a sub-folder within the resource tree. This is useful for grouping objects and things of the same type together for easy referencing.

  • Delete: Deletes the currently selected resource (or group of resources) from the resource tree. Be very careful with this as it cannot be undone. You will be warned before the operation is completed and given the option to cancel or go ahead. It should also be noted that depending on the preferences you have selected for GameMaker: Studio these resources may also be removed from the hard-drive.

  • Rename: Gives the resource a new name. This can also be done in the property form for the resource, by right-clicking the resource with the mouse and selecting "rename" from the pop-up menu, or by simply clicking the resource again and typing in the new name.

  • Properties: All resources have a properties form that can be brought up by selecting this command. Note that all the property forms appear within the main window and you can have open and edit many of them at the same time. You can also call up the properties by double clicking on the resource.

  • Find Resource: This searches through the resource tree looking for the name of the resource that you request. This is very handy when you have a large project with many resources in grouped sub-folders.

  • Bookmarks: From here you can access any of the bookmarks that you may have set in your code and scripts (you can bookmark a script or code action using <Shift> + <Control> + <NUM> , where <NUM> is a number from 0 to 9 on the keyboard).

  • Expand Resource Tree: Each section (and sub-folder within) of the resource tree can be collapsed when not in use to allow more space on screen for other resources. Click on this to expand them again.

  • Collapse Resource Tree: . Similar to the above, this command collapses a resource tree section or sub-folder.

  • Show Object Information: It is sometimes necessary to see all the details of an object and its properties in one place, and this can be achieved by selecting this command. It can be a very useful feature for debugging and getting an overview of any object.

  • Transparent Background Settings: Here you can indicate how the transparent area of the sprite and background resources should be shown in the sprite editor. You can either use a customizable block pattern, or a solid fill colour which you can change by clicking on the colour selector box.

Note that many of these commands can also be given by right-clicking on a resource (or a resource group), and then using the appropriate action from the pop-up menu.

Back: The Drop Down Menus
Next: The Windows Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The File Menu

Here you can find out all about the various options available to you from the drop down file menu.

In the file menu you can find the commands you'd expect for loading and saving files, but there are also a few special ones:

  • New: Choose this command to start creating a new game from scratch. If the current game has changed you are asked whether you want to save it before proceeding. There is also a tool-bar button for this command, but both will methods will take you back to the "Welcome" screen where you can create a new project.

  • Open: Opens a GameMaker: Studio game file with the extension *.gmx.

  • Import: Imports a GameMaker: Studio *.gmz compressed file (which will then be saved as a standard *.gmx) game file. You can also select to import Legacy GameMaker files with the extensions gm81, gmk, gm6 or gb1...n files from here. These might not work correctly in this new version due to changes in GameMaker over the years, and as such it is recommended that you check out the YoYo Knowledge Base to see what's changed between versions before deciding to import legacy files. There is also a tool-bar button for this command and you can even open a game by dragging the file into the actual GameMaker: Studio window.

  • Recent Files: Use this sub-menu to open game files you have recently opened or modified.

  • Save: Saves the game project file under its current name with the *.gmx extension. If no name was specified before, you are asked for a new name. You can only use this command when the file has been changed and, again, there is a tool-bar button for this. Saving with this command will only save those things that have been changed since the file was opened.

  • Save As: Saves the current game project file under a different name. You are asked for a new name before saving.

  • Save All: Saves the game project file under its current name with the *.gmx extension. If no name was specified before, you are asked for a new name. Unlike the regular "Save" command, this will export and save all the game information, whether it has changed or not.

  • Export Project: Exports your project as a compressed GameMaker file with the format *.gmz. These project files contain all the information relevant to your current project (including resources, extensions, game information etc...) which can then be imported again into GameMaker: Studio as a complete project in the future. This is very useful for transferring a project over a network as well as for storing shelved projects or backup copies of a current project.

  • Create Application: Once your game is ready you will probably want to give it to others to play! By using this command you create a stand-alone version of your game. The actual files produced will depend on the target module chosen in the drop down menu of the GameMaker: Studio GUI.

  • Preferences: This will open the GameMaker: Studio preferences where you can adjust how the program looks as well as different behaviours when dealing with resources etc... For further information on this please see GameMaker: Studio Preferences

  • Exit: We know that making games is fun and addictive, but you need to eat and sleep sometimes! So press this to exit GameMaker: Studio. If you changed the current game project then you will be asked whether you want to save it before the program closes.

Back: The Drop Down Menus
Next: The Edit Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Help Menu

Here you can find out all about the various options available to you from the drop down help menu.

  • Open The Manual: Use this command to bring up this help file.

  • Key Bindings: This option opens the Key Binding Editor where you can redefine the GameMaker: Studio keyboard shortcuts. More information on this can be found below.

  • News: Here you can see the most recent news about the GameMaker range of products and the company YoYo Games.

  • Website: Connects you to the YoYo Games official website.

  • Forum: This will connect you to the GameMaker Community (GMC) forum, where you can find help with any problem as well as tutorials, resources and much more all related to GameMaker: Studio.

  • Knowledge Base: This will take you to the GameMaker Knowledge Base where you can find plenty of official information about the use of GameMaker products.

  • Required SDKs: This will take you to the page on the GameMaker Knowledge Base where you can find updated SDK information for each of the available target platforms.

  • Release Notes: Opens a tab in your browser to show the current build and accompanying release notes for your version of GameMaker: Studio.

  • Helpdesk: This link will take you to the YoYo Games Helpdesk and Knowledge Base where you can find additional tutorials and FAQs, as well as ask questions about the product.

  • Report A bug: While we make every effort to make sure GameMaker: Studio is bug free, in a program as large and complicated as this it is a nearly impossible task. So, if you find something you think is a bug, then please use this link and report it to us and we'll do our very best to fix it.

  • Open GameMaker in Explorer: Use this command to open the folder location of GameMaker: Studio in Windows Explorer.

  • Open Project in Explorer: Use this command to open the folder location of your current project in Windows Explorer.

  • Open Project Data in Explorer: Use this command to open the local appdata folder location that your current project is using.

  • Update Licence: if you have bought a new licence to upgrade GameMaker: Studio to a new version or to add a new target module, then you should select this option to activate it. Note that if you bought GameMaker: Studio through Steam this option will not be present.

  • About GameMaker: Studio: Gives information about this version of GameMaker: Studio, including the product key and the user it's registered to.

Note that if you have any Sony console license or the Xbox One licence as part of your GameMaker: Studio licence, then you will also see an option here to install the appropriate SDK and module resources.

Key Bindings

The help Key Binding Editor permits you to re-assign the default GameMaker: Studio IDE keyboard shortcuts to those that you choose. When you open the editor you will be presented with the following window: Along the top of the window are the tabs for each of the editors available, as well as a "General" tab for the main IDE keyboard shortcuts. Each tab is split into three parts:

  • Shortcut: The name of the command to create a keyboard shortcut for.
  • Key: The key (or key combination) to be assigned to the shortcut command. Note! Not all IDE commands permit a keyboard shortcut.
  • Anchor: The Anchor letter in the IDE name for the keyboard shortcut. This is the letter that will be underlined in the IDE, meaning that you can also use the <ALT> key plus the underlined character key to call the command.

To change a Key, simply right-click on it and select the key, or key combination, that you require from the lists presented and your shortcut will be created. Note that you can also create your own custom bindings if those that are presented by default do not match what you require by selecting the Custom Keys option. This will open a window another window which will detect and show the keys that you are currently pressing: You need to hold the key combination for 3 seconds and then it will be added to the Key Bindings for that command.

Back: The Drop Down Menus
Back: The File Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Resources Menu

Here you can find out all about the various options available to you from the drop down resource menu.

In this menu, you can create a new resource for each of the different types as well as change the global game settings, add Macros, and select files to include in the final game (more information on each of these items can be found further on in the manual). For each of these commands there is also a button on the tool-bar and a keyboard shortcut.

  • Create <Resource>: Creates a new resource of the type selected. A form will then open in which you can change the properties of that resource (more on each of the resources in the following sections of the manual)

  • Change Global Game Settings: This opens the Global Game Settings window where you can change many things relating to how your game behaves. More information can be found here.

  • Define Macros: This will open a further window where you can define your own constants and macros for use within your projects. More information can be found here.

Note that many of these commands can also be given by right-clicking on a resource (or a resource group), and then using the appropriate action from the pop-up menu.

Back: The Drop Down Menus
Next: The Scripts Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Run Menu

Here you can find out all about the various options available to you from the drop down run menu.

This menu has options that relate to testing your games and to setting up configurations (note that each of these items has a corresponding button on the GUI Toolbar):

  • Run Normally: This will cause the game to run as if it was finished and installed on the target platform for play testing.

  • Run in Debug Mode: This option runs the game in debug mode. For a windows game, this opens another window (apart from the game window) with various debug options to help you debug every aspect of your game. For more information on debugging in GameMaker: Studio, please see the section Advanced Use - Debugging.

  • Clean Build: This is the same as clicking the green "broom" icon in the main IDE toolbar, and will clear the asset compiler cache. This is important as it prevents any "stale" assets from corrupting your game. It is not necessary to clear the cache every build, but should you be getting any odd errors or corrupted sprites, it should be done, and it should always be done before building any final packages for deployment..

The following two options are limited to the Professional Version of GameMaker: Studio (and above) and will not be present on other versions:

  • Configuration Manager: Selecting this will open the Configurations Manager.

  • Configurations: Placing the mouse over this option will open up a sub-menu with a list of all the currently available configurations from which you can select one to use (this shows the same options as the configurations tab in the main GUI.

Back: The Drop Down Menus
Next: The Help Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Scripts Menu

Here you can find out all about the various options available to you from the drop down script menu.

This menu has a number of options that relate to the internal scripting functions as well as the script resources that you can create:

  • Show Built-in Variables: This will bring up a list of all the global variables as well as a list of all the instance variables common to all objects.

  • Show Built-in Functions: This will show a complete list of all the functions available in the GameMaker Language (GML).

  • Show Extension Functions: If you have installed any extensions then clicking this will bring up a combined list of all the functions and constants used by them.

  • Show Constants: This will bring up a list that shows all the constants that exist to be used in GameMaker: Studio.

  • Show Resource Names: This will bring up a list that shows all the current resource names used in the project.

  • Search In Scripts: This brings up a search form that can be used to search through various resources to find a specific string or function and it includes a number of options to make the search as narrow or as broad as necessary. This is an extremely powerful tool for changing things within a game or for debugging when there is a problem with a variable name or a function. The following window will pop up and allow you to narrow or widen the search as needed:
  • Check Resource Names: To check and make sure that no name conflicts exist you can choose this command. GameMaker: Studio will not allow you to name two resources with the same name, but if you merge files or import an older format project, then this may happen. If it does, you may get odd behaviours and even errors, which can be resolved by using this.

  • Check All Scripts: This will run a check through all objects, instances and rooms that have GML in them for errors and display them in a list. You can then click on any errors that are displayed to be taken to the properties window of the relevant resource to fix it.

  • Clear All Breakpoints: Clears all the breakpoints from your project.

  • Clear All Bookmarks: Clears all the bookmarks from your project.

Back: The Drop Down Menus
Next: The Run Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Window Menu

Here you can find out all about the various options available to you from the drop down window menu.

In this menu you find some typical commands to manage the different properties of the actual windows in the main GameMaker: Studio form:

  • Cascade - Cascade all the windows such that each of them is partially visible.

  • Show Compile Form - This will show the compile form in the IDE if you have previously closed it.

  • Close All - Close all the property windows, asking the user whether or not to save any changes made.

  • Properties - Open the properties window for the selected resource (This option may or may not be visible depending on the current resource selected).

Back: The Drop Down Menus
Next: The Resources Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Events

GameMaker: Studio uses what is called an event driven approach, and this section of the manual outlines how that works.

So, what are events? Basically, these are discreet moments in the game loop where things are made to happen based on what you have programmed for them. You see GameMaker: Studio works with cycles of these events - from the moment a room is started to the moment it is finished there is a game loop running where every step (a step is a moment in game time, governed by the room speed setting) a series of events are run, and you can choose to place code or DnD actions in your instances that respond to these events. Let's look at a typical object setup with events and actions:

As you can see in our example object there are a number of events listed that it should respond to, but initially when you create an object this list is empty and you must decide which events you need and what instances of that object should do when those events are triggered. To add events into the object, you press the Add Event button found at the bottom of the events list which will bring up the following window:

That is the list of all the basic events which an object can respond to, although some of those events also have sub events to further define behaviours. For example, if you add a Key Press event you will then get a further window popping up with the sub events that allow you to select which key the object should respond to. Once you have selected your event, you can then add your DnD actions or code into the Actions section on the right of the event list, which means that you are telling GameMaker: Studio that when this event is triggered, these actions should be performed. here is an example image to illustrate this:

You can change the order of the actions in the list by pressing and holding the left mouse button and then dragging to move the selected DnD action icon. Note that if you hold the <Alt> key while dragging, you can make a copy of the action. You can even use drag-and-drop between action lists for different objects, either by having them both open and literally dragging the DnD action icons between them, or you can click with the right mouse button on an action which will open a menu where you can edit, cut, copy, paste and even delete actions (deleting can also be done by using the <Del> key). You can select multiple actions for cutting, copying, or deleting by holding the <Shift> key or <Ctrl> key and clicking on a series of action icons, and pressing <Ctrl><A> will select all actions. Finally, when you hold your mouse at rest above an action, a longer description is given of the action in a pop up window so that you can see what it does without actually having to open it.

There are two further buttons available at the bottom of the events list, Delete and Change. As you may well imagine, the Delete button will permanently remove the currently selected event and all its associated actions from the object (Events without any actions assigned to them will automatically be deleted when you close the form so there is no need to delete them manually). The Change button can be used to change the current event into another one, and in this way transfer all the associated actions to the new event (if the event you try to change to has already been defined then nothing will happen). These actions can also be accomplished by simply right clicking on the event and selecting the appropriate choice from the pop up menu that will open.

In this way you can "build" behaviours that are triggered by specific events in your game by just adding in more actions or more code (you are not limited to the amount you can add for each event). If you wish to know more about all the available actions then you can go to the Actions section of the manual, and the Reference section has all the information you need on the available code functions.

Event Order

It should also be noted that the exact order that the events are going to occur in each step cannot be clearly stated, simply because it depends on the internal workings of GameMaker: Studio, which is subject to change as the software develops. However there are certain events that always run in the same order. The first set of events that will always happen the same way are those that occur when a room is first entered and the order of events for that is:

  • Create Event of each instance, followed by the
  • Instance Creation Code of each instance
  • Game Start Event (this will only be run in the very first room of the game)
  • Room Creation Code
  • Room Start Event of all instances

It is also worth noting that you can also set the order in which specific instances are created within the room editor itself. See the section on Instance Order in the Rooms - The Settings Tab for further details.

Other than those specific events, the only known order that will always occur in the same way no matter what belongs to the three step events and the two draw events. These will always remain consistent, so if you have code that relies on specific timing during each step of your game, you should use:

  • Begin Step Event
  • Step Event - The step event is executed just before instances are put in their new positions.
  • End Step Event

All of the sub events for drawing are also always dealt with in the same order as follows (except for the Resize event, which is triggered differently):

  • Pre Draw Event
  • Draw Begin Event
  • Draw Event
  • Draw End Event
  • Post Draw Event
  • Draw GUI Begin Event
  • Draw GUI Event
  • Draw GUI End Event

The sections below deal with each available event:

Create Event

Destroy Event

Alarm Events

Step Events

Collision Event

Keyboard Events

Mouse Event

Other Events

Draw Events

Asynchronous Events

Back: Using GameMaker: Studio
Next: Actions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Alarm Events

The alarm events are one of the many events that can be triggered in an instance and may contain code or actions.

The Alarm Events
The alarm event is split into 12 sub events, one for each of the possible alarms that can be set in an instance. So, when you click on the add alarm button you are presented with this window:

Here you select the alarm that you wish to create and, once that is done, you will see that it has been added to the event window allowing you to add actions to it as normal. But what is an alarm? Well, it is a special event that does nothing unless the alarm has been previously set, and then it will wait until that alarm has counted down to 0 before running the actions or code that you have added into it. So, say you set alarm[0] in the create event of the object to 30, this means that GameMaker: Studio will count down 30 game cycles (steps) before it runs the actions or code that are placed in the alarm[0] event.

This can be very useful as it allows you to set things in motion at precise moments, and you can even have them repeat as there is nothing to stop you setting an alarm in its own event! Imagine you have a monster and you want it to turn right every three seconds... well, you would set an alarm in its create event to the room speed*3 (if the room speed is 30, that's 30 steps per second, so multiply that by 3 and you get 3 seconds!) and then in the alarm event you would have the code or action to set its direction, as well as the action (or code) to set its alarm to room speed*30 again. In this way, you can set up simple game loops where things only happen at specific intervals.

NOTE: An alarm with no actions in it will not run. However, even with just a comment and no code, the alarm will count down.

Back: Events
Next: The Step Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Asynchronous Event

The asynchronous event is one of the many events that can be triggered in an instance and may contain code or actions.

Asynchronous Event
This event is special in that it is not triggered by GameMaker: Studio itself, but rather by the end of some other action, like the loading of a file, or the reply from a web server. The actual event is split into various sub events:

So, say you want to add an image file to GameMaker: Studio. Well, you would code this in another event (maybe the create event) of an instance and then have that instance draw a loading bar while waiting from the callback that tells GameMaker: Studio that the file has loaded. This callback triggers the Asynchronous Event where you would then do something else, like go to another room.

For more details on this event and how it functions please see More About Async Events.

Back: Events
Next: The Create Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Collision Event

The collision event is one of the many events that can be triggered in an instance and may contain code or actions.

The Collision Event
Obviously when making a game, it is very important that you know when two (or more) instances of an object have collided, and for that we have the collision event. This is an event that you place in an object and then specify against which other object you should be checking for collisions.

Now, when you don't have physics turned on, these collisions will be calculated based on the mask of the two objects (the mask is defined within the sprite properties, or can be assigned independently in the object properties) and whether they over-lap or not. Note, that if one or the other instances in the collision does not have a mask assigned (or the sprite mask is set to nothing), even if it is drawing something no collisions will be detected. Also, if the object being collided with is solid, before the collision event code is run the instance is placed back at its previous position before the collision was registered, but only if there is a collision event defined.

If you have physics on, the collision will be based on the type of collision shape that you have defined for the object in its physics properties, as will its reaction to the collision.

Back: Events
Next: The Keyboard Events

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Create Event

The create event is one of the many events that can be triggered in an instance and may contain code or actions.

The Create event
This event happens when an instance of the object is first created, and is the very first thing that happens within an instance placed in the room through the room editor when a room is entered. This means that this event is the ideal place to initialize variables, start Timelines, set paths etc... and do anything else that generally only needs to be done once or only when an instance first appears in the room.

NOTE: This event will always be called the moment an object is created.

Back: Events
Next: The Destroy Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Destroy Event

The destroy event is one of the many events that can be triggered in an instance and may contain code or actions.

The Destroy event
This event is the very last event to be executed when an instance is destroyed. It is often overlooked when adding behaviours to objects, but it can be very useful, for example by creating explosion or particle effects when an enemy is killed, or for re-spawning a new instance of the object in another part of the room, or even for adding points onto a score.

NOTE: This event is called the moment the action or code to destroy the instance is run.

Back: Events
Next: The Alarm Events

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Draw Event

The Draw Events are some of the many events that can be triggered in an instance and may contain code or actions.

Draw Event
This event is the one that governs what you see on the screen when you run your game, and is split into various separate "sub-events":

As you can see, the draw event category has multiple different event types, and here we will deal with the standard Draw Events: draw Begin, Draw and Draw End. You can get information on the other event types from the following pages:

  1. Draw GUI Event
  2. Pre And Post Draw Event
  3. Resize Event

The standard draw events are the ones covered on this page and they run before the Draw GUI events and between the Pre Draw and Post Draw events, meaning that everything that is drawn in this event is drawn beneath that of the Draw GUI event, regardless of depth (ie: anything drawn in the Draw GUI event will always be drawn over anything drawn in the normal draw event, regardless of depth). The image below illustrates the order in which each event is performed:

The Standard Draw Event

The normal Draw Events fall into three types: The Draw begin, the standard Draw and the Draw End events. In general, you will only need to use the standard Draw event and you should be aware that all instances in a room will have this standard draw event triggered each step of the game. So, this event will always be called as long as the instance has the visible flag set to true. Even if you have defined nothing for this event in the object properties (ie: no code nor actions), if the object has a sprite assigned it will still have a draw event which will be triggered! You see, GameMaker: Studio has two ways to draw things in the standard Draw event:

  • the default draw, which is when you define the sprite in the object properties and place no actions or code in the normal draw event, in which case GameMaker: Studio will draw that sprite, but note that any transforms you perform in other events to change the image scale, index, blending etc... will be reflected too as long as the draw event is empty.

  • the custom draw, which is when you place code or actions in the draw event. This is telling GameMaker: Studio "I want to control what you draw for instances of this object" and it completely over-rides the default draw. This means that you can have an object with a sprite assigned, then set the draw event to draw text and the sprite will not be drawn as you have not told GameMaker: Studio to draw it.

Draw Begin and Draw End Events

Apart from the main draw Event, you also have a Draw Begin and a Draw End event. These act exactly the same as a standard Draw event (ie: they will draw whatever you put in them every step of the game and for all views), but they do not "default draw" anything if not added to an instance, and they will always run before/after the standard Draw event. So, you would have the Draw Begin step for all instances, then the Draw Event for all instances, then finally the Draw End step for all instances.

In this way, you can draw things or set draw properties in the Draw Begin step in one instance and be sure that all instances with a standard Draw event or Draw End event will use these properties or draw over what the first instance has drawn. Basically its a sure fire way to guarantee that certain things are drawn at certain times, much like the Begin Step and End Step events do.

Things to Note

There are a few things to note when drawing things in GameMaker: Studio, whether it's a sprite you are drawing or a shader, or 3D:

  1. The draw event is a very intensive event, in that it's one of the events that takes up most time and resources... to that end it is never a good idea to do anything in the draw event other than drawing. So save your large code or complex actions for the Step event or Alarms or whatever other event fits, but leave the draw event clear for the drawing as that's what it does best.

  2. If your object has had the visible parameter set to off (so that the instances of the object are not drawn) then all draw events are skipped (except for the Resize event. This means that making an instance invisible will stop all code placed in any of these events not to run, so don't put essential code in the draw events if they are not going to be visible.

  3. What you draw has nothing to do with the collision engine you choose (traditional or physics) as that is defined by the object properties and the sprite or mask that the object has been given.

Back: Events
Next: The Draw GUI Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Draw GUI Event

The Draw GUI Events are some of the many events that can be triggered in an instance and may contain code or actions.

Draw GUI Event
The Draw Gui event type falls under the Draw Event category and are specifically designed for drawing GUI (Graphical User Interface) elements that are not affected by the view scale or rotation. This means that you can have an instance draw all the elements for your HUD without having to base all the positioning on the position within the room of the instance and the position of the current view either.

When drawing in these event it is important that you understand that the draw coordinates do not change even when views are active and 0,0 is always the top left hand corner of either the application surface or the display (see the note at the bottom of this section), and the default width and height are 1:1 with the application surface. Depth ordering is still maintained between different instances (so an instance at a low depth will draw over one at a higher depth) and also within the events themselves, as the Draw GUI Begin event will draw for all instances first, then the standard Draw GUI will draw for all instances over that, and finally the Draw Gui End event is triggered.

In this way, you can draw things or set draw properties in the Draw GUI Begin step in one instance and be sure that all instances with a standard Draw GUI event or Draw GUI End event will use these properties or draw over what the first instance has drawn. Basically its a sure fire way to guarantee that certain things are drawn at certain times, much like the Begin Step and End Step events do.

These events can also be used in conjunction with the normal Draw events (which will be affected by the view position, scale and rotation as normal). If you have no Draw Event but you do have a Draw GUI Event, then GameMaker: Studio will still default draw the sprite for the instance (if it has one) as normal.

You may notice depth issues when using this event due to the fact that it is not dealt with the same was as the traditional draw event. What happens is that the normal draw events for all instances are resolved first, once each for each active view, and then the draw GUI events for all instances are resolved. So the depth order between instances with draw GUI events is always respected, as is the depth order between instances with normal draw events, but the draw GUI events will always draw over anything drawn in the normal draw event, even if the instance doing the drawing it is at a higher depth than other instances.

NOTE: This event will, by default, draw 1:1 with the application surface size, which is normally the size of the room or the view port. This means that when you have Aspect Ratio Correction on in the Global Game Settings the GUI is not going to be drawn over the black bars that "letterbox" the game. This behaviour can be switched off using the display_set_gui_maximise function, and you can also lock the GUI event to a specific size which will then be scaled to fit the display or application surface dimensions automatically by using the function display_set_gui_size.

Back: Events
Next: The Pre And Post Draw Events

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Keyboard Events

The keyboard events are three of the many events that can be triggered in an instance and may contain code or actions.

The Keyboard Events
Obviously when creating a game, letting the player control the different aspects is very important. To that end GameMaker: Studio provides you with a very comprehensive list of keyboard sub events that can be used in any of the three main keyboard events. As these are all the same for each of the three events they will all be covered together in this section of the manual.

Before looking at the sub events, let's look at the three keyboard events themselves:

  • Keyboard Pressed Event: This event is only triggered once whenever the selected key is pressed down
  • Keyboard Event: This event is triggered continuously, every step, for as long as the selected key is pressed down
  • Keyboard Released Event: This event is only triggered once whenever the selected key is released

As you can see, each of these events does a very different thing and knowing the distinction between them can help you solve many a problem or do things in your game in a much more efficient way. It should be noted that keyboard events are actually triggered in all active instances in a room whenever a key is pressed, but only those that have an event defined for that particular key will respond and you can create multiple keyboard events in any object and the instances of that object will respond to all of them while the game is running.

When you add any keyboard event to an object, you will be presented with the keyboard sub event menu where you can specify the key you are to be checking for:

Now, most of them are fairly obvious, but let's just go through the sections briefly - at the top we have the arrow keys, followed by the most used modifier keys, then the rest of the keyboard (split into sub sections as you can see) and finally two very special sub events, No Key and Any Key. As their names imply, these are sub events that check for when no key is pressed or for when any key is pressed. Please note that the keys on the numeric keypad only produce the corresponding events when <NumLock> is pressed.

Back: Events
Next: The Mouse Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Mouse Event

The mouse event is one of the many events that can be triggered in an instance and may contain code or actions.

Mouse Events
The mouse event is separated into a series of sub events that can be selected to give you a more precise control over what is happening in your game. Here you can see exactly what these sub events are:

The left, right and middle button events (whether normal, pressed or released) all work on the mask of the instance that has the event. What this means is that GameMaker: Studio will check the position of the mouse in the room when those buttons are used against the collision masks of the instances that have a mouse event. If there is a "collision" then the event will be triggered, so make sure than any object with these events has a sprite with a valid mask or that the object has a mask selected in the object properties. As their names imply, these events will be triggered either once when the chosen mouse button is first pressed or released, or continuously each step while the button is maintained.

The mouse enter and release events are also similar to the button events in that they too rely on the mask of the instance to work, but this time they are triggered when the mouse first "enters" (touches) the object or when the mouse "leaves" (stops touching) the object. These events are not continuous however, and are triggered only once for each time the mouse enters or leaves the object - so they are an ideal method for creating, for example, buttons that need to change as the mouse hovers over them before going back to normal when the mouse is removed.

Finally we have another section to the mouse events which is called the Global Mouse. in this sub-menu you will find a selection of events that are for generating mouse events in instances even when the mouse is not over them or even near them. These are events that are generated for all instances and if there are actions or code defined for the specified event then it will be run, regardless of the position of the mouse within the game room.

Please note that on devices (iOS and Android targets) the left mouse button can also be used to check for a finger tab on a touch screen, and the right mouse button is triggered by a double tap on the screen.

Back: Events
Next: The Other Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Other Event

The other events are some of the many events that can be triggered in an instance and may contain code or actions.

Other Events
There are a number of special events for use when making games with GameMaker: Studio and they are mostly grouped together under the Other event and can be selected from the pop up menu of sub events that comes up when you select this. Here is an image of all these other events:

Outside Room

This event is triggered when an instance goes outside the room, and is based on a check done against the assigned sprite (and its properties) of the instance, so that even if you have set the image x or y scale to a value other than one, this event will only be triggered when the whole sprite would be out the screen. If the instance has no sprite, then the position of the instance is used and the moment its x or y position is outside of the room then it will trigger the event too. This event is typically used for things like bullets, where they are destroyed once they leave the room so you don't end up with millions of bullets flying away infinitely and causing your game to slow down. Note that this event is only triggered once when the instance leaves the room initially.

Intersect Boundary

This event is triggered when an instance "touches" the inside edge of the room, and, like the outside room event, is based on a check done against the assigned sprite (and its properties) of the instance, so that even if you have set the image x or y scale to a value other than one, this event still be triggered the moment a part of the sprite intersects the room boundary. If the instance has no sprite, then the position of the instance is used and the moment its x or y position intersects the room boundary then it will trigger the event too. You can use this event to do things like tell an instance to "bounce" back in towards the room again rather than go outside.

Views

Views are normally defined in the room editor and used to show only a small area of a large room at any one time. This event has its own sub event list that is split into two categories (outside view and intersect boundary), with eight different events in each corresponding to the eight available views. These two categories function exactly the same as the respective room events, only taking the boundary of the view as the thing for the instance to check against rather than the room.

Game Start

This special event is triggered only once in the whole game and only for those instances with actions or code placed in the event. These instances must be present in the first room of the game and have been placed there in the room editor, rather than have been created dynamically. It should be noted that this event happens after the create event of all instances and so can contain code or actions with variables that have been previously defined in that event. This event is typically defined in only one "controller" object and is typically used to initialize global variables, start music, read from files and any other thing that is usually only done once at the start of a game.

Game End

Similar to the above mentioned Game Start event, this event is only triggered once in the whole game and that is just before the game window actually closes. Again, for an instance with this event to actually do anything it has to be in the room as the game is closed. Please note that this event in really only viable for Windows, Ubuntu (Linux) and MacOS games as mobile devices may just close the game without giving GameMaker: Studio the chance to call this event. For browser games made with the HTML5 module, this event should work when the game tab or browser is closed, but not all browsers support this feature (Firefox, Chrome and Safari do at the time of writing) so care must be taken when using it. Typically you would use this event to save data.

Room Start

This event happens for all instances initially in a room when the room starts. Please note that it happens after the creation event and so can depend on variables and things defined previously in that event.

Room End

This event happens to all instances that are in the room when the room ends. This event is very useful for "cleaning up" after a level has ended, for example you can delete loaded resources here, or remove a particle system to prevent memory leaks etc...

No More Lives

GameMaker: Studio has a built-in lives system, which is basically a global scope variable that is created for you at the start of a game. There is an action to set and change the number of lives, and you also have the option to manipulate this variable through code. This event will be triggered whenever the number of lives becomes less than or equal to 0 and it is typically used to end or restart the room.

No More Health

GameMaker: Studio has a built-in health system, which, like Lives above, is basically a global scope variable that is created for you at the start of a game. There are actions to set and change the health variable as well as to draw a health-bar, with code available to change them too should you prefer to use GML. This event is triggered whenever the health becomes less than or equal to 0. It is typically used to reduce the number of lives or to restart the game or room.

Animation End

In GameMaker: Studio sprites are not static things as they can have sub-images and be animated at different speeds. Each frame of an animation (called a sub-image) has its own number, starting at 0, which can be checked in code or even through actions, but sometimes all you really need to know is when the animation has ended. That's when this event is triggered, right at the end of the animation, the moment that the sub image index loops back to the beginning (0). This event is really useful for many things, for example an explosion object where you can set the instance to destroy itself after the last frame of the animation has been shown.

NOTE: Because the animation has already looped when this event fires, if you want to freeze the animation on the exact last frame then you will need to manually reset the image_index to the last frame (image_number - 1) in this event.

Animation Update

This event is designed onlyfor use with the Skeletal Animation Functions. It is a special event that is triggered every step in an instance that uses a skeletal animation sprite, and is designed to "intercept" the bone data after the orientation of the bones has been calculated for the current animation state but before this data is committed to use for drawing. This allows you to make modifications to the bone data using the appropriate functions.

Animation Event

This event is triggered in an object which has a skeletal animation sprite assigned to it, and where the object is using the default draw for the assigned sprite, or the sprite is being drawn via draw_self(). It currently won’t trigger on skeleton animation sprites drawn any other way. The event is designed to capture and transmit the events that have been assigned to particular events in the sprite animation as defined in the editor used to make them.

When the Animation Event is triggered, a special ds_map will be created called the event_data map (much the same as we have the async_load map for an async event). This map will have all of the following key/value pairs that you can parse to get information about the event:

  • "name": the name of the event (as defined in the animation program)
  • "track": the index of the track the animation is playing on (default is 0)
  • "integer": an integer value associated with the event (as defined in the animation program, default is 0)
  • "float": a float value associated with the event (as defined in the animation program, default is 0.0)
  • "string": a string value associated with the event (as defined in the animation program, default is an empty string "")

End Of Path

Paths can be an important part of making any game, whether it is for a tower defense type game, or a shoot-em-up or whatever, and it's often really important that an instance does some particular action when it reaches the end of its path. This event detects this and is triggered when it happens allowing you to add in code or actions to deal with the circumstances, for example in a tower defense game you would use this to destroy the instance and remove a health point from the goal object.

User Defined Event

These are special events that are not triggered by GameMaker: Studio itself, but have to be implicitly called by you from a code box while the game is running. These events can contain code or actions and do the same things as any other event, making them very useful for creating your own events that happen when you decide and not GameMaker: Studio decides!

Back: Events
Next: The Draw Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Pre And Post Draw Events

The Pre And Post Draw Events

The Pre Draw and Post Draw event are two of the many events that can be triggered in an instance that may contain code or actions.

Draw GUI Event
The Pre Draw and Post Draw events are part of the Draw Event category. However, unlike the other Draw events these draw directly to the screen buffer, which will be the size of the combined screen space for all views currently visible, or the window size if only using one view or none at all. The image below illustrates this:

So, if you are using the Pre or Post draw event, you are drawing to the full screen render target which will have the same size as the window to which all views are made to fit. If you have no views active, this is instead set to the size of the window itself.

The Pre Draw Event

The Pre Draw event is triggered before any other draw event, and in it you can set values, set draw properties and even draw things without worrying about the views or the size of the GUI layer (the GUI layer size may be the same as the screen buffer, but it may not since you can set the GUI resolution in code).

It is worth noting that this event happens before the screen buffer is cleared meaning that if you do not switch off view clearing in the room editor then nothing that is drawn in the Pre Draw event will be seen, as the first view will clear it. If you want to be able to see through the views themselves, or you are not using views at all, then you should also have set the background colour to not be drawn in the appropriate room editor tab too.

NOTE: If you switch off these options, you may notice unwanted artefacts being drawn on the screen when the game is tested (like "trails" from instances). This is because you are drawing directly over the previous frame of the draw buffer without it being cleared. However you can use draw_clear_alpha.

The Post Draw Event

The Post Draw event is triggered after the standard draw events, but before the Draw GUI events. Like the Pre Draw event, it is based on the size of the screen buffer size, and is placed before the Draw GUI events to enable you to perform post-processing effects and other things on a full screen basis simply and easily without interfering with any HUD/GUI elements that you may have in your game.

Back: Events
Next: The Resize Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Resize Event

The Resize Event (Obsolete)

The Resize event is one of the many events that can be triggered in an instance and may contain code or actions.

Resize Event

IMPORTANT! This event was desgned for use with a target platform that is no longer supported, and as such is obsolete.

This event type falls under the Draw Event category, and although it doesn't actually draw anything, it does react to changes in the draw canvas - specifically, it is designed for reacting to the change in the Windows 8 canvas size when the game window is "snapped".

On the Windows 8 target platform it is important that you catch any resizing of the game canvas from the "snapping" of the game window (when the user drags the window to the side of the display, for example). This event will do just that and is triggered every time the canvas is changed, permitting you to add custom code here that will resize the view or reposition HUD elements as necessary. This function is provided as a convenient way to avoid having step event code that checks for these things all the time.

NOTE: You cannot draw in this event! It is triggered by resizing the canvas and is only for catching this change... any drawing that should be done still must be in one of the other draw events.

Back: Events
Next: The Asynchronous Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Step Events

The step events are one of the many events that can be triggered in an instance and may contain code or actions.

The Step Events
GameMaker: Studio splits time into steps with the room speed defining how many of these steps there are supposed to be per second. A step, is basically the loop that runs constantly with all the events being checked and triggered as necessary while the game runs, so as you can imagine, the Step Event is an event that is checked every single step of the game while the instance exists.

The step event is actually comprised of three sub events that are outlined below:

For most things the standard step event will be fine to use, but sometimes you want a bit more control over what code runs and at what time, so for that you are provided with the begin and end step events. All three are checked every step, but their order will never vary even through future updates to the GameMaker: Studio engine, which means that this is the only reliable method of making sure that something always happens before something else. So what can the step event be used for? Well, it can be used for actions or code that needs to be executed continuously. For example, if one object should follow another, here you can adapt the direction of motion towards the object we are following to keep it moving smoothly behind. Be careful with this event though! Don't put many complicated actions in the step event of objects, especially if you are planning on having lots of instances of the object in your game room, as this might slow the game down.

Back: Events
Next: The Collision Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Trigger Event

The Trigger Event (Obsolete)

The trigger event is one of the many events that can be triggered in an instance and may contain code or actions.

Trigger Event
A trigger event is an event that permits the user to define special conditions which will "trigger" a set of code or actions to run. When you add a trigger event you will be presented with a menu of sub events like this:

The first two things you see on that menu are just examples of triggers that have been defined previously (these were created to give an example and are not standard GameMaker: Studio triggers), and the last section, "Add/Modify Triggers", is where you would define them so that they show up on this menu.

Important

The trigger event has been made obsolete in GameMaker: Studio and the references to it in this manual are only due to the fact that previous versions of GameMaker may have them. In this case it is important to know how they worked so as to make importing these older projects easier. For more in depth information on triggers, please see the following section of the manual - Obsolete Functions: Triggers

Back: Events

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Creating Rooms

Rooms are where everything in your game happens, and this section outlines how you create them and add instances to them.

All games that you make in GameMaker: Studio need at least one room to run (but can have many, many more) , and a room is just a space where you place instances of the objects that make up your game. When you first create a room in your resource tree you will be presented with a new window with which to edit its properties, something like this:

As you can see, most of the room editor is taken up with the a visual representation of the room itself, where you place the objects, tiles and backgrounds for your game, but around the edges there are a number of buttons, tabs and information bars that help you to create your game.

The Toolbar

At the top of the form there is the tool bar, which has a number of buttons that refer to different actions in the room editor.

  • Confirm: Clicking this button will close the room editor and save any changes you have made. Beware, as this will not warn you that the room has changed, as clicking the close button would do, but will just save directly any changes you have made. However, depending on the GameMaker: Studio preferences, you may be asked if you want to remove any instances that have been placed outside the room or not.

  • Undo: This is a simple, one level, undo button. By one level, we mean that only the last action performed will be undone.

  • Instance Actions: These buttons allow you to change certain properties of the instances (and tiles if you are in the "Tile" tab) in the room, specifically: clearing all instances from the room, shifting all instances a set amount along the x and/or y axis of the room, locking instances (so they cannot be moved or edited) and unlocking instances.

  • Grid Snap: These values can be changed to make instances snap to a different grid resolution. A value of 0 will switch snapping off.

  • Visualisation: By clicking this you will open a drop-down menu where you can switch on or off the visualisation of many room elements, like instances, tiles, views etc... Here you can also change the grid type from being the regular square grid to a diamond "isometric" grid. You can enable/disable the grid overlay by clicking the grid icon.

  • Zoom Controls: The main view of the room editor can be zoomed in and out to show more or less detail either using these controls or by scrolling the mouse wheel (if you have one).

  • Instance Order and Shortcuts: Both these buttons will bring up separate windows, with the first giving you the option to change the order in which instances are created at room start (see the Room Settings page for more information), and the second shows the available keyboard shortcuts that you can use when editing rooms.

The MiniMap

As you can imagine, this is a miniature representation of the whole room. you can click and drag the current area around on the minimap and the main view will scroll and pan to match, or you can just click on the minimap to have the main view jump to that position.

The Info Bar

While placing tiles and instances within a room, you often need extra information about them at a glance. For that you have the Info Bar which shows the current mouse position within the room, the id and object_index of the instance that the mouse is currently over, and further context sensitive information like whether the instance has code or not in its room create event.

The Tabs

At the left you will see six tabs that open separate sub-pages in the area on the left, but in this section we will only deal with the three most important ones: The settings tab, the backgrounds tab and the objects tabs. Further information on these tabs can be found in the sections below:

  1. Settings
  2. Backgrounds
  3. Objects

For information on the other tabs as well as the advanced functions available to you in the room editor please see the section - Advanced Use: More About Rooms.

Back: Using GameMaker: Studio
Next: Game Information

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Backgrounds

Within the tab backgrounds you can set the background images for the room.

This tab is where you can define the backgrounds of your room. A background can be made up of a single colour, an image, or a combination of colour and transparent images. The following options are available:

Draw Background colour

When you tick this option, you are telling GameMaker: Studio to draw a background colour below everything else in your room. This colour can be selected by clicking on the colour box which will open the following standard colour picker: The background colour is only useful if you don't use a background image that covers the whole room, or if that image is partially transparent, otherwise it is best to un-check the box labeled Draw background colour as this will save some processing time.

It is worth mentioning that for the HTML5 module, switching this option off and unticking "Clear Background with Window colour" in the Views Tab permits you to use the special function draw_clear_alpha to clear the canvas alpha, making your game "transparent" and so showing any background images that you may have on the host web-page HTML.

Warning! Having a room with no background colour and no background image will result in "artifacts" being left behind by all moving instances within the room on most of the target platforms (which can give some interesting results!)

Background Number

Underneath the colour picker, you can see a list of eight backgrounds numbered from 0 to 7. These can all be defined for one room, and you can have all eight active at any one time if you wish. When you select one, all the options beneath will then refer to that background only, and in this way you can define the properties for all eight independently. The rest of the options on this page are applied to each individual background that you select.

Visible When Room Starts

This toggles the background when the room starts between being visible or not. You may have a game where only one of the backgrounds is visible at the start of the game, but later you wish to set another up as visible. So, you set up the two backgrounds in the room editor and then in a later event within an instance, you can toggle between them. Another thing you may want is several backgrounds visible at the same time, especially if you wish to have semi transparent parts, different sizes or even parallax scrolling, so you can toggle this to have various visible at once.

Foreground Image

Toggling this converts the background into a foreground, which basically means that instead of being drawn below everything it is drawn on top of everything.

Background Select

If you click on this box, you will be presented with a list of all the background resources available and you may select one of them to be used as the background image for the currently selected background.

Tile Horizontally And Vertically

By checking these options you are telling GameMaker: Studio to tile the background in the chosen direction infinitely. You can choose the position within the room for the coordinates of the top left hand corner of the background and the room will be tiled from this point, or, if tiling is not activated, the background will be drawn at that point.

Stretch

This option will stretch the background to cover the whole room. Bear in mind that this option will make backgrounds that are smaller than the room larger to fit and make backgrounds that are larger than the room smaller to fit too. Note that the ratio of the image will not be maintained, so some distortion may occur when using this option.

Horizontal And Vertical Speed

These options allow you to set the background image to scroll through the room at a given speed. You can have positive or negative values, where a positive value for the horizontal scroll would be to the right (negative to the left) and a positive value for the vertical scroll would be to the bottom (negative to the top). The speed is calculated in pixels per step, so a horizontal speed of 5 will move the selected background through the room 5 pixels to the right every step. This can be particularly useful for top down shooter games, where you can have a scrolling tiled background to give the illusion of movement and make the room seem infinite even when it is really small. Be careful using these options with stretched backgrounds as the result can sometimes be rather ugly.

Back: Creating Rooms
Next: Objects

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Objects

This section discusses the objects tab in the room editor.

The objects tab is where you can select an object and then place an instance of that object into the selected room.

First you must decide which object from your resource tree you wish to add, and this can be done by clicking on the Object to add with left mouse menu button, or by clicking the large area above where the object sprite is normally shown. If the object has no sprite, this box will be blank, but if it does, the sprite will be shown on a chequered background along with its x/y origin which indicates how the instance will be aligned with the grid once placed in the room editor.

Instance properties

Once you have selected the correct object, you can now place instances of it within the room by clicking anywhere, with the instance being snapped to the grid (if you have the snap values other than 0). There are a number of additional options which will be made available to the right of the object image that you can then change for the instance that you have just placed within the room. These are:

  • PositionX - With this you can set the position in the room along the x-axis (note that negative values are accepted and you can set values to outside the defined room boundary).

  • PositionY - With this you can set the position in the room along the y-axis (note that negative values are accepted and you can set values to outside the defined room boundary).

  • ScaleX - With this you can set the scale along the x-axis of the instance. 1 is the default value, and you can use negative values too to "mirror" the instance.

  • ScaleY - With this you can set the scale along the y-axis of the instance. 1 is the default value, and you can use negative values too to "flip" the instance.

  • Rotation - Rotates the instance around its x/y origin by the given number of degrees. You can use any real number for this value.

  • Alpha - With this you can set the alpha value for the instance from 0 to 255, where the default value of 255 is completely opaque, and 0 is completely transparent.

  • colour - This option sets the colour to be blended with the current instance sprite. White is the default colour (which means that the instance will be drawn "as is" with no blending).

  • Flip X - Flagging this will mirror the instance sprite along the horizontal (the same can be achieved by setting the ScaleX value to -1).

  • Flip Y - Flagging this will mirror the instance sprite along the vertical (the same can be achieved by setting the ScaleY value to -1).

You should note that a selected instance can also be scaled by clicking on one of the corner "nodes" that mark the bounding box of the instance when you select it in the room editor. By clicking the node and dragging the mouse, you can change the image scale, and these changes will be reflected in the values of the above mentioned areas. You can also use the cursor keys to move an instance of an object placed in the room and so "fine-tune" the position easier. By default this is a shift of 1 pixel at a time, however you can modify this behaviour using the following keys:

  • <Shift> + cursor keys - Move the instance 10 pixels in the direction of the cursor key.

  • <Control> + cursor keys - Move the instance 5 pixels in the direction of the cursor key.

  • <Shift> + <Control> + cursor keys - Snap the instance to the next nearest grid position in the direction of the cursor key.

Delete Underlying

The normal behaviour for placing instances within the room is that if you place an instance on top of another one, the original instance is overlapped by the new one. Generally this is what you want to happen, but not always, and so there is a check-box at the bottom of the objects tab which you can flag to make any new instances delete those that were place before in the same position. The "hitbox" used to calculate whether an instance is over another one or not is the bounding box taken from the collision mask defined for the sprite that the instance uses. if the instance has no sprite, then only those that have been previously placed at the same position will de removed.

Shortcuts

There are also a number of keyboard shortcuts that can be used to make your life easier when placing instances (you can open the following window that shows them all from the toolbar at the top of the room editor):

  • Clicking with the left mouse button in the room will place an instance of the currently selected object, and clicking an instance will permit you to move it around the room.

  • Holding the <Alt> key while placing the instance will make ignore the grid snapping and be placed exactly where you release the mouse button.

  • Holding the <Shift> key while clicking the left mouse button on an instance will add it to the selected group. In this way you can select multiple instances which can then be moved together by clicking and dragging the bounding box, or they can be copied and pasted, even into other rooms.

  • Holding the <Control> key while clicking the left mouse button will add a new instance on top of previously placed ones.

  • Holding the <Shift> key and the <Control> while clicking the left mouse button will add multiple instances like a "brush" when you drag the mouse around.

  • Holding the <Space>key while clicking and dragging with the left mouse button (or simply clicking and holding the middle mouse button) permits you to scroll around the room.

  • Right click on an individual instance will bring up a special menu with further options (more information on this can be found here - Advanced Use: More About Rooms).

  • To remove an instance from the room, hold the <Control> key and then right click the instance.

  • To remove all instances at the mouse position, hold <Shift> key and then right click the position.

  • Holding the <Control> key and pressing the "C" keyboard key will copy the selected instance or instances.

  • Holding the <Control> key and pressing the "V" keyboard key will paste the selected instance or instances, even in a different room from that in which they were copied.

  • Using the mouse wheel permits you to zoom in and out of the room editor.

Back: Creating Rooms
Next: Settings

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Settings

Each room has a number of settings that you can change by clicking on the settings tab.

This tab is where you set the basic details of your room and should be your first stop whenever you create a new room. The following settings are available:

Name

The "Name" of your room is the unique identifier that you can use to direct GameMaker: Studio to the correct resource. This name is really just a "pointer" as it holds the internal id of the room and "points" GameMaker: Studio to the correct resource when it is referenced. This means that it is very important that no other resource has the same name as this will cause conflicts and cause unexpected errors within your game. This name is what you will use in all code and actions that move the player from room to room or change room properties.

Width and Height

As you can imagine, a room has to have a size and this is defined by the values that you input for its width and height, in pixels. Be careful here, as it's very easy to say "I'm making a space game, let's have a room 100,000 x 100,000 pixels!" That is a recipe for disaster! GameMaker: Studio is powerful, but there are limits, and so when dealing with rooms it's much better to keep them as small as possible and then optimise your game around them, especially if you are making a game for mobile devices or the web.

Clear Display Buffer

Here you have the option to Clear Display Buffer With Window Colour. This option fills the backbuffer with a colour. If you know that the views or backgrounds are going to be covering the whole screen at all times or that you have a fullscreen background being drawn, then you can un-check this (which saves a redraw and so helps optimise your game), but if you have overlapping views that, when on the screen leave open spaces, or your background has any transparency, you should check this so that those area where there is no view are filled in with the draw colour of your choice. Currently this colour can only be set through code using window_set_colour().

NOTE: If you are using automatic aspect ratio correction (as set in the Global Game Settings, then you should always have this checked otherwise you can get odd effects over the "letterbox" that your game is drawn in. If you do not use this option then you can un-check this and get a small boost to your games performance (especially noticeable on Android and other mobile platforms).

Speed

The room speed is defined as being the number of steps per second that GameMaker: Studio should run at. This is not the same as the fps (frames per second) which can (and usually does!) give a different value. The room speed is the speed at which GameMaker: Studio ticks over and is a constant value, however the fps will fluctuate and is the actual speed at which the game is running. The typical room speeds for a game are 30 or 60, but some people like to set it slightly higher to 100 or 120. There are many arguments about which room speed is the ideal, but the actual answer depends on what type of game you are making, the size of the room, the number of instances and how intensive the code is. For example, if you have a large room (anything over 1024 px) and a room speed of 30, the game may appear "choppy" as the larger the area you are looking at, the easier it is for the eye to perceive low room speeds, but if the game is intensive then setting the room speed to 100 may cause the game to "lag" as the fps drops due to the amount of processing being done. So take care with this value and try to always adjust it to what your game needs.

Persistent

Normally, when you leave a room and return to the same room later, that room is reset to its initial settings. This is usually fine for most games but it is normally not what you want in, for example, an RPG or any non-linear game, where you want to come and go between rooms and have them be way you left it the last time. Checking the box labeled Persistent will do exactly that. The room status will be remembered and when you return to it later, it will be exactly the same as you left it, with it only being reset to the start state when the game is reset. Note that there is one exception to this - if you marked certain objects as being persistent, instances of this object will not stay in the room but move to the next room.

Creation Code

If you click on this button you will open a code editor. This editor allows you to input functions and code that will be run at the start of the room, after the create event of all instances but before their room start event.

Instance Order

On very rare occasions you may require your game to create one object before any of the others, but not wish to use an alarm due to dependencies between instances. In that event, you can use this button to open up the Instance Order window. Here you can select individual instances and move them up (or down) the creation order list, meaning that those at the top are those which are created first, while those at the bottom will be created last. You can move multiple instances up or down the list by using <SHIFT> + LMB to select them and then clicking the move buttons, although if you stagger the selection of instances (ie: you select instances 1, 3 and 5 while missing out 2 and 4) then when you move them to the top or bottom, it will bunch them together (so if you moved 1, 3 and 5 to the top, your order will now be 1, 3, 5, 2, 4).

NOTE: If the create event of the instance actually creates further instances, those instances will be next in the order for running their code, before going to the next instance set in this list.

This is actually quite a powerful tool for advanced users, as you can use it to give individual instances unique names to make them something more memorable or obvious than the default inst_<value> that GameMaker: Studio assigns by default (Important! This name is unique to the game, not the room, so you cannot have two instances with the same name, even if they are in different rooms). You can also open up the object properties for any instance, remove it from the room, or see its creation code.

Back: Creating Rooms
Next: Backgrounds

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Advanced Use

This section is designed to explain some of the advanced functions to be found in the GameMaker: Studio IDE.

The GameMaker: Studio IDE (integrated development environment) has a number of advanced options that are of great importance if you wish to get the most out of the product. These options include source control integration, project configurations, advanced debugging and a number of extra tools for changing and manipulating the game assets, although the exact selection of tools available to you will depend on the version of GameMaker: Studio that you are using (more information on versions can be found here). The following sections and sub-sections explain every detail of how to get the most out of GameMaker: Studio using these advanced tools, features and options.

Game Assets

  1. More About Sprites
    1. - Editing Sprites
    2. - Editing Subimages
    3. - Editing Collision Masks
  2. More About Backgrounds
    1. - Designing Tiles
    2. - Texture Pages
  3. More About Objects
    1. - Parents
    2. - Object Physics Properties
  4. More About Rooms
    1. - Tiles
    2. - Views
    3. - Physics
  5. More About Async Events
    1. - Image Loaded and Sound Loaded Events
    2. - HTTP Event
    3. - Dialogs Event
    4. - IAP (In App Purchases) Event
    5. - Cloud Event
    6. - Networking Event
    7. - Steam Event
    8. - Social Event
    9. - Push Notifications Event
    10. - Load/Save Event
    11. - Audio Recording Event
    12. - Audio Playback Notification Event
    13. - System Event

Resource Editors

  1. Fonts
  2. Paths
  3. Time Lines
  4. Scripts
  5. Shaders
  6. Macros
  7. Including Files
  8. Importing Resources

Game Settings

  1. Extension Packages
    1. - Using an Extension
    2. - Creating an Extension
    3. - Legacy Extensions
  2. Configurations
  3. Source Control
    1. - Getting Started With Source Control
    2. - Setting Up GameMaker: Studio For Source Control
    3. - Using Source Control with GameMaker: Studio
  4. Global Game Settings
    1. - General
    2. - Texture Groups
    3. - Project Info
    4. - Source Control
    5. - Advertising
    6. - Analytics
    7. - In App Purchases
    8. - Windows
    9. - Windows UWP
    10. - Mac OS
    11. - HTML5
    12. - iOS
    13. - Android
    14. - Ubuntu (Linux)
    15. - Steam
  5. GameMaker: Studio Preferences
    1. - General
    2. - Forms
    3. - Scripts
    4. - Editors
    5. - Web Server
    6. - Android
    7. - Mac OS
    8. - Ubuntu (Linux)
    9. - Steam
  6. Debugging
    1. - The Debug Module
    2. - Profiling

Back: Contents
Next: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Including Files

This section deals with including external files in your game.

GameMaker: Studio is not just limited to the resources that you create within the program as it has a special section on the resource tree of the main window for Included Files. Here you can load different file types (and even create sub-directories for them) into GameMaker: Studio and they will then be included in the final game as part of the final package for the target platform. So, for example, in a windows game they will be bundled within the *.exe and exported when run, or in HTML5 they will be included in the html5_game folder and stored on the server.

To add a file to your resources you must right-click on the Included Files section of the resource tree and select Create Included File or, if you want to create a sub-directory to store other files, Create Group. This will then prompt you to add a file, or files if your select more than one, to the list. Once it has been added you can right-click on it and select "Properties" to edit the properties of the file: Here you can rename the file if you choose by changing the File Name. Beneath the file name there are also a series of options for the target platform that this included file should be copied to. If you wish it to be only exported when you run the game in a browser, then you would only tick the "HTML5" box, and if you want it to be exported only to Android and iOS targets you would tick those, and so on. If you choose not to tick any targets then that file will not be exported at all. This option is especially useful for those that wish to make use of the Configurations Manager to store certain configurations and export specific files depending on them. Note that you can select all targets or none of them simply by clicking the buttons in the properties window.

Once you click on "OK" the file will be stored with your current project in its own folder called data-files found in the project *.gmx directory. If you have chosen to change the name of the file when you added it to the resource tree, then the file will now be stored with that new name. Please note that from now on you should edit the files stored in this folder and not the original files (unless you plan on including them again, but generally there is no need).

Back: Advanced Use Index
Next: Extension Packages

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Fonts

This section deals with the font resource.

When you want to draw text in your game this text is drawn in a standard Arial 12 points font, but to make more interesting or unique looking texts you will probably want to use different fonts, however. So, to use different fonts that you have on your computer you must create a font resource in GameMaker: Studio. For each font resource you specify a particular type of font from your computer which can then be used in your game using the action or code to set a font for drawing to the screen.

To create a font resource in your game, use the item Create Font in the Resources menu or use the corresponding button on the toolbar, which will cause the following window to pop up: As with all resources, you should give your font resource a unique name so that you (and GameMaker: Studio) can identify it while writing your game. Next you should start selecting the fonts to preview using the drop-down menu "Font" on the left. Beneath this section you can set other things like the size and whether the font should be drawn as bold or italic or have anti-aliasing (edge smoothing) applied, and you also have the option to use High Quality fonts, which will use a different rendering technique for the font glyphs, giving a better, sharper look. However it should be noted that some fonts may not look better, and you should experiment with this option to see which you prefer.

The preview window on the right will show you different text ranges you have selected as they will look with the size and transforms you have specified, except the anti-aliasing which is not visible in the preview but will be in your game. Please note that font scaling (especially from small to large) can give artifacts when drawn, so try to avoid this where possible. There is also a check-box labelled "Include In Asset Package. If you are creating a package of fonts to upload to the Marketplace or to distribute as part of an extension, then you should tick this option otherwise the base font files will not be distributed with the package.

WARNING!: If you include a base font file in this way it must be licensed for distribution.

One final option that you have available to you is the ability to assign your font resource to a texture group. this can be very useful when it comes to optimising the way your game runs and the amount of texture swaps that must be done while the game is being played. for more information on texture groups please see the section Advanced Use - Texture Pages.

NOTE: Due to licensing issues, GameMaker: Studio does not store the fonts with the project file (when the game is finally finished the font is rendered to a texture page, so finished games will draw the text as designed). This means that if you wish to share the *.gmx or a zipped *.gmz file, you must include the font resource that you have used yourself, as not everyone will have the same fonts as you installed on their computer. The only exception to this is when creating asset packages (see above).

Font Range

A font typically consist of 256 characters, numbered from 0 to 255, but in general you use only a small portion of these. This is why GameMaker: Studio defaults to using only the characters from 32 till 127 are stored in the font. You can, however, change the character range used to help optimise your games ie: If you only need the numbers from a specific font, then only select the numbers. To do this, you should first click the Clear button to clear the current range and then click on the "+" button to add a new range. This will open the following window: This window has some buttons to help you establish a standard range for your font -

  • The Normal range from 32 till 127
  • The All range from 0 till 255
  • The Digits range that only contains the 10 digits
  • The Lettersrange that contains all uppercase and lowercase letters only

Other ranges can be used by typing in the first and last character index of the range you wish to set in the Character Range input boxes (If a character does not lie in the range it is replaced by a space). Apart from these buttons and input boxes, you also have two further options there especially useful.

The first is the button marked From Code. If you click on this button and then click OK, GameMaker: Studio will automatically parse your game code for strings and then create different character ranges to cover all the text in your game. Note that it looks for all strings (either within "" or '') and so may also include file names in the character ranges. However you can remove any ranges from your font resource using the "-" button at the bottom of the window and so remove those unwanted characters.

The second button in this window is marked From File and it works similarly to that explained above. If you click on it, you will be asked to supply a file, and then once that is done you should click on OK. GameMaker: Studio will then parse the file and create character ranges for the text found within.

It is worth noting is that if you add a font to your game that doesn't have the glyphs required by the text you wish to write, then the unicode character 9647 (▯) is used to substitute those missing glyphs when rendering it in the draw event. So if your font doesn't have, for example, the ° symbol, then writing 90° will actually produce 90▯.

Back: Advanced Use Index
Next: Paths

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Paths

This section deals with the GameMaker: Studio path editor.

At some point while creating your games you will need one of your objects to follow a path through a level. Now, this can be done by simply creating an array of positions within the room and then having an instance move between them, but that can be a chore to set up and is difficult to change, test and adapt for different instance. For this reason GameMaker: Studio has path resources and a dedicated path editor.

The basic idea is rather simple - you define a path by drawing it in the path editor, then you can place an action (or code) in the creation event of an object to tell the object to follow that particular path. You can also set the speed to follow the path and a number of other actions relating to the position and orientation of the path within the room. Let's start by looking at the path editor and how that works.

Defining paths

To create a new path resource in your game, choose Create Path from the Resources menu (or right click on the path resource and select Create Path), which will open the following window where you can create a new path (the image shows a path already created): As you can see, most of the path editor is taken up with the a visual representation of the space your path is drawn in, but around the edges there are a number of buttons, tabs and information bars that are there to help you in the task of creating and changing the paths you make.

Path Information

As with all resources in GameMaker: Studio you should give your new path a unique name as this is what will be used to identify it throughout the game you are making, and a good system that a lot of people use is to prefix (or suffix) the resource for easy recognition in code or actions (eg: path_Enemy_1 or PowerUp_path). Once you have named the path, you can start to define it by placing points in the main window on the right. This is simply done by clicking the left mouse button on a point where you want the path to pass through, with a green square signifying the start of the path, a red dot being the current path point, and a blue dot being a normal path point (the path itself is drawn as a yellow line). You can click any point of a path and then drag the mouse to move it around in the editor, although be aware that the green path start position is not directly selectable as it changes position automatically depending on whether the path is smooth or not (more on this further down). These points are added automatically to the point list beneath the path name and you can also click on a point in the list to select it in the main window.

Path Toolbar

At the top of the path editor you can find the tool bar which has a number of buttons that refer to actions in the path editor:

  • Confirm: Clicking this button will close the path editor and save any changes you have made. Beware, as this will not warn you that the path has changed, as clicking the close button would do, but will just save directly any changes you have made.

  • Undo: This is a simple, one level, undo button. By one level, we mean that only the last action performed will be undone.

  • Path Point Actions: These buttons all change the path points in some way, giving you the ability to clear them completely, mirror them and shift them.

  • Path View Actions: You can use these to pan the view of the path around (as the path may be bigger than the visible area in the editor). Note that you can also click and

  • Path Editor Actions: Here you can select the snap resolution for the path points, as well as toggle the grid visibility on or off. The last button permits you to select a room to be drawn as a background which can be very useful for giving you a "feel" for how the path will work in any given game room.

Path Point Control

You can add points to the path using the Add button, which will add a new point to the path, but at the same position as the previous path point created (or at the path start position if none have been created yet). these points can then be moved by clicking and dragging on them (as can all points on the path), or by changing the values presented to you on the left for the X and Y position. you can also set a speed for individual path points by changing the value in the Sp box (default value is 100). The speed value is actually a percentage of the speed at which you make the instance move along the path, so if you start an instance at a speed of 2 (2 pixels per step) along a path and then one of the path points has a Sp value of 50, the instance will reduce speed as it approaches this point to a speed of 1 (50% of the path speed). Equally, you can set the Spd to 150% and the instance will accelerate as it reaches the point. In this way you can create some nice dynamic-looking movement without any code whatsoever!

Beneath the Add button you have Insert and Delete buttons too. If you select a point on your path (either by clicking on it in the editor or by clicking the point list on the left of the editor) and then click on Insert, a new point will be "inserted" into the path at the same position. You can then drag this point to get it to the position you wish. If you click on the Delete button, the point selected will be removed from the path (there is an undo button at the top of the screen should you make a mistake).

Finally, you can specify the connection kind and whether the path should be closed or not (a closed path will connect the last point on the path with the first). The connection kind can be either straight line, or smooth where a straight line connect simply connects the points of a path in a linear basis, with angular changes at each point, while a smooth connection will create a much softer path that may not pass directly through any of the points, but rather take an approximate line, creating nice curves. You can also specify the precision for the curves (default is 4) which can be from 1 to 8 with 8 being the smoothest. The image below shows an example of how these options affect the path:

Info Bar

This bar at the bottom shows the x and y coordinates of the mouse in the path editor, as well as the area of the room visible in the path editor window. The path editor has a center point (0,0) and its coordinate system works the same as for the room editor, in that down is +y, up is -y, right is +x and left is -x, and in this way you can plot your path around these coordinates. This means that it can be useful to know what part of this area you are looking at while designing your path and this is shown by the Area values, with the first set of coordinates being the upper left corner of the current view, and the second set of coordinates being the lower right corner.

Assigning A Path To An Object

To assign a path to an instance of an object, you can use the path actions (covered in the section Actions - Move Actions) or you can use code. When using scripts or pieces of code you have more control over the way the path is executed, and there are a variety of functions that cover basic actions like starting the path (see Reference - Paths), and more complex actions like modifying and changing path points from within the game (see Reference - Changing Paths).

Back: Advanced Use Index
Next: Time Lines

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Timelines

Timelines offer you a way to create and control instances and actions over a set time period.

In most games you will want certain things to happen at certain moments in time. Now, you can try to achieve this by using the alarm events but when things get too complicated this won't work any more, especially as you are limited to only twelve alarms. That's why we have the time line resource.

In a time line you specify which actions must happen at certain moments in game time, and you can use all the actions that are also available for an object in its different events. Once you create a time line you can then assign it to an object, and the instance of that object will then execute the actions at the indicated moments of time when placed or created within a room. Let us explain this with an example:

Assume you want to make a guard and that this guard should move 20 time steps to the left, then 10 upwards, then 20 to the right, then 10 downwards and then finally stop. To achieve this you can make a time line where you start with setting a motion to the left. You would then create moment 20 (a "moment" is just another way of saying "step") and set a motion upward, then at moment 30 a motion to the right, at moment 50 a motion downwards and finally at moment 60 you would stop the motion. Once that is done, you can assign this time line to the guard and the guard will do exactly what you planned. You could even set an alarm in the time line so that it is repeated after a certain length of time and in this way your guard can patrol an area!

You can also use a time line to control your game more globally. Create an invisible controller object, create a time line that at certain moments creates enemies, and then assign it to the controller object. Once you start to work with it you will find out it is a very powerful tool indeed!

Creating A Timeline

To create a time line, choose Create Time Line from the Resources menu, or right click on the time line resource in the resource tree and select Create Time Line or you can just click on the create a time line icon found on the resource toolbar at the top of the main screen. Whatever method you choose will open the following window:

It's very similar to the object properties window as you can specify a name for your time line (like all resources, this should be specific and unique), and with an action list and actions on the right, and there is even a Show Information button that can be used to get an overview of all actions within the time line. However, on the left, instead of an event list we have a moment list. In a time line a moment is the same as a step, so ten moments on your time line are the same as ten steps in your game, and you can insert any number of actions and/or code into one moment and the object that has the time line assigned to it will carry out these actions at the required time. Note that the time line can be started at any time in-game, so moment 0 is just the moment in which the time line starts and not the moment the game or room starts.

The following buttons are available in this window to enable you to add, remove and change moments within the time line resource that you have created:

  • Add. Use this to add a moment to the time line. You must indicate the moment, which is the number of steps since the time line was started. Now you can drag actions to the list as for object events. If you are adding in code actions then these can also be named, as explained in the section on Scripts - Adding Comments and Naming Code Blocks.

  • Change. Use this button to change the time steps for the currently selected moment.

  • Delete. Use this button to delete a moment or a range of moments. You must indicate the time step of the first moment to delete and the last one. All moments in between will be deleted.

  • Clear. Use this button to clear the entire list of moments.

  • Shift. Use this button to shift a range of moment to a new moment. You must indicate the start of the range, the end of the range, and the new time step to which the start of the range must be shifted. When different moments become the same their action lists will be merged.

  • Duplicate. This is almost the same as the shift button but in this case a copy of the moments are made.

  • Spread. Use this button to spread out a range of moments by adding time between them or put them closer together by removing time between them. You specify the start and the end of the range and the percentage for the spread. A percentage of 100 means nothing changes. For values smaller than 100 the moments are moved closer together and for values larger than 100 they are moved further apart. For example if you have moments at timesteps 5, 8, and 12 and you indicate as range 5:12 and a percentage 200, the moments will move to time steps 5, 11, and 19 (the intervals between them have doubled.) When different moments become the same their action lists will be merged.

  • Merge. Use this button to merge a number of moments into a single one. You specify the start and the end of the range and they will all be merged into the start moment.

Please note, that although it is possible to create negative time moments, it is pointless to do so as they will never be executed!

Back: Advanced Use Index
Next: Scripts

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Scripts

Scripts are the way in which GameMaker: Studio permits you to design your own functions.

You can use code in a number of places within GameMaker: Studio, from objects, to rooms and instances, and there are a number of built in functions that make your life easier when programming, however it is often necessary for you to create your own functions to do a specific task, or to condense a large section of code into a more manageable chunk, or even to be able to re-use a particular code block in many different places. That is why GameMaker: Studio gives you the ability to create scripts.

What Is A Script?

Scripts are written using GML (the Game Maker Language, covered in the Reference section), which is the built-in programming language that GameMaker: Studio uses. Once you become more familiar with GameMaker: Studio and want to use it to its fullest extent, it is advisable to start learning to use this language, as it greatly expands your possibilities when creating games.

A script (like any built-in function) can take different input variables, with real, string, boolean and special values like all or noone being accepted, and these input variables are generally called arguments, although they are also referred to as parameters. To execute a script from an object or a time line you can use the Execute Script action , but you can also call it in a code box using the actual script name as if it were a function or even by using the GML function script_execute. If you use the script action you can specify the script you want to execute, together with the up to five arguments, but if you are using the code editor to call a script, you can pass up to sixteen arguments.

Using Scripts

As mentioned above, you can pass a number of arguments to a script, and it will use these to perform the task you have written it for. To understand this better, take, for example, an action (or a code in GML) and think about how it works... you place it in an event and specify a number of parameters and it will make your instance do something. Scripts are exactly the same, with the only difference being that you write them! Not only can you pass arguments into a script, but you can also ask a script to return a value too (using the return keyword), so you can use them to build calculating methods (mathematical methods) or give back an instance id after a complex collision detection or any number of things. Please note, however, that using return effectively ends the script, and so no code after it has been used will be executed, and this means that a certain amount of thought has to go into how your scripts are structured.

Saving and Loading Scripts

You can save and load scripts from *.txt files into GameMaker: Studio and in this way you can create collections of scripts and store them for use in multiple projects. To load a script (or a collection of scripts) into GameMaker: Studio, simply right-click on the scripts resource folder (or any sub-folder that you have created in that section) and select Add Existing Script. This will open the file browser and you can select either a script *.gmx, or a *.txt file. They will then be loaded in to GameMaker: Studio.

For saving scripts it's a similar process, where you right-click on a script (or a script folder) and select Export Selected Script. This will open up a window asking you where to export to, and when you click on "Okay", the script will be saved as a *.txt file, with the name of the file being the same as the name of the script. If you have selected multiple scripts in a folder, they will all be saved, each with the name of the script they correspond to.

Creating A Script

To create a script in your game, choose Create Script from the Resources menu, or right click on the scripts resource in the resource tree and select Create Script, or just click the create script button on the toolbar at the top of the main GameMaker: Studio screen. Whatever method you choose will open the following window: Note: The script editor window and the code editor window for objects have exactly the same functionality. The only difference between them is that the script editor has a name box whereas the code editor has the choice of which instance is to run the code (self, other or object), just like the D'n'D actions.

The Script Editor

When you open the script editor, you should first give your new script a name. This should be something sensible and easy to remember and recognise, and must not start with a number or have any symbols (except the under-bar "_" symbol). The name you give the script is the one you will use later as a function in code. It is also a good idea to write some comments at the start of the script (see the above image) to outline the script arguments and how it should be used, especially if you are going to work as part of a team, or plan on using many scripts in your game.

Once you have done that you can start to write your script using standard GML functions and variables, using the many options along the Toolbar at the top to help you in this process. Here is a brief explanation of what each of the toolbar buttons does:

Confirm

This will close the script editor and save any changes you have made. Be aware that there are no confirmation messages asking if you want to save.

Load A Script From A File

This will open the standard window for loading a script that has previously been saved as a text file. This will replace the existing script with the loaded one.

Save Script

This will save your current script as a *.txt file, ready to be used in another game.

Print Script

This will open a standard windows dialogue where you can select a printer and print out your current script on paper.

Undo

This will undo the last action, and you can repeatedly undo consecutive actions with this button, but note that the number of undos that can be performed is limited to 16.

Redo

If you have used the undo function, you can use this to go back to the state that you undid. This is limited to the number of undos that you have done previously.

Cut

You can use this to "cut" a section of your code out of the script. This code is stored to the clipboard and can then be pasted into another part of the same script, another script resource or even into some other program, independent of GameMaker: Studio.

Copy

This button will copy the currently selected code into the clipboard for use in another place, either the same script, another script or even an alternate program.

Paste

You can use this button to paste whatever text you have previously stored in the clipboard (with cut, or copy) into the current script.

Search And Replace

Clicking this button will open the search/find and replace tab in the script editor. See below for more details.

Check Syntax

This button will toggle on and off the syntax checker of the script editor. When on, any errors in the code syntax will be highlighted in red (default) and a message will be displayed at the bottom of the editor explaining briefly what the problem is. Note that not all aspects can be tested at this stage but the syntax of your script will be tested, together with the existence of functions used.

Auto Complete

When this is switched on, if you pause when typing something an auto-complete window will pop up and you can then use the cursor keys or mouse to navigate to the function that you are looking for. The image below illustrates this:

Keyboard Shortcuts

There are a number of keyboard shortcuts to help you navigate around the script editor, and each one is designed to help you get the most from this powerful tool:

  • By pressing f2 you get the code snippet pop-up, which permits you to select one of the commonly used code methods. You can define your own code snippets if you want to, saving them to the Local App Data directory (ie: C:\Users\MyUserName\AppData\Local\GameMaker-Studio) for future use using the name "snippets.txt". If there are no snippets defined then GameMaker: Studio will copy the defaults from the Roaming directory (ie: C:\Users\MyUserName\AppData\Roaming\GameMaker-Studio). You can edit this file with any text editor, and each snippet is on a separate line (there should be no blank lines). It starts with the name of the snippet (which is what is shown in the menu) followed by the colon (:) followed by the actual snippet of code. Use # for a newline and put the text that needs to be selected first between | symbols. See the examples that are already in the file in the Roaming directory to see how it is set up, and it is strongly recommended that you make a backup of it before you start changing anything, although the base file will be re-installed when you update GameMaker: Studio (but the Local App Data version will remain).

  • You can use f7 and f8 to change the size of the font within the editor.

  • If you press f10 you can toggle on or off the colour coding for your code.

  • Press <CTRL> + F to call up the search, find and replace options (see below).

  • If you are using multiple scripts, then you can press f12 (or click the Middle Mouse Button) when the mouse is over any of the other script names to have it opened in a new window, ready for editing. If no script is selected, then the manual will be opened.

  • You can press <Shift> + f12 (or <Shift> and the Middle Mouse Button) when the mouse is over any selected text to have it open the Search In Scripts window, already populated with the selected text. You can also do this on a function (without selecting it) and the function will be used to populate the search feild of the window.

  • You can use <Ctrl> + Z for undo and <Ctrl> + <Shift> + Z for redo.

  • The arrow keys move you around in the text, and you can use <Ctrl> with the left and right arrow key to move to the beginning of the previous or next word. If you use <Ctrl> with the up and down arrows you also scroll the text.

  • You can hold the <Shift> key and move with the arrow keys to select text.

  • The <Home> key moves the cursor to the beginning of the line and the <End> key to the end of the line, and if you also hold <Ctrl> they move to the start and end of the script. Holding the <Shift> key you can select the text too.

  • Use <TAB> to indent selected lines and <Shift> + <TAB> to unindent selected lines.

  • Hold <Ctrl> with the <Backspace> or <Delete> key to delete until the beginning of the previous or next word.

  • You can force the auto-complete window to appear if you have it switched off in the Scripts Preferences by pressing <Ctrl> + <Space>, and you can cancel it at anytime by pressing <ESC>.

  • You can drag a selection with the mouse. (Use <Ctrl> to copy it.) The new location is immediately shown.

  • You can scroll through the text with the mouse wheel and with <Ctrl> pressed the cursor scrolls with the text. As with previous shortcuts, holding the <Shift> key selects text.

Adding Comments and Naming Code Blocks

Commenting your code is very important for maintaining productivity as it keeps things clear and separates sections of code in such a way that it is obvious what each part does and why it is there. It also means that if you are working in a team then you can leave notes for other members and that they will know exactly what you have done or what a specific section of code is for. Even if you are a solo developer, leaving comments for your code is important, especially if you have to leave the project and come back to it at a later date.

Commenting your code is simple, as you just have to use "//" before any line of text or you can comment out whole paragraphs by using "/* text here */". The following image illustrates a script using both these methods: If you are in the code editor, then you can also give your code box a title by making a comment for the first line using the following format:

///Your Comment Here!

This comment will then be used for the "name" of that codebox (this works for codeboxes added to Timelines too) as illustrated by the following image: If you use make a comment in this way in the script editor, then the comment text will be used as the auto-complete text in the code editor when you type the script. So, in the example script image above above we have the script "MovePlayer", and it starts with a "///" comment, which would then show in the code editor like this:

Script Tabs

When creating larger games, you will often require many, many scripts and this can cause a certain amount of "clutter" in the resource tree, and it can be hard to keep track or organise the scripts in a coherent fashion. To help with this, the Script Editor has child scripts available to you in the form of tabs. So, say you have a player object with a create script, a movement script, a collision script and a draw script. Instead of placing them all in the resource tree, you would have a parent script, with its name being the one shown in the resource tree, and various child scripts. These child scripts are no different to any other scripts in your game, and will work as they should. However they will not appear in the resource tree, and to access them you must first open the parent script. To create a new child script you simply click on the empty tab that is always to the right of the current tab (if you can't see this, then try scrolling the rest of the tabs using the arrows in the top right corner). This will create the new script which you should name, and it will be stored within the parent script when you close and save the script editor. You can also delete these scripts easily by clicking on the "cross" icon that you can see on all the script tabs.

Colour Coding

As you might have noticed, parts of the script text are coloured. The script editor "knows" about existing objects, built-in variables and functions, etc. and colour codes them accordingly. colour-coding helps a lot in avoiding mistakes, in particular, you see immediately if you have misspelled some name or use a keyword as a variable, or have a syntax error. However, if you don't like the colour coding, in the Preferences you can switch it on and off (you can also use F10) as well as customise the colours that are used.

Search, Find And Replace

When working with code, it is common that you will want to find some piece you have written in a large section and then replace it something different, or simply see at a glance where a line of code lies within the function. To this end, the GameMaker: Studio script editor has a search, find and replace function that can be accessed by pressing the Search button in the toolbar. This will open up a panel on the right of the code window which looks as follows: You can type the find string at the top (note that in the code all occurrences of the find string are immediately shown with a yellow background), and you can indicate whether the search must be case sensitive, which is normally what you want as variable and function names in GML are also case sensitive, and whether you want to only search for whole words. Note that the editor remembers your most recent searches, and you can click on the drop down button to call them up and re-select them. With the buttons underneath the search string input you can now move to the previous, next, first, and last occurrence of the find string, and this string will be selected in the text so that you can edit it.

You can also use this panel to replace anything that you have previously searched for by simply typing in the new code that is to be used and pressing one of the buttons that are highlighted underneath. Now you can use the buttons to replace the previously selected, the next one to be selected, the first, the last or all occurrences of the code searched for. Note that since your scripts can be spread over multiple tabs in the same category, you are also provided with a Replace in all tabs option which, when checked, will use the search and replace terms to parse all the scripts in all tabs for that category, rather only the one currently selected.

Bookmarks

The script editor permits you to bookmark a script so that you can open it directly from the IDE using a key combination rather than having to click through multiple windows and icons. This is a very handy way to track script changes while testing your game, and is activated simply by moving the cursor to the line of the script you want to bookmark and the holding <Shift> + <Control> + <NUM>, where <NUM> is a number from 1 to 9 on the keyboard. The script editor will now show your bookmark beside the code in the editor. To open the bookmarked script again at any time, you should use the keyboard combination <Control> + <NUM>, where <NUM> is the number key of the bookmark.

Back: Advanced Use Index
Next: Shaders

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Configurations

Here you can find all the information on Configurations.

Due to the demands of cross platform development and the need for one product to be available and customised for different clients and/or devices, GameMaker: Studio includes a configuration manager to make things simpler. Using this system, you can quickly switch between different splash screens, icons and included files and test or export only those that are relevant to the target platform or client at any time, all from the same base code.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

To set up your configurations it is recommended that you first prepare a "default" config by incorporating all the configurable assets for the project into GameMaker: Studio, including icons and splash screens (done through the Global Game Settings), included files and any extensions that you may need. Please note that with the included files and extensions, you can select a target platform for them, and that should also be done at this point so that when you create individual configurations it is simply a question of un-ticking those that you don't need.

Once you have set up the default configuration, at the top of the GUI you will see a button marked "Manage". If you click on this it will bring up the Configuration Manager window, as shown below: Here is where you create new base configurations and give them a name (these configurations are project specific). You can remove configurations and rename them (note that the "default" configuration cannot ever be removed or renamed) as well as create new ones by clicking on the "+" button. If you choose to make a new one, the following dialogue will be shown: at the bottom which will bring up the following dialogue: Here you are prompted to choose a new name for your new configuration and a previous config on which to base this (usually the default one, but in some special cases you may need to choose one of your other configs). Clicking okay will return you to the manager where you can then create more custom configs or exit back to GameMaker: Studio.

Now that you have created your configurations you have to go ahead and customise them so that they actually do change the configurations! For that you should now review the Global Game Settings for each target platform and add or remove icons, splash screens and any other information that is relevant to the configuration, as well as set up the Texture Groups for each configuration. Then you should go through the included files and extensions and tick (or untick) those that are needed too, and if you have set texture groups for each configuration you will also need to go through all the graphics assets (sprites and backgrounds) and re-assign them. Every change you make to these settings will be remembered by the configuration manager and recalled whenever you change configurations.

Back: Advanced Use Index
Next: Source Control

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Importing Resources

This allows you to copy resources from one game to another.

In previous versions of GameMaker it was a complicated business to import and export files from one project to another, and if you weren't careful you could end up with a corrupt game or loss of data. Thankfully, that has all changed with GameMaker: Studio as the *.gmx format makes sharing resources between projects a simple and painless procedure.

When you save your project, GameMaker: Studio creates a number of special files in the game directory (this can be found easily through the drop down Help Menu) with the extension *.gmx and a sub-extension that indicates the resource type (eg: a room resource would be called game_room.room.gmx). These *.gmx files contain all the information that GameMaker: Studio needs to define the object, sound or whatever resource, and you can add these into a new project simply by right clicking on the resource tree and selecting Add Existing Resource, which will open a standard file selector where you can browse to the file you wish to import.

You can select multiple files in this way too and they will all be imported into GameMaker: Studio, but they must all have the same sub-extension (ie: you can load ten *.object.gmx at once, but not a *.sound.gmx and a couple of *.sprite.gmx). It should also be noted, that if you add an object resource into your game, if it has a sprite associated with it this sprite will not be imported. You have to make sure that any sprites your object needs have been imported from their appropriate *.sprite.gmx. The same goes for any rooms that you import, as they will be missing the objects that they contained if you have not imported them previously. So, it is always best to import sprites, sound, fonts and other resources before objects, and those you should import before rooms.

Back: Advanced Use Index
Next: Configurations

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Shaders

A shader is a set of two short scripts that permit you to tap directly into the graphics pipeline and change how things are drawn.

Shaders are a very powerful tool that can be used to manipulate the graphics that your game renders to the screen, permitting incredibly fast effects that can range from, for example, adding a subtle colour hue to a sprite, right up to full screen distortion effects.

What Is A Shader?

A shader is basically a two-part program that runs directly on the graphics card itself, making it very fast since the GPU is doing all the work and freeing up CPU cycles for your game code.

The full shader is comprised of a vertex shader program, and a fragment shader program (also known as a pixel shader). Both of these tiny programs work together in order to manipulate what the graphics card renders to the screen. This then permits you to manipulate in real time, the position, colour and alpha values that are actually rendered into the display buffer.

A complete overview of how shaders really work and what place they have in the graphics pipeline is outside the scope of this manual, but YoYo Games have produced a number of Tech Blog articles which give an excellent base to start from:

  1. Shaders Part 1
  2. Shaders Part 2
  3. Shaders Part 3
  4. Shaders Part 4

The Shader Editor

The shader editor has the exact same functionality as the Script Editor, with auto-complete, search, print, etc... as well as all the same keyboard shortcuts. However, please note that there is no syntax checking, due to the code being written using the specific shader language and not GML. The code editor itself is split into two sections, with each one being available from tabs at the top. This is because you cannot create a shader without both parts. Even if you wish to only use the fragment shader you will have to have created a "pass through" vertex shader (by default any new shader being created will have a vertex and fragment pass through shader already coded for you).

The shader program itself is written in a shader language with the default, cross platform choice being GLSL ES. Using this language guarantees that your game will work correctly on all platforms that shaders are available on, but you can also choose to use one of three other languages if you are only targeting a specific platform. The available languages and their respective targets are shown in the table below:

Shader Language | Target Platform
GLSL ES | All targets
HLSL9 | Windows 32 bit
HLSL11 | UWP, XboxOne
GLSL | Mac and Ubuntu (Linux)

It is worth noting that you can use GLSL ES shaders on the HTML5 target platform but you must have enabled WebGL in the HTML5 Global Game Settings otherwise it will not work.

For further details on the shader functions and how they can be used in GameMaker: Studio please see the section Reference: Shaders.

NOTE: This manual will not cover any of the Open GL shader functions and variables, unless they are special ones that exist ONLY in GameMaker: Studio (which can be found here. For a complete overview of the available GLSL ES functions and variables please see the OpenGL ES Shading Language (GLSL ES) Reference Pages.

Back: Advanced Use Index
Next: Constants

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Macros

This section outlines how to define macros that you can then use in actions, scripts and code.

A macro is, as the name implies, something that can hold a constant value (real, or boolean) or a string, or an expression. This is different to a variable in that it can't be changed once defined, although it is global in scope as all instances in all rooms can use it, and it will always be the same value unless you use a GML function as the value. There are a number of built-in constants within GameMaker: Studio, like the vk_ ones for the keyboard or the c_ ones that hold different colours, but you can also define your own constants and function macros to be used in your games too.

To define macros you chose Define Macro from the drop down Resources menu at the top of the main window (or click on the resource tree icons, as explained below) and the following window will open: The main part of this window is take up with the list of macros, and will start off empty, ready for you to create your own. To do this you would click on the button marked Add at the bottom left of the window, which will then create a new, empty, macro with the Name section highlighted. You must give all your macros a name, and as with all things in GameMaker: Studio this name must be unique and it is recommended that you distinguish it in some way from other variables, for example, by using all capitals, or by using a suffix or prefix. Note, that you cannot use any symbols except the under-bar (_) and the macro cannot start with a number.

Once you have named your new macro you must give it a value. This value can be numeric, a function or a string. For a string it must be wrapped in quotes ("") and if it is a function, it cannot make reference to anything in the game (the current room, instances, or scripts etc...) as the macros are initialised before everything else, but it can however use resources like sprites and objects.

When you have defined a few macros you can use the buttons at the bottom of the window to change them around and add, insert or delete them. Add will add one at the end of the list, Insert will insert the next macro above the current one, and delete will delete the current one. You may also press Clear to clear the whole list of macros, which will open a prompt to ask if you are sure you really want to do that before deleting the whole list. beside these button are two labelled Up and Down which simply move the macros up and down the list, and beside those is the sort button which will put the macros into alphabetical order, with the ones starting with "A" at the top.

Finally, there are two buttons marked Load and Save. With these, you can load into your project macros that you have previously defined in an external editor, or that you have saved from a previous game. If you have already defined macros when you load some from a file, the new ones will be appended on at the end of the list. A saved macro list is stored in a simple *.txt file and can easily be edited and added to by any application that reads these files (Notepad++, for example). You can even pre-define your own text file with a set of macros to be loaded into GameMaker: Studio as the format is simply: NAME = VALUE.

Expressions

It is worth noting that when using an expression in a macro, if this contains a function then no constant value can be created for it, and it will be evaluated every time the macro is called. For example, you could have the following macro:

myran : irandom(100)

Now every time you call the macro myran it will return a different random number. If the expression can be evaluated to a single value or string, then the macro will function like a constant, for example:

mynumb : "10"
myname : "Hamish"
myconst : mynumb + myname

As you can see in the above example the last macro is an expression using the previously created two macros. This will be evaluated once on startup and a constant value returned for it.

The Resource Tree

Macro are included as part of the resource tree on the left of the GameMaker: Studio IDE. When you create a new game, you will have two sets of macros - All Configurations and Default. Macro created in "All Configurations" will be available to you no matter what configuration you have chosen (see the section on Configurations for more information), and you can then add configuration-specific ones to any other lists that you will have, with each new configuration creating a new macros list.

Back: Advanced Use Index
Next: Including Files

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Debugging

This section outlines the debug tool and how to correct and detect errors in your game.

GameMaker: Studio has a built-in programming language called GML, and once you become more familiar with how GameMaker works, you will want to use it to its fullest extent, meaning that you will need to program aspects of your game in this language.

However, when programming code it can be very easy to make mistakes - using the wrong variables, passing the wrong arguments, or using the wrong functions - which are not always detected by the syntax checker that is included with the script editor (for more information on the script editor see Scripts). This means that these mistakes will only become apparent when you actually run your game, and even then it can sometimes be difficult to know exactly what is going wrong! It can therefore be of vital importance to know how your game is performing on the chosen device, as well as see what instances are in the room, what global variables have been created and a whole host of other details.

Now, you can check a lot of these things yourself by adding in "debug code" to your games to display on-screen the information you require, or that shows messages when there is an error, but this is often a lot of work and if you aren't sure where the problem is in the first place then it can be a time consuming case of trial and error to track down your bug. For that, GameMaker: Studio has a special run mode called Debug Mode which will start the Debug Module, and there is also a comprehensive error reporting system which displays messages at run time to help you track down any problems with your game.

Error Reporting

When an error occurs during the execution of a script this is reported with an onscreen message, much like the one shown below: Most error messages follow the same outline, with a message stating the type of error, the instance and event in which the error was encountered, then a series of compiler details that explain the error in a lot more depth and, finally, a list of all the declared global, instance and local variables in your game at that point. At the very bottom is the Abort button which will abort the game, as well as the Copy button (which copies the error into the clipboard) and the Clear button which clears the error messages from the window. The information provided by the error reporting is very important as it detects and reports the large, syntax related bugs that are going to cause your finished game to crash, but it won't report more subtle bugs, nor does it give feedback on performance... for that you need to use the Debug Mode.

Apart from these compile errors, you can sometimes get compiler errors. These will be shown (where possible) in a separate window, with a list of the possible problems. These types of errors are more general than compiler errors and may be due to some subtle error in the game.

You can find further information on the different compiler errors and runner errors that are shown from here.

Debug Mode

If you need to check things more carefully, you can run the game in debug mode. When you do, the Debug Module will open along with your game. This module permits you to monitor how everything is working in your game, from the global performance, right down to the values of individual variables in individual instances. You can find out further information about the Debug Module and it's possibilities and how to use it from the following page:

  1. The Debug Module

Checking Performance

When running a game for debugging, you can also see how your game performs and get an overview of how everything is performing by using the Profile option in the Debug Module. This will give very detailed information on how a game is performing and how long it takes to perform specific function calls or events (see the section on Profiling for further details). However this requires that the debug module is running which may not be what you want, especially if you wish to test final executables on devices etc...

In these cases, and as a compliment to the profiler too, you can display the debug bar in your game, which will display much memory, CPU power and GPU power your game is using.

This Debug Bar shows in a helpful graphic of CPU/GPU usage in the actual game window itself, and this can be toggled on and off in your game using the function show_debug_overlay(). This bar is split into sections, with each section being 1/60th of a second. As you can see from the image below, the bar is made up of various colours, with each one signifying a different aspect of the games performance, where the larger the bar, the more time that aspect requires and the larger the performance hit from it:

  • Green - Input / Output processing (ie: keyboard, mouse, gamepad, networking etc...)
  • Red - The update speed of the step event
  • Yellow - The time required for the draw event
  • Orange - Debug update time, which is only normally visible when you use the debug module
  • White - GPU left over time, which is the time spent waiting for the GPU to finish the rendering of the frame before the next one can start
  • Cyan - The text rendering time
  • Grey - The time required to clear screen each draw step
  • Dark Red - The GPU flush, which is how long the GPU takes to clear images from memory

Apart from the coloured bars, there are also a few values at the top. These values represent the following:

  • FPS - This is the "Frames per Second" of your game, and basically shows how fast your game is running. This value is not clamped to the room speed of your game, and so shows you how much "overhead" you have to play with. The larger this value compared to your room speed, the smoother your game will run and the more overhead you have for adding further things. Note that this value may vary a lot during a session, but when you close your game, the compiler window within GameMaker: Studio will show you the minimum and maximum as well as the average values for this (note that the minimum value can be negative! this is not a bug, but due to the startup times and the way that the game is processed when initialised).

  • Texture Swaps - This number shows how many times your game is swapping textures per game tick (the time it takes GameMaker: Studio to run all events is a game tick, and the number of game ticks per second is set by the room speed). Textures (sprites and backgrounds) are stored on texture pages, and if you have a lot of image assets in your game, then GameMaker: Studio has to swap between texture pages to draw them all, therefore if this value is high (over 15-20, for example) you really should look into ways to optimise this as it will affect the performance of your game.

  • Vertex Batches - This is how many times the game is sending off texture batches to the GPU per game tick, and (as with Texture Swaps) you want this to be as low as possible. Texture batches, are basically bundles of data that are sent all at once to the GPU for rendering. The batch is "broken" when you change a font, a colour, a blend mode, or any other draw status that affects how things are drawn on a global scale, so you should try to limit these things to as few objects as possible since a high number of batches will adversely affect your games performance.

NOTE: texture swaps and vertex batches will never be zero and will normally show values of 2 or 3, since even with an empty room an no objects GameMaker: Studio still has to draw and batch things.

With these tools you can see how well your game is performing and what areas need "tweaked" to increase this performance. You can find out more information on performance issues and ways to optimise your game on the YoYo Games Helpdesk - Optimising Your Games.

Clearing the Cache

GameMaker: Studio has an asset compiler cache which stores sprites, sounds, object data, etc... between builds of your game. This greatly increases build time as each asset only has to be re-created only when it has changed. However, this cache can become "stale" and odd behaviour can creep into your games, like the wrong sound playing when something happens, or graphics becoming corrupted. When this happens it's time to clear the asset compiler cache using the "broom" icon at the top of the screen: This will clear all cached files and the next test run or final build will recreate all the files for your game from scratch. Note that you should generally do this anyway every few builds, and always before building a final executable package.

Command Line Parameters

When creating games it is important that you play test the executable file to make sure that the final compile is correct and has no unforeseen errors or differences. However creating an executable means that since you have no access to the debug console - nor to the compiler window - it can be difficult to pin down and debug any problems that you may find. However there is a fix for this, and that is to use command line parameters to set certain properties when the executable version of the game is run, in turn permitting you to create output log files and test other special situations.

NOTE: This is available on the standard Windows target module only.

To get this working you must first create a Windows executable of your game and have it installed on your test machine. Once you have that done, you need to create a Shortcut to the game on the desktop. This is where we will add in the parameters to be passed to the *.exe (to create a shortcut, right click the game executable and then select Send to > Desktop (create shortcut)) .

Once you have made your shortcut you can then use any of the following parameters in the target path:

  • -noaudio: This switches off all audio in your game, no matter whether you are using the legacy sound functions or the new audio ones.

  • -inawindow: Forces the game to start in a window, even when set to run in fullscreen mode.

  • -output <filename>: sends console output to the filename

  • -debugoutput <filename>: sends debug messages and console output to the filename

  • -software: Will force the game to use Software Vertex Processing instead of hardware for rendering the game graphics. This is especially useful for those PCs that are using an on-board Intel GFX chipset or show display issues on older machines.

  • -intel: This will switch on a fix for bad Intel drivers, no matter what GPU is being used. This work around for those bad drivers will slow things down, giving a noticeable performance hit for your game, so if you do not need the fix do not use it.

  • -vanillaGFX: Using this switches off any check for driver manufacturer, and can be very useful for testing your game "as is".

It's worth noting that the <filename> in -output and -debugoutput can be the same one if desired, as the file is opened and closed on each write.

You should now go to where you created the shortcut to the game executable, and then right click on it and select Properties: Command Line Shortcut This will open a window similar to the one above. Here you can add into the Target path your command line. Simply scroll along to the end of the given path, add a space, then the parameter string. So, for example, to create a debug file output you would have:

D:\Users\Me\GameMaker\CustomLoadBar-Default-1.0.0.0\CustomLoadBar.exe -debugoutput debug.txt

This will now create a file called "debug.txt" in the same location as the executable (not the shortcut location, but where the game is installed) with debug and compiler information from your finished game. Click on "OK" and then use the shortcut to run your game to have it use these parameters and help with your debugging.

A/B Testing Using The Command Line

The YoYo runner also benefits from a special command line parameter:

  • -game <filename>: loads the given game file

Why would you use this? Well, normally you wouldn't, but if you wish to have more than one version of your game running at a time it can be done using this, making A/B comparative tests far easier. With this method you could focus test with someone else or, as the designer, get a better feel for things by doing side-by-side tests.

To set this up, you will need to know a couple of things beforehand. To start with you will need the path to the Runner itself. This can be found in the Appdata Roaming folder, using the following in Explorer:

%appdata%/GameMaker_Studio/

You will also need the path to the <yourgame>.win file, as this is what we are going to point the runner to. The easiest way to find this is to go to the Temp folder and just search for *.win, as that will show you all those available and you can simply pick that which you need to get the full path from.

Now, we could create a shortcut to the runner like we did for the exe, and then change the parameters as necessary, but that means having to open and edit it between tests, which defeats the purpose of our using this functionality for side-by-side testing. Instead we are going to create a couple of tiny "batch" files to handle this.

To do this, first create a new text document on your desktop and open it in Notepad. Add the following:

START %appdata%\GameMaker-Studio\Runner.exe -game <LOCAL TEMP PATH>\<GAMENAME>.win

You need to to set the temp path to point to your game *.win file, and then save this as "GM_Test_1.bat" to your desktop (be aware that Notepad will save automatically as a *.txt file unless you choose "all files" from the save dialogue options). An example of how your final command should look would be:

START %appdata%\GameMaker-Studio\Runner.exe -game D:\Users\Me\AppData\Local\Temp\gm_ttt_44657\Delve_Pt6.win

Now, create another text file and add the same line, only this time you point it to the path for the second version of the game that you want to do side-by-side testing with, and you would save this as "GM_Test_2.bat". You can double click either of them to bring up the different versions of your game, and having them as batch files means that you can easily open them again to edit them and change the game being tested.

Back: Advanced Use Index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Profiling

This section explains how to use the Profile tab in the Debug Module.

The Debug Module permits you to step through your code and find any issues with the code base, but sometimes you need to check for subtler details in order to properly optimise your games. The Profile option helps to do just that by giving you a performance overview, showing the time takes to call functions, scripts, and even how long it took a specific event to complete.

Profile Controls

As you can see form the image above, you set the Profile as a window in the Debug Module, and has a button for enabling/disabling profiling, the number of steps that have been profiled, as well as a two sections which you can use to display the information in different ways.

Clicking the enable/disable button will switch profiling on or off for the game being debugged, while the value next to it shows the total number of steps that have been profiled. Beside that you can also see either the total time taken for the profile, or the average time taken per step. Which value you view will depend on the button for selecting the format, which also changes the way that the Time and Calls data is displayed, with "Total" being the total number of calls made to the function, script or event and the total time taken (times are in microseconds) over the course of the profile. Setting this to "Average" will make these columns show the average time taken per step for each function, script or event, and the average number of times that it was called. You can also click the "Run Game At Maximum Room Speed" button to force the debugger to remove the room speed clamp and try to run the game at the real FPS.

The other two options are for controlling what exactly you are profiling and the data that is shown. The first option is for selecting how to view the data, and you can choose from the following:

  • Tree - This will show the profile from the top down (more or less the same as the callstack hierarchy) so it will show the event, then the script and then any functions used. Note that you can double click on any of the entries to have it open in the Source debug window if you have one. If you see a (+) icon beside a name then there are further script or function calls within that section, and clicking the (+) will expand the tree to show them.

  • Bottom Up - Contrary to the tree view, showing things from the bottom up will show all the functions and scripts individually, and clicking on the (+) will expand to show what actually called them.

The second option is for selecting what data is shown, whether it should be the event and code data, the engine data, or both. If you choose "GML", then you will get the events, functions and codes being called each step while the "Engine" view will only show the engine calls required by the game, enabling you to see any bottlenecks in the way that your game is handling things. If you select both, then both sets of data will be displayed, and the "Engine" data will be coloured differently to help you differentiate it from the functions.

Profile Data

The profile data is shown in four columns, and clicking on any of them will sort the data according to the column criteria.

  • Name - This is the name of the event, script or function being called, and may have a (+) beside it to denote further calls to it or from it (depending on the view you have selected). You can double click on any of the names to have it open the code block or script within the Source window, assuming you have one open. Clicking this column will sort the names in alphabetical order.

  • Time - This will show either the total time that a function (or script or event) has taken while profiling, or the average time that it has taken each step to be called (depending on the view option selected) and it is displayed in microseconds.

  • Calls - Here you can see either the total number of calls to the given event, function or script, or the average number of calls to it in a single step (again, depending on the view options selected).

  • Step% - The value shown here is the overall percentage of a single step that the call has taken.

Exporting Data

You can export the profile data at any time by right clicking on the window and selecting the "Export to file" option. This will write the current view (after expanding all the nodes) in .csv format, which you can then load into any spreadsheet, like Excel for example.

Back: The Debug Module
Next : Debugging

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Debug Module

This section explains how to use the Debug Module to find and correct errors or issues in your games.

The Debug Module is a powerful tool for checking your game, and is especially useful for tracking down errors and bugs in your code, as well as checking that scripts are run when they should be, and that variables and arrays contain the values you expect etc... You can start the Debug Module by running your game from GameMaker: Studio using the red"Play" button at the top of the IDE, or by going to the Run menu and selecting "Run in Debug Mode".

NOTE: You may be prompted by Windows Firewall (or any other firewall program that you run) to create a security exception for this module. You must do this otherwise it will not work correctly. This is due to the way the Debug Module works and is essential for debugging mobile platforms.

NOTE: On devices the debug module will connect over WiFi automatically, however should you have any configuration issues, you will need to go to the Preferences and switch on "Manual IP Entry". This will then let you specify the IP to connect to manually, which will then be saved for future use.

The actual Debug Module window will look something like this:

At the top you have four drop down menus:

  • File: Here you can attempt to reconnect the debug module to your game should the connection be lost, or exit the debug module (which will not exit your game, only the module).

  • Window: This menu contains options for the various sub-windows that you can create for debugging. You can delete them (clear all of them so that you can create a new watch layout), or save the current layout or load a previously saved layout.

  • Debug: From here you can pause or play the game being debugged, or you can toggle a breakpoint on or off.

  • Help: Opens up your browser, taking you to the YoYo Games Helpdesk.

Apart from these drop down menus, you also have a series of buttons along the top with which you can control certain aspects of your game and the Debug Modules interaction with it. These buttons are:

Play: This starts the game again after it has been paused (hotkey = f5).

Pause: Pauses the game (hotkey = f6).

Restart: Restarts the game.

Step In: Step into a code block or script (hotkey = f11).

Step Over: Step over a code block or script (hotkey = f10).

Step Out: Step out of a code block or script (hotkey = <SHIFT> + f11).

RealTime Updates: Turn on or off (it is off by default) real time updates for the debug information.

The first three buttons are used to control your game, permitting you to start, stop and pause it at any time. When the game is paused, you can then use the next three buttons for "stepping" through your code. This simply means that you can tell your game to run the current line of code, then step onto the next one, permitting you to run through your entire game one line of code at a time should you wish. Normally you would simply use the Step In button to do this, but you also have one for stepping over code and one for stepping out of the code. Stepping over is useful when you have large scripts to run through, as clicking this will run the whole script or code block as a single step and stop on the next line afterwards, while stepping out will take you out of a script (they will run, but all at once) and stop on the next step. The final icon permits the debug window to update its data in real time, so you can see how variables change or instances are created and destroyed as it happens. Note that this may affect the games performance and that not all information is available in real time. For example, the Render State watch cannot be viewed in real time.

Watches

The whole idea of the Debug Module is to permit you to "watch" every detail of your game. This is done using "watch windows" which are opened on the right hand side of the debug module. To open a new watch, simply click on an empty area (which should show the text "select window type") or right-click on the top window bar and choose a new "Type".

NOTE: Many of the watch windows (like Global, Local or Watches) will not update while the game is running, and will require that you pause the game or set a breakpoint before they are updated.

You can also split the main watch area into multiple windows using the "Split" option from the top window bar, permitting you to organise the layout to suit your needs (and these layouts can also be saved through the "Window" drop down menu). The type of window that you choose to open will depend on what it is that you wish to watch, with the following options available:

Source

The source window is where you can see the source code for your game, and you can have multiple tabs open in this window, with each tab showing the code from a different instance or event. If you do a right click beside a line of code you can add a Breakpoint to the code (see below for more details on Breakpoints), and doing so again will remove it (you can also use the key <f9>, or the toggle option from the "Debug" drop down menu. If you have this window open, you can also double-click on an event in any instance from the resource tree and it's code will be shown in a new tab.

Globals

The Globals window will show a list of all the currently declared global variables and their values. If you right-click on a value you can set its type (see Data Types, below) to see details of data structures.

Locals

The Locals window shows the current step properties, which includes the name of the current event (or script) being run, the position within the event (PC is "program counter"), the "self" instance running the code block, and the "other" instance in the event. This last part is only ever valid when the event is a collision event or there is a with used in the code. If the instance is in collision, "other" will show the other instance (and it's variables) in the collision, but if it is a with then the "Self" instance becomes that which is running the code, while "Other" is then the instance that actually contains the with. At all other times, "other" will simply show the same data as "Self". After all this information, you will then find a list of all local variables that are currently declared for the code block being stepped through. If you right-click on a value you can set its type (see Data Types, below) to see details of data structures.

Watches

This window is for you to add a specific variable that you want to keep track of. This can be a global or instance scope variable, a built in variable or even an array or data structure. If the the instance code being stepped through has the watched variable it will be shown here, meaning you can easily keep track of a value without having to search for it in the Locals or Globals windows. If you right-click on a value you can set its type (see Data Types, below), delete it or clear all watches from the window. You can also change some of the values for the variables shown by simply double-clicking on the value and giving it a new one. Note that you cannot re-asign arrays or data structures in this way, but you can change some of their contents (you cannot change the "key" values in maps, nor the priority value for priority queues).

Instance

As the name implies, this window will show all instance variables, local variables and built in variables associated with the instance currently being stepped through in the Source window (if an instance is being referenced using the keyword "other" or the with statement, then this window will show that instances properties instead).

Output

This window simply shows the output of the compiler (as shown in the main IDE compiler window). If you right-click on the window you can clear it or copy its contents to the clipboard.

All Instances

Should you need to see all instances that are currently in the room, you can select this window and they will be listed. You can also see the state of any built in or instance variables that they have, and you can right-click on a value to set its type (see Data Types, below)

Selected Instance

This window is for when you select an instance from your game. This is done by simply pausing the game and then clicking on any visible instance within the game window. The instance found beneath the mouse cursor will then have its information displayed in the Selected Instance window, where you can see it's built in and instance variables, the same as for the Instances window.

Call Stack

This window will display the current call stack of events, as well as the line number for the code being stepped through.

Buffer

If you have initialised any buffers in your game, then this window will show you the buffer data. You can select any buffer created by setting the Buffer ID value, which will start at 0 for the first buffer created in your game, and increment by 1 for each consecutive buffer. If you right-click on the data window, you can select how the data is displayed, setting the alignment and type, and you can also set how the data is laid out from the Columns box. There is a drop-down window here where you can select from a default list of layouts, or you can click the box and input your own value. Note that for large buffers, scrolling down through the data will require that you scroll, then release the mouse button for the Debug Module to fetch and display the required data.

Profile

This window is where you can see the current system profile for the game being tested where you can check everything in your game from whole events to individual function calls to see how they are performing and spot any trouble areas or bottlenecks. For further information on profiling see the section below:

  1. Profiling

Graph

The Graph window shows you a graphic display of how your game is performing. You can see the memory use, or how the GML is performing on the CPU, or a combination of both. You can change views easily by clicking the drop-down tab on the right and selecting the option you require.

Render States

This watch shows you all the information available for the state of the current frame being rendered, like the draw alpha or fill colour. this cannot be updated in real time so you will need to pause the game to get and update the frame details.

Surfaces/Textures

This watch enables you to see exactly what is being drawn to any surfaces you have in your game (including the application surface) as well as see the texture pages that are in memory. You can select from textures or surfaces from the top of the watch, and then select the texture or surface ID to have it displayed in the window.

It is important to note that while the game is running it doesn't update the debug windows with variable values and other details by default, therefore you must first use the "Pause" button in the Debug Module to pause the game before Locals, Globals and other data will be available, or enable real-time updating from the icons at the top. The only exception to this rule is the Profile view, which updates in real time when enabled independently of the real-time switch, as it has its own on/off button.

Data Types

When you are watching a variable in any of the windows, it can be one of multiple data-types. However, due to the way that GameMaker: Studio stores certain things, the Debug Module does not always know just what the variable holds. This is because the internal ID values for data structures or instances are integers and so the Debug Module doesn't always know if the integer value being stored in a variable is for a data structure or an instance or is simply an integer value. For that reason, you can right-click on any variable value and get a pop-up window that lists the available data-types that this variable could be. Strings and arrays do not permit this option, and it is worth noting that even if a data structure is stored in an instance variable, its ID number is global, so if you have four instances and each one creates a ds_list (for example), each list will have an id from 0 to 3, and they won't all be 0.

Once you have selected your data-type, the variable will then show the entries in the structure simply by clicking the small "+" next to its name. This will expand the structures contents, and, in the case of the "Watches" window, permit you to modify them too.

Breakpoints

A breakpoint is a place in your game code that you wish it to stop at so you can see what's going on. With the Debug Module, you can set these at any time and in any code block, and you can also set them from the GameMaker: Studio IDE. When making your game, they can be added at any time using f9 (or using the right mouse button and selecting "toggle breakpoint"), either on an action in the object window, or on a line in a code editor window. Now, when you run your game in debug mode it will pause at the point (or points) that you have defined. Breakpoints set from the IDE are saved along with your game and persist over various runs, however if you add a breakpoint to your code in the Debug Module, this will be lost after the module is closed, or a new test run started.

Back: Debugging
Next : Profiling

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Extension Packages

Extension packages extend the possibilities of GameMaker: Studio.

An extension package (GMEZ) can be used to add a number of additional functions and constants to the GameMaker Language (GML). These functions can link your game to external SDKs or source code written in other languages (like Java for Android, for example), as well as native GML. You can add extension packages to a project by simply right-clicking the Extensions folder in the resource tree and selecting "Import Extension". If you are using legacy GEX extensions from previous versions of GameMaker, you can access them from the Help menu at the top of the main window (see The Help Menu).

For more information on Extension Packages please see:

  1. Using Extensions
  2. Creating Extensions
  3. Legacy Extensions
  4. Proxy Files

YYG Extension Packages

Previous versions of GameMaker: Studio had a lot of 3rd party functionality built in, but this was inefficient and difficult to maintain so current versions have adopted the use of extensions packages to add third party support to your games. This means that you can add only those extra functions that you require and that you can even adapt and edit them to suit your specific needs. You can get these extension packages from the Demos on the GameMaker: Studio welcome screen when you start up the program, and you can find further information about them from the following YoYo Games Knowledge Base articles:

  1. Advertising And Analytics

These extensions come with a demo and a help file that explains how to use them, and as such are not covered in the manual.

Back: Advanced Use Index
Next: Importing Resources

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Android Extensions

This section details the Android tab in the Extension Package Properties.

When you create a new extension for your game, you are presented with the Extension Package Properties window from where you can set the basic properties for the extension (see the page Creating Extensions for further details). If your extension is for Android, you would tick that option too, and clicking on the Next button will open the following tab: Here you give the following details:

  • ClassName: Your extension can have multiple classes, with each class having its own functions and constants, so you should give it a name that reflects its purpose

With that done, you will then need to add in any extra permissions that your extension requires. What these permissions are will depend entirely on the use that the extension has, and so you should check the documentation supplied by Google for the Android platform, or, if you are using a third party SDK, the documentation that comes with the SDK.

You can also set any extra code to be injected (added) to the Android Manifest XML file when your game is built for testing or final release. Make sure to revise this (and your permissions) carefully before submitting any games to the store, as incorrect settings will cause your game to be failed for submission.

Once you have set this up correctly, you will need to add the required files for your extension package to work. To do this you need to right click on the extension and select either Add Android SDK or Add Android Source and then browse to the files you wish to add. Added files will be stored in the AndroidSource directory along with your extension. You can open this location at any time by right clicking on the extension and selecting Open Extension Directory.

Adding Functions and Constants

To add your functions and constants to the extension package, you must now right click on the extension again and select Add Placeholder. This will create a placeholder file which "links" the functions you want to add to the extension itself. Once you have added your placeholder, you can then follow the instructions given on the page Creating Extensions to add the functions and constants it requires. Don't forget to set the export targets for the functions by right-clicking on the placeholder and selecting properties.

Further Information

You can find a more detailed explanation of the exact steps necessary to create an Android Extension from the YoYo Games Knowledge Base: Creating A Native Extension For Android.

Back: Extension Packages
Next: iOS Extension

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Creating Extensions

This section details how to create an extension in GameMaker: Studio.

To create an extension (no matter what format file you are using) you must first start by right clicking on the Extension resource in the resource tree and selecting Create Extension which will open the following window: This window is where you place the basic information that is required to create the GMEZ extension package. You can give it a name and a version number, and also supply a Package ID. If you only wish to use the extension in this one project you can leave the package ID blank, but if you want to export the extension as a GMEZ file, or if you want to upload it to Markeplace, then you will need to give this information too. The Package ID should be unique to this extension and be in reverse URL format com.<company>.<extension_name>. If your extension package is for iOS or for Android, then you should mark the appropriate check boxes in this window too.

When you are happy that the information is correct you should click the "Next" button to continue. If you have not chosen iOS or Android as part of the extension, your next step will be to flag any of the project resources as being part of this new extension in the following tab: You can select resources to add into the extension package from the left side of the window, and clicking the "---->" button will add them to the resource list on the right. You can select individual assets, or you can select a group folder from the resources and add that (adding everything it contains). If your GMEZ is to be a template or a framework, you can click the "Add All" button to add everything in the current project to the extension. If you make a mistake, select the resource or group folder and press "Remove".

Once everything is correct you can click Create and your new extension package will be made. You can still edit the package by double clicking on it, or by right-clicking and selecting the Properties option. This will enable you to edit the extension package properties. If the extension contains resources, you will also see that there is an extra tab available to you for Importing those resources into the current project: As with exporting resources to an extension, tis tab has various buttons for adding the package resources to your project. the available resources are shown on the right, while the current project resources are shown on the left. Clicking the <--- button will add the selected resource, or folder of resources, to the project resource tree, or you can click Import All to add everything from the package. If you make a mistake while adding resources, you can select them from the resource tree on the left and click Remove to remove them again.

Android and iOS

When you create your extension package for iOS or Android, there are a couple of extra steps required by you to create the final extension package. These are detailed in the following pages of the manual:

  1. iOS Extensions
  2. Android Extensions

Adding Files

Once your basic extension package has been created, you can then go ahead and add files, functions and constants to make it work. This is done by right clicking on the extension and selecting Add File. The choice of file greatly influences how GameMaker: Studio will use the extension as different file types are required for the different target platforms that can be used when you compile your game, and not all platforms require a "real" file either (in which case you would use the Add Placeholder option instead of Add File). The relevant files needed per target are listed below:

  • GML: This is an extension made only with the GameMaker Language and is compatible with all platforms.

  • .js: This is a JavaScript extension and is only compatible with the JS target modules (HTML5).

  • .dll: This a dynamic-link library extension and is only compatible with the Windows and Xbox One targets (each target will need a different *.dll file compatible with its specifications).

  • .so: This is the Linux equivalent of a DLL and is only compatible with the Ubuntu (Linux) target.

  • .prx: This is a file for adding functionality to the PS3 and PS4 targets (each target will need a different *.prx file compatible with its specifications).

  • .suprx: This is for adding functionality to the PSVita target.

  • .dylib: This is the Mac equivalent of a DLL and is only compatible with Mac target (not iOS).

  • placeholder: This is a file that can be of any type, except those given above and .gmez, and will not be used except as a "linker" file to connect a set of functions or constants with the given extension (generally only for use with iOS and Android extensions).

If the extension package is for iOS or Android platforms, you will also see some extra options for adding files to the package. These are explained in the pages linked to above for those platforms.

File Properties

As you can see, not all extensions are compatible with all target platforms, so you should first open up the extensions resource tree and select for each of the installed extensions a target from their Extension File Properties. This can be achieved by double clicking on the extension file (NOT the package itself), or by right clicking and selecting "Extension Properties" from the pop up menu. Either action will open up the following window: In this window you can re-name the file that is to be used as the extension (this file is then saved with the gmx project and any changes should be made in the project file, and not to the original) and you can define the Init Function and the Final Function. These functions are the ones that the included file or the source file (which will depend on the target platform) needs to have called to set them up for use with GameMaker: Studio and to free them again when the game closes. They are called automatically, with no arguments, and you should note that these are not always necessary so you should check the documentation for the file you wish to use as an extension first to see if these functions are necessary or can be left blank (if in doubt, leave them blank).

If you are developing for multiple platforms and wish the same extension to be used on all of them, you can create Proxy Files for each target and add them to your extension too. Simply place the proxy file in the same folder as the extension (you can find this by right-clicking on the extension and selecting "Open in Explorer". Note that the naming of these files is very important and you can find a full list of the available platforms and conventions from the following page:

  1. Proxy Files

The final section is labelled Copies To. Here you can see a list of target platforms which you can tick (or un-tick) as appropriate for your extension. In this way, you can have (for example) two hi-score extensions, one *.dll and one *.js that have the same functionality but work for different target platforms. You would tick ONLY the Windows check-box for the *.dll and ONLY the HTML5 check-box for the *.js and then GameMaker will know to use only the appropriate one for the target platform. You can also set up different configurations and tick/un-tick options as necessary depending on the current configuration chosen (for more information see Advanced Use: Configurations). Note that adding proxy files will automatically tick the appropriate target platform.

Adding Functions and Constants

Now you have added the necessary files to the extension, it is time for you to add the functions and constants that you wish the extension to use. This is done by right-clicking on the file and selecting either Add Function or Add Constant. For a constant, it is simply a case of giving it a name (only letters from A-Z, numbers and the under-bar "_" symbol are permitted, and the name must not start with a number) and a value and then clicking on the "Okay" button. If you choose to add a function, then the following window will open: The different options presented here are:

  • Name - This is the GML name of the function (only letters from A-Z, numbers and the under-bar "_" symbol are permitted, and the name must not start with a number).

  • External Name - Here you must put the name of the original function as it is recognised by the extension, even if the Name is the same.

  • Help - This is the text that will appear at the bottom of the script editor and should be a correct form of the function syntax with the format function(argument0,argument1).

  • Return Type - What the function returns. This can be either a string (text) or a double (real number).

  • Type (dll only) - The calling convention used to call the function.

  • Arguments - Here you can list all the arguments that your function can take as well as the type (string or double). This is limited to a maximum of sixteen arguments, and note that for functions with 4 or more arguments, all of them must be of type double.

Once you have defined all your constants and functions, the extension is almost ready to be used and distributed as a *.gmez. To create a *.gmez, simply right-click on the extension name and select Export, which will open a save dialogue where you can say where to save the final *.gmez file to. Once this is done you can then use the same GMEZ file in other projects, or distribute it for others to use.

NOTE: A saved *.gmez does not save the configuration options, and those will have to be set whenever you load a created gmez into a new project.

Additional Documentation

You can find additional documentation on extension packages from the YoYo Games Knowledge Base:

  1. Extensions

You can also find additional information about the GameMaker: Studio Marketplace from the following section of the Knowledge Base:

  1. Marketplace FAQs

Back: Extension Packages
Next: Legacy Extensions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iOS Extensions

This section details the iOS tab in the Extension Package Properties.

When you create a new extension for your game, you are presented with the Extension Package Properties window from where you can set the basic properties for the extension (see the page Creating Extensions for further details). If your extension is for iOS, you would tick that option too, and clicking on the Next button will open the following tab: Here you give the following details:

  • Linker Flags: Some frameworks and third party SDKs require the addition of extra linker flags to work which can be specified here (see the documentation that accompanies the SDK or framework in question for details).

  • ClassName: Your extension can have multiple classes, with each class having its own functions and constants, so you should give it a name that reflects its purpose

Once that has been set up, you can add in any iOS system frameworks or third party frameworks (see the documentation that came with your chosen SDK for info on the framework name) to your extension. To do this you need to right click on the extension and select either Add iOS Framework From Mac or Add iOS Source Directory and then browse to the files you wish to add, either from the PC or from your Mac. Added files will be stored in the iOSSource directory along with your extension. You can open this location at any time by right clicking on the extension and selecting Open Extension Directory.

If your extension requires the use of System Frameworks or 3rd Party Frameworks, these will now be listed in the Extension Properties window, with each one having a check-box beside it. If you mark the check-box, you are enabling weak linking, which is useful should you need to "over-ride" any symbol from the included library with your own value, but it should be noted that doing so will slow linking down.

Adding Functions and Constants

To add your functions and constants to the extension package, you must now right click on the extension again and select Add Placeholder. This will create a placeholder file which "links" the functions you want to add to the extension itself. Once you have added your placeholder, you can then follow the instructions given on the page Creating Extensions to add the functions and constants it requires. Don't forget to set the export targets for the functions by right-clicking on the placeholder and selecting properties.

Further Information

You can find a more detailed explanation of the exact steps necessary to create an iOS Extension from the YoYo Games Knowledge Base: Creating A Native Extension For iOS.

Back: Extension Packages
Next: Android Extensions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Legacy Extensions

Here you can find out how to add GEX extensions to GameMaker: Studio.

You can add a GEX legacy extension straight into your project resource tree y right clicking on the extension resource and selecting Import Extension (you will need to change the file selector to point to GEX files), which will open the following window: In this form you can indicate which GEX extension packages must be used in the game you are making. On the left there is the list of Used packages and on the right is the list of Available packages, and to move a package from one list to the other, simply select it and press the button between the lists. When selecting a package a short description is usually given at the bottom (but not always if the package has been made by third party developers), and further help may also be available by pressing the Help button.

To install new GEX packages or uninstall existing GEX packages, press the Install button and the following window will open: You can see a list of all extension packages available (these are stored by default in the "Extensions" folder of the root directory where you have GameMaker: Studio installed). By selecting a package and clicking the Uninstall button the package is removed from the system, and pressing install will open a standard load file window where you can select a new package from your computer to make available within GameMaker: Studio.

Back: Extension Packages
Next: Proxy Files

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Proxy Files

This section explains how to add proxy files and their naming conventions.

When working with multiple target platforms, it is worth noting that you can create a single extension with only one set of functions which will work on all platforms. This is achieved by adding only one of the link libraries to your game as an extension and placing the other in the to the list of Proxy Files from the File Properties window. For example, say you have a Windows extension with the dll "Haggis.dll". You would simply replicate this dll as a Mac DyLib, naming it "libHaggis.dylib" and making sure that the internal function names match those of the original Windows dll. This DyLib would then be added into the Proxy Files and set to export when the game is run on the Mac target, and GameMaker: Studio will automatically use it when the extension functions are called.

To add a proxy file, simply click the (+) button in the File Properties window for the extension and browse to the file location. Once it is added you may need to change the extension target to the appropriate module, and when you next run your game it will be included as proxy for that platform. You can remove proxy files too by clicking the (-) button, which will remove the last one in the list each press.

Once you have added your proxy files they will be stored in the GMX of your game, in the Extensions folder (you can find them easily by right-clicking on the extension and selecting "Open in Explorer"), so if you need to edit them, you should edit the copied files that are bundled with the game and not the originals, as GameMaker: Studio will be using the ones in the GMX for compiling your game.

Naming Proxy Files

It is very important that your proxy files follow the naming conventions listed below, as GameMaker: Studio will parse these names and assign the target module for the file according to its extension and name and will automatically link the files for you. If you do not follow these conventions your game may not work at runtime, as GameMaker: Studio will not be able to work out which file to use or it will not load the file properly.

The naming conventions for each target platform are given below:

Platform | Names
Windows | <Name>.dll
Linux | <Name>.so, lib<Name>.so, <Name>_linux.so, lib<Name>_linux.so
Mac | <Name>.dylib, lib<Name>.dylib
PS4 | <Name>.prx, lib<Name>.prx, <Name>_ps4.prx, lib<Name>_ps4.prx
PSVita | <Name>.suprx, lib<Name>.suprx, <Name>_vita.suprx, lib<Name>_vita.suprx, <Name>_psvita.suprx, lib<Name>_psvita.suprx
Xbox One | <Name>_xboxone.dll

Using the conventions above, you would swap out the <Name> part for the name of the base file that you are adding the proxy files for.

Back: Extension Packages
Next: Using Extensions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Using Extensions

This section details how to use pre-made extensions in GameMaker: Studio.

As you can see from the following screen, GameMaker: Studio can use various types of extension: The type of extension that you use will very much depend on the target platform - the list below shows what each target requires:

  • All targets - GML extensions. These are extensions made using the GameMaker Language (GML) and are compatible with all target platforms.

  • Windows (Standard) - You can use windows DLL files (Dynamic Link Libraries), except in those games destined for the Steam Workshop (which prohibits their use).

  • Mac OSX - The mac OSX target can use the standard DyLib files for extensions.

  • HTML5 - This platform can use JavaScript extensions.

  • Android/Fire - This platform requires extension written in Java or an Android Framework SDK.

  • iOS - Extensions for this platform are written in Objective C and require a *.mm and a *.h file, or if using any Frameworks, a pre-compiled *.a native file.

The extensions resource tree follows the format of Extension >>> Included/Dummy File >>> Functions and Constants and after you have added an extension you should double click on the included/dummy file that accompanies it to bring up the Extension File Properties Dialogue where you can select the target platform to which it should be associated: You can select no targets (the extension will not be used) or one or more depending on what type of file it is and the support for it from the available platforms. Please note that this selection can also be linked to change through the use of Configurations.

Functions

The icon on the left is the Function icon and it shows us that the extension we are using has a function that can be called using GML from an object or a script in our game. These functions can take arguments, return values and act just like any other GML function, only they use the extension to do the work and not GameMaker: Studio. You can right-click on a function and select Properties (or simply double click on it) and you will get the function properties window which looks like this: The Name is the name of the function in GML, and the External Name is the name of the function as the external SDK or file sees it. This part cannot be left blank, and must be filled in correctly, even if the function name is the same as the Name you have supplied previously. Below that is the Help section, where you would put in the correct syntax for the function which will then be shown in the script and code windows at the bottom of the screen. The Return Type is what the function returns, either a double (number) or a string (text) and if you are using a dll, you will also get a Type section which defines the calling convention used. Finally you have a list of the arguments that the function takes and whether they are doubles or strings.

Note that at the bottom you have a checkbox labelled "Variable length arguments". If the extension function is to have any optional arguments (ie: if you can provide 4 or 5 or 6 arguments) then you should tick this option.

Constants

An extension can also contain Constants, which are basically named values you can use rather than having to type the same text or numbers every time you wish to have a certain value. For example, the GML constant c_blue is a constant for the value $0048ff and is certainly much easier to remember than the hexadecimal value! If you right-click on a constant and select Properties (or simply double click on it), the following window comes up: Here you can simply change the name of the constant (be aware that this may affect how the extension works) and the value that it represents. Note that you can mark the Hidden check-box to have the constant excluded from the intellisense of the code editor, meaning that it will not be highlighted nor shown in the constants list from the Scripts drop down menu. This does not affect how the game runs, however, and the constant will still be recognised as such when the game is run.

Using Extension Functions And Constants

Once you have installed your extension, you can use the functions and constants for it just as you would the built in functions and constants used in the GameMaker Language. If your game is cross-platform (for example, it is designed to run on both Windows and Android targets), then you should do an OS check before calling extension specific functions to prevent issues, for example:

switch(os_type)
{
case os_android:
call_android_extension_function(x, y, z);
break;
case os_windows:
call_windows_extension_function(x, y, z);
break;
}

Note that for different platforms your extensions can share function names, so if you have two extensions to (for example) pop up a message for Windows and for Android, both extensions can share the same function name as long as they are both set to export only to their respective platforms.

Back: Extension Packages
Next: Creating Extensions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Global Game Settings

This section deals with the Global Games Settings window.

When working with GameMaker: Studio on a new project, it is vitally important that one of the first things you do is set up the Global Games Settings. It is through these options that you define how your game final game will be created and what information will be stored along with it for the various possible target modules.

The settings can be changed by double clicking on Global Game Settings in the resource tree at the left of the screen, or by clicking the icon at the top of the IDE, or by selecting "Global Game Preferences" from the drop down resources menu. The window that opens is further subdivided into the following tabs:

General Settings

The following pages deal with the settings that affect multiple (or even all) target platforms:

  1. General Settings
  2. Texture Groups
  3. Audio Groups
  4. Project Info
  5. Source Control
  6. In App Purchases
  7. Analytics
  8. Advertising

Target Module Settings

Apart from the general settings for your game, each target module has a separate tab where you can set up the target-specific details:

  1. Windows
  2. UWP
  3. Windows 8
  4. Windows Phone 8
  5. macOS
  6. Ubuntu
  7. HTML5
  8. Android / Fire
  9. Amazon Fire
  10. iOS
  11. Steam API

Please note that the availability and functionality of these tabs will depend on the version of GameMaker: Studio that you are using. See here for more information.

Back: Advanced Use
Next: Debugging

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Advertising Tab

This section deals with the Advertising tab of the Global Game Settings window.

This tab can be used to set up and control the add providers you use for your games, as well as how their adverts are displayed within your game. There are three sub-tabs provided for each of the target platforms that permit advertising (iOS, Android, and HTML5).

Enabling Ads

To switch advertising on for your game, you will need to do either one of two things depending on the target platform. If your game targets iOS or Android, then you will need to check the box for the ads provider that you require and then download the provider as an extension from the Marketplace (you can find more information on this here: Ad Provider Demos V3). If you require a demo of the ad providers on iOS or Android then you can click the link provided beside each provider to download a demo - which contains a help file - from the Marketplace. For all other platforms, ads support is built into GameMaker: Studio and you must first check the box labelled "Enable Advertising" and then select the advertiser that you wish to use as the provider from the drop down menu shown:

Testing Ads

If you wish to test out your adverts in a test game or to see how they look, you can also check the box labelled "Use Test Ads (where available)", and, depending on the provider, you should be able to compile and run your game with advertising coming though as you would see it in a "live" game, but without it actually counting towards your ad revenue. For more information on this feature and to see which companies support it, please see the section Reference - Advertising and Analytics.

NOTE: For iOS and Android the process for getting test ads is slightly different and you should consult the Knowledge Base article for each ad extension.

Ad Providers

Each target has a different set of advertising providers (the image above is just an example) and the list will change as more become available. Once you have chosen your provider, you should then choose which advert type you wish to display in your game. This is done by supplying the Key that the provider has given you for the advert type and by selecting the shape of the advert as it should be shown within your game. These shapes will vary from provider to provider, so you you should check with them for the exact size and layout of each ad.

You should note that there is one final ad-type that may be available for your provider, and that is interstitial ads. These normally take the form of full page adverts which can be offer walls (essentially a page to promote several different advertising campaigns), virtual currency deals, or a video and there are a number of specific functions that can be used to launch those ads should the provider permit them.

When you have finished specifying your provider and the ads you wish to support, you will then need to set them up from within your game code using the functions found in the section: Reference - Advertising and Analytics.

For information on individual Ad providers, please see the YoYo Knowledge Base.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

Back: Global Game Settings
Next: The Windows Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Amazon Fire Tab

This section deals with the Amazon Fire tab of the Global Games Settings Window.

IMPORTANT! This tab will only be visible if you have signed up for a promotional trial of the Amazon Fire module and do not have the Android module. If you do have Android, then you should look at the page Android Global Game Settings instead.

The Amazon Fire tab is split into various separate sub-tabs (accessible on the left of the window) to make changing and updating the information for your game clearer and less complicated. These tabs are explained in the following sections. The basic setup for the Amazon fire is similar to that used for Android, so make sure sure that you have set up the Android Preferences correctly before using this target.

General

The first thing to do is fill in the details about your game, including its Display Name, its Package Name and the Version info. The package name can only be made up of letters from A-Z and numbers 0-9, with no symbols or other special characters at all, nor should it have uppercase characters. It should follow the format “com.domain.myapp”.

Here you can also set the build tools version to use, along with the SDK values to use (minimum SDK version, Target SDK version and the Compile SDK version). In general you will want to leave these at their default values, but if your game targets a specific Android version then you can set the build tools and SDK values to that which you require here.

To the right of the page, you can add a splash screen to your APK, for both landscape and portrait modes, which will be shown while the game loads on the device. This screen should be a 24bit PNG file, and is recommended to be the same size as the first room (or view) in your game. If you require that the splash screen be shown for a specific time then you can also set it here from 0 to 10 seconds (the default time of 0 means that it will only show for the duration of the asset loading).

On this page you can also set the following options for your final APK file:

  • Architectures - This is the CPU type that your game will support. The most common ones are chosen by default (99% of all devices use these), but you can choose those that you think appropriate. Bear in mind that each one will add about 1MB to the final apk size, don't go ticking them all unless this is not a problem!

  • Orientation - Here you can choose to lock the game to a specific orientation by checking either landscape, portrait, landscape-flipped or portrait-flipped. Note that if you have selected Portrait and PortraitFlipped, then this is handled as sensorPortrait, but not all devices will allow the PortraitFlipped orientation in this mode.

  • Misc - This section permits you to add extra support for certain features:

    • you can set the Install Location for your game. This can either be set to auto, in which case the game will be installed to the location chosen by the user on their device, or it can be set to Prefer External which will always try to install the game to the external storage of the device.

    • you can add support for Moga Controllers for your game here. Note that all Moga functionality is accessed via an extension, and when you first check the Use Moga box you will be prompted to download the Moga extension from the Marketplace and then add it into your project.

Graphics

The graphics tab has three sections to it - Options, Icons and Texture Pages. The first of these controls the display options for your game, with the first one being the Interpolate colours Between Pixels flag. This turns on interpolation, which basically "smooths" pixels, so for crisp pixel graphics, it should be off, but if you have nice alpha blends and smoothed edge graphics it is better left on.

Next, you can set the Screen colour Depth to either 16bit or 24bit. This will affect the compatibility with some older devices if it is set to 24bit, and will also increase the ashmem that is needed (this is the shared memory on Android devices).

The next here is the Device Support for your game. You can choose to support any device, or only those that have a GPU. Basically, if your game has any advanced drawing functions like alpha blending, additive blending, surfaces, etc... you should limit it to those devices that have a GPU otherwise you run the risk of getting negative comments and poor rating for your game due to graphical errors or crashes on older devices.

Finally there is the option for scaling to the device screen. Here you can choose to maintain aspect ratio (so a 4:3 room, for example, will be "letter boxed" on a 16:9) or to scale fully (stretching the image to fit the full screen).

WARNING! Switching off the application surface in your code will disable all the scaling options set in the Global Game Settings until it has been switched back on again. See The Application Surface for further details.

After these options there is the section for setting the size of the Texture Page. The default (and most compatible) size is 1024x1024, but you can choose from anywhere between 256x256 up to 2048x2048. There is also a button marked View which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

On the right of the page you can set the game icons. These are used in various situations on the Store and in your game, and should be created as 24bit PNG files of the appropriate sizes given.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

Social

This tab permits you to enable social functions for your Android game with either Amazon GameCircle, Google Play, or Facebook as well as activate Push Notifications.

If you require the Facebook functions, you need to click the "Use Facebook" checkbox and then supply the Facebook App ID and Facebook App Display Name. Note that all Facebook functionality is accessed via an extension, and when you first check the Use Facebook box you will be prompted to download the Facebook extension from the Marketplace and then import it into your project.

In order for your game to use Push Notifications they must be enabled here first otherwise they will not work. Local notifications on Android do not require the "GCM Sender ID", but you must add it should you wish to create remote notifications.

If you want to enable achievements and leader boards from the Google, then you need to check the appropriate check box. Once you have ticked one of the services, you will be prompted to download and install the corresponding extension from the Marketplace and install it in your project, and then code the functionality into your game using the Achievements and Leader boards functions. Note that you will need to add your App Id from Google Play into this tab for the services to work (this can be found from your Google Play Developers dashboard).

If you are using any Amazon Services, you need to tick the "Enable Amazon API's" check box. Once you have ticked this, you will be prompted to download and install the corresponding extension from the Marketplace. The Amazon API does not hook into the built in leader board functions (like the Google APIs do) but instead has all the functions included as part of the extension.

Permissions

From this tab you can change some of the permissions that your game may request within the Android Manifest. GameMaker: Studio allocate permissions automatically as required, however you may find you require a permission for your game that we haven't assigned in which case tick the requisite permission box on the tab. The list below outlines those that are available:

  • WRITE_EXTERNAL_STORAGE - Will permit your game to write to external storage.

  • READ_PHONE_STATE - Allow read only access to the phone state.

  • ACCESS_NETWORK_STATE - Permit your game to access information about networks.

  • INTERNET - Permit your game to open network sockets.

  • BLUETOOTH - Will permit your game to connect to paired Bluetooth devices.

  • RECORD AUDIO - Will permit your game to record audio input from the microphone.
NOTE: If you are not sure that you need these, you should probably just leave them un-checked by default and let GameMaker: Studio deal with the permissions for your game.

Back: Global Game Settings
Next: The iOS Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Analytics Tab

This section deals with the Analytics tab of the Global Games Settings Window.

This tab permits you to add analytics to your game, permitting you to use certain third-party products to track your game and its sales or plays. There are three sub-tabs for this, one for HTML5, one for Windows Phone and one for Android.

For all available platforms you can specify whether to use Flurry Analytics or Google Analytics to track your game, but due to the nature of these functions, you can only have one active at a time, so make sure that you check the correct one! Once you have flagged the Enable Flurry or Enable Google Analytics check-box for your analytics provider, you should also add the unique ID that you have been assigned into the appropriate area for HTML5, and for Android, you will be prompted to install the appropriate extension (and you add the ID value into the extension functions). You can find further information about this from the following Knowledge Base article: Analytics Provider Demos v1.4. Checking these boxes does not install the extension and you will need to download it independently from the YoYo Games Marketplace and import it into your game project.

For more general information on analytics, please see the YoYo Knowledge Base.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio and will depend on the target modules that you have installed.

Back: Global Game Settings
Next: The Advertising Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Android Tab

The Android / Fire Tab

This section deals with the Android / Fire tab of the Global Games Settings Window.

This Android / Fire is for setting up per-project details for the Android or Amazon Fire target modules. The tab is split into various separate sub-tabs (accessible on the left of the window) to make changing and updating the information for your game clearer and less complicated. These tabs are explained in the following sections.

NOTE: If you have any promotional trial version of Amazon Fire but don't have the Android module then you will have a separate Global Game Setting for Amazon Fire. See Amazon Fire Global Game Settings for more details.

General

The first part of the General section is dedicated to the Product Information and the Build Settings. You should fill in the Product information, which includes the projects Display Name, its Package Information, which consists of a Domain, Company and Product. The package information can only be made up of letters from A-Z and numbers 0-9, with no symbols or other special characters at all, nor should it have upper-case characters. These details will then be used to generate a Package ID with the format "com.company.myappname".

You then need to set the Target, Minimum and Compile SDK versions. The Compile SDK version is the version of the API that the project is compiled against. This means you can use Android API features included in that version of the API. If you try and use API 16 features - for example - but set Compile SDK 15, then you will get a compilation error. If you set the Compile SDK to 16 then you can still run the app on an API 15 device (as well as all other previous versions too).

The Target SDK, however, has nothing to do with how your app is compiled or what APIs you can utilize. The Target SDK indicates that you have tested your app on (up to and including) the version you specify. This is simply to give the Android OS an idea of how it should handle your app in terms of OS features. For all practical purposes, most apps are going to want to set Target SDK to the latest released version of the API (as used by the Compile SDK setting). This will ensure your app looks as good as possible on the most recent Android devices.

The Minimum SDK version is the minimum API level that will run your project. This is set to 9 by default, and in general this will be fine, but if you add extensions then they may require a higher minimum API level. After that you need to give the Build Tools version, which can be found from the SDK Tools section of the SDK Manager in Android Studio, although note that you will need to check the "Package Details" to see it. If you are using the command line tools it can be found inside the "Tools" folder of the Android SDK Manager.

You also need to get the Support Library to use. Recent versions of the SDK Manager (both the Android Studio one and the Command Line Tools) no longer list these separately and instead they are included as part of the Support Repository, so to target the correct one simply use the initial Build Tools version number (for example, if the build tools are 25.0.2 then the support library would be 25.0.0).

The second part of the General section covers the CPU Architectures to build for, with the following options available (you can select all of them or only those that you require, but note that each one will add to the final size of the compiled apk):

  • Build for ARMV5 (checked by default)
  • Build for ARMV7 (Checked by default)
  • Build for x86
  • Build for Mips

After setting that up you can select the different Orientations that your game can be run on for the best user experience. The available options are:

  • Landscape
  • Portrait
  • Landscape-flipped
  • Portrait-flipped

Finally you have the following Miscellaneous options:

  • Enable Bluetooth/iCade support: This will add support for bluetooth or iCade gamepads to your game project. This is on by default.

  • Enable MOGA gamepad support: This will enable support for MOGA controllers. Note that all MOGA functionality is accessed via an extension, and when you first check this option you will be prompted to download and install the MOGA extension from the Marketplace. This option is off by default. Find the functions here for GamePad Input.

  • Run Lint Code Analysis: When this option is flagged, the build tools will run a lint code analysis on the project as it builds, giving a more in-depth error check and showing more information in the output window as the project compiles (a LOG file will be created too, with the path to the file shown at the end of compiling in the Output Window). Note that not everything flagged by lint analysis as an error is necessarily problematic for your game, and having this enabled may mean that your game no longer compiles, even though when it is off, it will compile and run fine. Essentially this is only for debugging, and the option is off by default.

  • Install Location: Here you can set the default Install Location for your game. This can either be set to Automatic, in which case the game will be installed to the location chosen by the user on their device, or it can be set to Prefer External which will always try to install the game to the external storage of the device.

You can also set the Android Sleep Margin here. This option is related to reducing stuttering when running your game on specific systems. Basically, if your game is running faster than your room speed GameMaker Studio 2 will "sleep" for the remaining time, but this sleep can be quite inaccurate and you can often end of sleeping for longer than necessary, causing your frame to take longer which causes stuttering. To get around this we can sleep for less time, then sit in a tight loop for the remainder of the time to make it more accurate - although the problem with sitting in a loop is that it causes CPU usage to increase, which in turn can cause your CPU temperatures to rise and your fan to run faster. By default, this value is set to 4, and in 99.99% of the cases you'll be fine with this, but for low end machines or for machines with a lot of background processes running this may not be an ideal solution and a value of 5 up to 10 may be required. Note though that this is very much a device specific configuration and what works on your build device may not be appropriate for another user, and as such if in doubt leave it set to 4. To the right of the page, you can add a Splash Screen to your APK, for both landscape and portrait modes, which will be shown while the game loads on the device. This screen should be a 24bit PNG file, and is recommended to be the same size as the first room (or view) in your game. If you require that the splash screen be shown for a specific time then you can also set it here from 0 to 10 seconds (the default time of 0 means that it will only show for the duration of the asset loading).

Graphics

The graphics tab has three sections to it - Options, Icons and Texture Pages. The first of these controls the display options for your game, with the first one being the Interpolate colours Between Pixels flag. This turns on interpolation, which basically "smooths" pixels, so for crisp pixel graphics, it should be off, but if you have nice alpha blends and smoothed edge graphics it is better left on.

Next, you can set the Screen colour Depth to either 16bit or 24bit. This will affect the compatibility with some older devices if it is set to 24bit, and will also increase the ashmem that is needed (this is the shared memory on Android devices).

The next here is the Device Support for your game. You can choose to support any device, or only those that have a GPU. Basically, if your game has any advanced drawing functions like alpha blending, additive blending, surfaces, etc... you should limit it to those devices that have a GPU otherwise you run the risk of getting negative comments and poor rating for your game due to graphical errors or crashes on older devices.

Finally there is the option for scaling to the device screen. Here you can choose to maintain aspect ratio (so a 4:3 room, for example, will be "letter boxed" on a 16:9) or to scale fully (stretching the image to fit the full screen).

WARNING! Switching off the application surface in your code will disable all the scaling options set in the Global Game Settings until it has been switched back on again. See The Application Surface for further details.

After these options there is the section for setting the size of the Texture Page. The default (and most compatible) size is 1024x1024, but you can choose from anywhere between 256x256 up to 2048x2048. There is also a button marked View which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

On the right of the page you can set the game icons. These are used in various situations on the Store and in your game, and should be created as 24bit PNG files of the appropriate sizes given.

Social

This tab permits you to enable social functions for your Android game with either Amazon, Google Play, or Facebook as well as activate Push Notifications.

If you require the Facebook functions, you need to click the "Use Facebook" checkbox and then supply the Facebook App ID and Facebook App Display Name. Note that all Facebook functionality is accessed via an extension, and when you first check the Use Facebook box you will be prompted to download and install the Facebook extension from the Marketplace.

In order for your game to use Push Notifications they must be enabled here first otherwise they will not work. Local notifications on Android do not require the "GCM Sender ID", but you must add it should you wish to create remote notifications.

If you want to enable achievements and leader boards for the Google app store, then you need to check the appropriate check box. Once you have ticked one of the services, you will be prompted to download and install the corresponding extension from the Marketplace, and then code the functionality into your game using the Achievements and Leader boards functions. Note that if you use Google Play you will need to add your App Id into this tab for the services to work (this can be found from your Google Play Developers dashboard).

If you are using any Amazon Services, you need to tick the "Enable Amazon API's" checkbox. Once you have ticked this, you will be prompted to download and install the corresponding extension from the Marketplace. Unlike previous versions of GameMaker: Studio, the Amazon API no longer hooks into the built in leader board functions (like the Google APIs do) but instead has all the functions included as part of the extension.

NOTE: This also needs to be ticked if you require the use of the Amazon Services along with the Amazon Fire target module.

Permissions

From this tab you can change some of the permissions that your game may request within the Android Manifest. GameMaker: Studio allocate permissions automatically as required, however you may find you require a permission for your game that we haven't assigned in which case tick the requisite permission box on the tab. The list below outlines those that are available:

  • WRITE_EXTERNAL_STORAGE - Will permit your game to write to external storage.

  • READ_PHONE_STATE - Allow read only access to the phone state.

  • ACCESS_NETWORK_STATE - Permit your game to access information about networks.

  • INTERNET - Permit your game to open network sockets.

  • BLUETOOTH - Will permit your game to connect to paired Bluetooth devices.

  • RECORD AUDIO - Will permit your game to record audio input from the microphone.
NOTE: If you are not sure that you need these, you should probably just leave them un-checked by default and let GameMaker: Studio deal with the permissions for your game.

Extras

One of the features of using Google Play for your Android games is the ability to licence your games. This means that your games will be controlled by Google so that only people that have downloaded it through their market will be able to play the game, thus avoiding illegal copies of your product from getting distributed.

To activate this function in your game, you must first flag the Enable Google Licensing box and then copy your Public Key into the box as shown in the above image. This licence can be found by going to your Google Play Developers Page and then selecting the option Edit profile. Once on the profile page, scroll down to the section titled "Licensing & In-app Billing" and there you should find the Public key that is needed for this functionality to be enabled.

Once activated, if anyone who is not authorised to posses your game tries to play it, they will be shown a pop-up message box that will inform them that the Licence cannot be found on their device, and then give them the option to retry and test again, or exit the game.

Another feature of Licensing is that your game can then use apk expansions. This is a way to bypass the 50MB maximum application size imposed by Google Play (and only Google Play). It will create your game in two parts: a small *.apk file and a larger *.zip file which will hold all your games assets, both of which are uploaded to the store. When the user first runs your game, the zip will be downloaded and unpacked. You can find further details of this option here.

Finally, if your game is being created for the OUYA games console, then you can specify that the final APK should be packaged in accordance with the console specifications here.

Back: Global Game Settings
Next: The Amazon Fire Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Audio Groups Tab

This section deals with the audio group options of the Global Games Settings Window.

Here you can add, delete and rename audio groups. GameMaker: Studio permits you to assign each of the audio resources (sound effects and music) to different audio groups to try and optimise the number of sounds that are being played at any one time, as well as give you further control over volume and other things. For that to work, you need to define the necessary audio groups from this tab, and then go through each of the appropriate resource types and select the group you wish it to belong to from the drop down menu. Once you have defined audio groups and assigned sounds to them you can see them in the list marked Audio Group Sounds List.

NOTE: If you have a set of sounds in a folder within the Resource Tree, you can Right Click on the folder icon and select "Assign audio group" to assign all the sounds contained with the folder to a specific audio group.

The "default" audio group will include the audio files in the game bundle and they will all be loaded into memory on start-up (unless flagged as "streamed" in the Audio properties), but when you create a custom audio group, the files that are added to it will not be loaded into memory until you call the function audio_group_load(). In this way you can control what audio is resident in memory at any time.

Audio Groups are also linked to the Configurations settings. When you select a configuration, you can then open the Audio Groups tab and select the export targets from the right hand side for that configuration. Note that you cannot set audio resources to different groups on a configuration basis, only the export target for the given group.

For more information on how to set a sound to a specific audio group, please see the section Sounds and Music and for the functions available see the section on Audio Functions.

NOTE: Audio groups can only be used when working with the normal audio system, but will not work with legacy audio.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

Back: Global Game Settings
Next: The Project Info Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The General Options Tab

This section deals with the general options of the Global Games Settings Window.

This tab deals with a few of the general aspects of how GameMaker: Studio 1.4 will run your game.

To start with you are shown the Game Identifier value - which can be edited if required - along with the Game GUID which is the unique identifier that is used to identify the game project. Underneath these fields you have a button that can be used to generate a new Game Identifier (which can be accessed in your game by using the constant game_id) and . The button to generate this id also re-creates the Game GUID hash which can then be copied to the clipboard with the help of the button below for use in your applications and games.

Underneath the Game ID data, you can choose the colour outside the room region (which is the colour used to draw the background when the view goes outside of the room region). The default value is black. Beside this you also have the following options:

  • Use New Audio Engine: Checking this will enable the "new" audio system (which uses the audio_* functions) while unchecking it will enable the legacy audio engine (that uses the sound_ and music_ functions). Due to incompatibilities you cannot have both the new audio engine and the legacy sound engine active at the same time. For old games created with other versions of GameMaker or for those games started before the new audio engine was added, the Legacy Audio will be used as default, while for all new games GameMaker: Studio will default to the new audio system. However, you can change this at any time by flagging (or un-flagging) this option. For more information on the new Audio Engine, please see the section on Game Assets - Sound.

  • Short-Circuit Evaluation: The default behavior for GameMaker: Studio is to have short-circuit evaluation on, meaning that when performing any boolean check with multiple expressions, if any of them fail then the rest will be "skipped", giving a very minor boost to your game logic. However, older versions of GameMaker: Studio evaluated both arguments to a boolean operation, even when the first argument already determined the outcome, so disabling this option will return GameMaker: Studio to using the previous method. Generally you would want this on, but in certain cases (particularly if you are importing old projects) you may need to switch this off to prevent any undesired effects.

  • Use fast Collision System: This is checked by default and tells GameMaker: Studio to use the "fast" collision system over the legacy one. The fast system is a tree based spatially collision system that can make massive speed ups in collision testing. However it may not be entirely compatible with old or imported projects and so you can disable it here (although you might want to try Compatibility Mode first, see below). It is on by default for new projects.

  • Fast Collision System Compatibility Mode: When this is enabled, GameMaker: Studio will still use the fast collision system, but it will be modified to work more like the legacy collision system. If you are having issues with collisions in your project (especially if the project is an older one) then you may benefit from enabling this (note that this will affect the performance of the fast collision system, but not as adversely as switching off fast collisions all together).

Back: Global Game Settings
Next: The Texture Groups Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The HTML5 Tab

This section deals with the HTML5 tab of the Global Games Settings Window.

This HTML5 tab is split into two separate sub-tabs (accessible on the left of the window) to make changing and updating the information for your game clearer and less complicated. These tabs are explained in the following sections.

General

At the top of the window you can set the File options for your HTML5 game, which includes:

  • adding a custom index.html to use instead of the pre-defined one that GameMaker: Studio generates by default. This can be very useful if you have a website design implemented or want to include certain features in all your HTML5 builds.

  • choosing a Loading Bar Extension. This should have been added in as an extension to the GameMaker: Studio resource tree (there is a demo of this included with the program) and will override the standard loading bar when selected.

  • selecting a new name for the title bar of the tab for your game in the browser.

  • selecting a new name for the folder where your HTML5 game files will be stored (default is "html5game").

  • selecting a new name other than the default "index.html".

Once that is done you will need to give your game a favicon and a Splash Screen. The icons should be authored as an *.ico file and can be 16x16, 32x32, 48x48, or 64x64 pixels in size, and 8-bit, 24-bit, or 32-bit in colour depth. The splash screen should be the size of the canvas that is going to hold your game and will override any loading bars if you tick the Use Splash Screen option (ie: you can have a loading bar, OR a splash screen, but not both). Smaller or larger images are permitted but will be scaled to fit.

If you are testing a game locally (ie: clicking on the index file from your computer rather than a server - not recommended), then you normally get a warning informing you that things won't work as you may expect due to browser security for local files. You can suppress this warning by un-checking the Display "running outside server" alert option.

Should you require the cursor to be disabled while the mouse is over the canvas area, you can un-check the option "Display Mouse Cursor".

You also have the further options to send all debug output to the JS console of your browser, and to prepend the *.js output with any extra JavaScript necessary for your game. For example, a Chrome Store app may require that you add window.localStorage = undefined; to the output JS, for which you would use this option.

Graphics

Here you can change the following details related to how your game will be displayed (note that not all browsers will display your game in the same way, so test these options on as many browsers as possible to make sure that they have the desired effect).

  • Allow switching to fullscreen - Checking this will allow the user to toggle the game from windowed to fullscreen mode using <CTRL> + <CMD> + <F> on Mac and F10 on Windows.

  • Interpolate colours between pixels - Turns on interpolation, which basically "smooths" pixels. for crisp pixel graphics, it should be off, but if you have nice alpha blends and smoothed edge graphics it is better left on.

  • Center the game in the browser - Checking this will automatically center the game screen within the browser running the game.

  • Use Built In Particle Sprites - This option will export the sprites required for the built in particle system along with your game. These sprites are stored in individual texture pages, meaning that they are not the most efficient method of generating particles for this platform, therefore it is recommended that (unless using WebGL) you un-check this option and use your own particle sprites which will be stored on the main texture pages all together for your game.

  • WebGL - Choose whether to switch off WebGL support, make it optional (auto-detect), or make it a requirement for your game. It should be noted that to test performance under all circumstances, you should have this as disabled, then normally set it to auto-detect for publishing. Making it a requirement may reduce considerably the compatibility that your game has with different browser types.

  • Scaling - Your game can be configured to scale the draw canvas automatically to maintain the aspect ratio within the browser, or you can select to have it stretch to fit. The stretch to fit option will not full screen the game in the browser, but rather stretch what is drawn to fit the canvas size, as defined by the first room of the game.

Finally there is the option to set the size of the Texture Page. The default (and most compatible) size is 2048x2048, but you can choose from anywhere between 256x256 up to a whopping 8192x8192! There is also a button marked View which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

Social

The social tab is used for setting up Facebook communication in your game. If you require the Facebook functions, you need to click the "Use Facebook" checkbox and then supply the Facebook App ID and Facebook App Display Name. Note that all Facebook functionality is accessed via an extension, and when you first check the Use Facebook box you will be prompted to download and install the Facebook extension from the Marketplace.

Back: Global Game Settings
Next: The Android Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The In App Purchases Tab

This section deals with the In App Purchases tab of the Global Games Settings Window.

This tab is for setting up certain In App Purchase options for Android, where you can supply your Android Public Key for Google Play (this is a key code supplied by Google as a protection method for your game). This licence can be found by going to your Google Play Developers Page and then selecting the option Edit profile. Once on the profile page, scroll down to the section titled "Licensing & In-app Billing" and there you should find the Public key that is needed for this functionality to be enabled. Note that to use In App Purchases in any Android project you must have installed the Google Services extension and the Google IAP extension (see here for more details).

For more detailed information on in app purchases, the available GameMaker: Studio functions and proprietary server setup, please see the section Reference - In App Purchases.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

Back: Global Game Settings
Next: The Analytics Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The iOS Tab

This section deals with the iOS tab of the Global Games Settings Window.

This iOS tab is split into three separate sub-tabs (accessible on the left of the window) to make changing and updating the information for your game clearer and less complicated. These tabs are explained in the following sections.

General

The first thing to do is fill in the details about your game, including its Display Name, its App id and the Version info. Then you will need to give your game its Icons. The icons should be authored as a individual 32bit *.png files of varying sizes so that they are shown correctly on the store, OS etc...

NOTE: The Bundle id must be in the correct reverse URL format for in app purchases to work correctly, EG: com.[Company].[GameName]

The last two sections on this tab are Orientation and Devices. The orientation section can be used to lock the game to a specific orientation by checking one or all of the following options:

  1. portrait
  2. portrait upside down
  3. Landscape left
  4. Landscape right

The Devices section is used to target specific iOS platforms, either iPhone or iPod Touch, iPad, or both.

Splash Screens

This tab permits you to add separate graphics as splash screens (the image that will be shown briefly while your app loads) for each of the different iOS target devices. These images must be authored as individual 32bit *.png images with no transparencies and at the correct size for each of the devices and orientations required. You can also set a minimum time for showing the splash screens from the drop down menu on the right (from 0 to 10 seconds).

Graphics

Once you have configured the game details and presentation graphics, there are two more available options on the Graphics tab. The first is the Interpolate colours Between Pixels option that (when checked) turns on interpolation, which basically "smooths" pixels. For crisp pixel graphics, it should be off, but if you have nice alpha blends and smoothed edge graphics it is better left on. Here you can also choose to halve texture pages when targeting the iPad1 (which has a lower specification and may not run larger games otherwise).

Next there is the option for scaling to the device screen. Here you can choose to maintain aspect ratio (so a 4:3 room, for example, will be "letter boxed" on a 16:9) or to scale fully (stretching the image to fit the full screen).

WARNING! Switching off the application surface in your code will disable all the scaling options set here in the Global Game Settings until it has been switched back on again. See The Application Surface for further details.

Finally there is the option to set the size of the Texture Page. The default (and most compatible) size is 1024x1024, but you can choose from anywhere between 256x256 up to 4096x4096. There is also a button marked View which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

Provisioning

The Provisioning tab is where you configure the Mac OS options to get the correct certificates for the iOS export module. You can do one of three things here, depending on the OS tyhat your Mac is running and how you want to do things:

  • If you are running a version of OSX (like Yosemite, for example), then you should go to the Certificate section to fill in the details of your developer certificates, which is done by simply clicking on the button marked Refresh From Mac and then selecting the appropriate certificate.

  • If you are using macOS Sierra or above, then you need to supply the Team Identifier and Xcode will use that to get the correct provisioning and signing certificates for your app. To find your Team Identifier, sign in to your Apple Developer account and go here. Note that you can set a default Team Identifier in the iOS Preferences.

  • If you supply neither of the above, you can still build the app but you will be required to set the signing yourself from within Xcode for every build that you do (each new build will need to be resigned).
IMPORTANT! Provisioning can only be completed successfully if you have previously signed up for an Apple developer account and have set up GameMaker: Studio correctly to communicate with your Mac computer where this information is stored.

Social

The social tab is used for setting up Facebook communication in your game. If you require the Facebook functions, you need to click the "Use Facebook" checkbox and then supply the Facebook App ID and Facebook App Display Name. Note that all Facebook functionality is accessed via an extension, and when you first check the Use Facebook box you will be prompted to download and install the Facebook extension from the Marketplace.

Back: Global Game Settings
Next: The Steam Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Ubuntu (Linux) Tab

This section deals with the Ubuntu (Linux) tab of the Global Games Settings Window.

This Ubuntu (Linux) tab is split into two separate sub-tabs (accessible on the left of the window) to make changing and updating the information for your game clearer and less complicated. These tabs are explained in the following sections.

General

This tab is where you set the name of your game as it is to be displayed while running, add a splash screen, and set the game icon that will be used. The icon must be a 64x64 pixel image in the *.png format, and the splash screen should be at least the same size as the fist room in your game (or it's view port) and *.png format too. You can also supply a contact email and a description (short and long), as well as a URL for the homepage of the game or the developer.

Graphics

The graphics options will determine how your game is displayed when run and affect the way things like scaling and interpolation are handled. The following options exist:

  • Start in fullscreen mode - If this is checked, the game will start in fullscreen mode.

  • Interpolate colours between pixels - Turns on interpolation, which basically "smooths" pixels. for crisp pixel graphics, it should be off, but if you have nice alpha blends and smoothed edge graphics it is better left on.

  • Use synchronization to avoid tearing - This toggles v-sync on or off. Note, that if you have a game with a room speed of 120 and the player has a monitor with a refresh rate of 60, turning this option on will lock your game speed to 60 too.

  • Allow the player to resize the game window - Checking this permits the user to change the size of the game window.

  • Scaling - Here you can choose to maintain aspect ratio (so a 4:3 room will be "letter boxed" on a 16:9) or to scale fully (stretching the image to fit the full screen).

  • Allow switching to fullscreen - Checking this will allow the user to toggle the game from windowed to fullscreen mode using <CTRL> + <CMD> + <F>.

WARNING! Switching off the application surface will disable all the scaling options set in the Global Game Settings until it has been switched back on again. See The Application Surface for further details.

Finally there is the option to set the size of the Texture Page. The default (and most compatible) size is 2048x2048, but you can choose from anywhere between 256x256 up to a whopping 8192x8192! There is also a button marked View which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

Back: Global Game Settings
Next: The HTML5 Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Mac OS Tab

This section deals with the Mac OS tab of the Global Games Settings Window.

This MacOS tab is split into three separate sub-tabs (accessible on the left of the window) to make changing and updating the information for your game clearer and less complicated. These tabs are explained in the following sections.

General

The first thing to do is fill in the Display Name of your game then go down to the Product Information section and fill in its Version Number, App id, App Output file and the Copyright details. The App Output is the location to which your game installation files go to on your Mac. When you create your .app.zip, that file can go anywhere (the location you specify when doing the save dialogue is not the only copy made of that .app.zip), but the .pkg and other files are left in this folder, permitting you to test local installations via Terminal in such a way as to simulate Mac Store purchasing, etc...

Once that is done you will need to give your game Icons and a Splash Screen. The icons should be authored as a single *.png file with a size of 1024x1024px. The splash screen should be the size of the first room in your game as this is what will briefly be shown while the game assets are being loaded. Smaller or larger images are permitted but will be scaled to fit.

Once you have configured the game details and presentation graphics, you should configure the two following options:

  • Allow menu and dock in fullscreen - When checked, this option will show the OS menu and dock if the game is in fullscreen mode.

  • Display the cursor - This toggles the mouse cursor visibility in your game.

Finally we have the option to give a Team Identifier. You can leave this blank to use the default Team Identifier as set in the Mac OS Preferences.

Graphics

The graphics options will determine how your game is displayed when run and affect the way things like scaling and interpolation are handled. The following options exist:

  • Start in fullscreen mode - If this is checked, the game will start in fullscreen mode.

  • Interpolate colours between pixels - Turns on interpolation, which basically "smooths" pixels. for crisp pixel graphics, it should be off, but if you have nice alpha blends and smoothed edge graphics it is better left on.

  • Use synchronization to avoid tearing - This toggles v-sync on or off. Note, that if you have a game with a room speed of 120 and the player has a monitor with a refresh rate of 60, turning this option on will lock your game speed to 60 too.

  • Allow the player to resize the game window - Checking this permits the user to change the size of the game window.

  • Scaling - Here you can choose to maintain aspect ratio (so a 4:3 room will be "letter boxed" on a 16:9) or to scale fully (stretching the image to fit the full screen).

  • Allow switching to fullscreen - Checking this will allow the user to toggle the game from windowed to fullscreen mode using <CTRL> + <CMD> + <F>.

WARNING! Switching off the application surface will disable all the scaling options set in the Global Game Settings until it has been switched back on again. See The Application Surface for further details.

Finally there is the option to set the size of the Texture Page. The default (and most compatible) size is 2048x2048, but you can choose from anywhere between 256x256 up to a whopping 8192x8192! There is also a button marked View which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

AppStore

If you wish the finished game to be App Store Ready then you need to check the Build for Mac App Store option, but be aware that this will only function if you are a registered Developer and have the necessary certificates. Under that are two sub-options that you should only check if they are true as Apple can reject your app if they are checked when they are not needed or vice-versa. These options simply permit your game to use the http_ and url_ functions. It is worth noting that if you wish to support GamePads in your game then the option to create an App Store ready package should be off.

Finally, you need to select its App Category (for more information, see here).

Back: Global Game Settings
Next: The Linux (Ubuntu) Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Project Info Tab

This section deals with the project info tab of the Global Games Settings Window.

This tab is simply where you can keep track of your project. You can enter details like the author name and the current version number, and there is a large area at the bottom for keeping notes or leaving messages for other team members etc...

Back: Global Game Settings
Next: The Source Control Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Source Control Tab

This section deals with the Source Control tab of the Global Games Settings Window.

If you have been working on a project without having it configured for source control, it's still not too late and you can actually version it too and have it protected the same as any new file. To do this, you have to go to the Global Game Settings and select the Source Control tab, then fill in the relevant details:

  • Username - This is the username assigned to you by whoever administers the source control system (if you have noone, or don't know, leave it blank).

  • Password - This is the password assigned to you by whoever administers the source control system (if you have noone, or don't know, leave it blank).

  • URL - This should point GameMaker: Studio to the location where you created your repository.

Finally, click on the "import Project to repository" button to version your current project and add it to the source control repository. For more information please see the section on Source Control.

NOTE: This only needs done once for any project and you should never need to do this again.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

Back: Global Game Settings
Next: The In App Purchases Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Steam Tab

This section deals with the Steam API tab of the Global Games Settings.

If your game has been accepted onto the Steam platform for sale, you should have installed and checked the Steamworks SDK through the Steam Preferences tab. Along with the SDK, you should have been given a Steam App ID which should then be inserted here, and the Enable Steam checkbox ticked for each of the possible Steam target platforms (Windows, Linux or MacOSX). This will now enable the use of the Steam API Functions in your game.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

Back: Global Game Settings
Next: The Windows Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Texture Groups Tab

This section deals with the texture group options of the Global Games Settings Window.

Here you can add, delete and rename texture groups. GameMaker: Studio permits you to assign each of the graphics resources (sprites, backgrounds, and fonts) to different texture groups to try and optimise the number of texture swaps that the hardware does at any given time in your game. For that to work, you need to define the necessary texture groups from this tab, and then go through each of the appropriate resource types and select the group you wish it to belong to from the drop down menu. note that there is also a button, "Check", for checking to see if any empty texture groups exist, ie: a group that has not got any sprites currently assigned to it. This can be useful when you've been changing graphics resources and need to check to see if you have any groups not used, or before deleting a group to make sure it's not got anything assigned to it.

Once you have defined texture groups and assigned sprites to them you can see them in the list marked Texture Group Contents, and clicking on any of the sprites in this list will show them in the image preview window on the right. This is particularly helpful when working on large projects and you need to be able to see which sprites have been assigned to which group.

NOTE: If the sprites have multiple sub-images, then only the first sub-image is shown in the preview window.

Texture Groups are also linked to the Configurations settings. What this means is that you can define texture groups for each individual configuration of your game, and then set the sprite or background asset assignments to these different groups and it will be "remembered" when you change to a different configuration. One use for this is that you could make an iPad configuration and for that create 2048x2048px texture pages. You would then close the Global Game Settings and assign all the graphics assets to the appropriate texture group, and when finished, you would then change to a different configuration (for HTML5, for example) and from the Texture Page tab, create new texture groups that are 512x512px, assigning the assets to these new groups. There is also a button at the bottom of the page that permits you to copy texture group settings from one configuration to another.

You can also choose to export (or not) any given texture group to any given platform by simply ticking/un-ticking the appropriate boxes from the Target Texture Group Is Valid For section of the window. In this way your configurations can be designed specifically for each target module and you can be sure that only those assets necessary for that platform will be compiled into your final game.

There is one other section on this page too, the Texture Group Settingand here there are extra options that are for use only in special circumstances:

  1. Texture group not scaled - Flagging this will force GameMaker: Studio to not scale the texture group under any circumstances. This can be useful, especially when dealing with universal apps, as it allows you to put specific resources like fonts in a group of its own to be used when the app is run on a specific device. For example, fonts can look great on a retina display, but when they are scaled down to draw on a normal display they can look terrible so you can assign them to a special non-scaling group. For example, if developing for the iPhone 6, you may wish to have this checked, as apps have been rejected due to the images being blurred by texture scaling.

  2. No cropping - When you add sprites into GameMaker: Studio, if they have any "space" around them (ie 100% transparency) this is automatically cropped when it is added into the texture page. However, if you are using the sprite as a non-repeating texture for primitives etc... this means that the UV coordinates for texture mapping are not going to be correctly represented. In these cases you can flag this option and the sprite will be added to the texture page "as is", maintaining any transparencies that it may have around the edges.

  3. Texture border width - This function is for use when scaling is enabled and is especially designed for those textures that need to be scaled by large amounts, primarily when using 3D models or scaling backgrounds. It increases the overlap or "pixel doubling" amount around the edges of all assets on the page (the default is 2 pixels), so that when the images are scaled, there are no gaps (or seams) visible.
  4. Parent - Here you can choose any of the existing groups to be the "parent" group for the currently selected one. "Child" groups will inherit any changes made to the parent texture group.

For more information on these features see the section on Texture Pages.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

Back: Global Game Settings
Next: Audio Groups

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Windows Phone 8 Tab

This section deals with the Windows Phone 8 tab of the Global Games Settings Window.

This Windows Phone 8 tab is split into three separate sub-tabs (accessible on the left of the window) to make changing and updating the information for your game clearer and less complicated. These tabs are explained in the following sections.

General

The first thing to do is fill in the details about your game, including its Display Name, its Description (which should be a short text), the Author name, the Publisher and the Publisher ID, and finally the Version info.

The next two sections on this tab are Orientation and Supported Resolutions. The orientation section can be used to lock the game to a specific orientation by checking either landscape or portrait, or landscape-flipped, while the resolution section is used to target specific displays. The following table shows the resolutions and ratios supported:

Name | Resolution | Aspect Ratio | Scaled resolution
WVGA | 480 × 800 | 15:9 | 480 × 800
WXGA | 768 × 1280 | 15:9 | 480 × 800
720p | 720 × 1280 | 16:9 | 480 × 853

Finally for this tab, you should indicate the Genre of the final product, which can be either Game or Application, and you can also flag the game as having access to the microphone for recording audio.

Graphics

Here you can give your game an Icon and different Splash Screens. The icon should be authored as an individual *.png file with a size of 99x99px. The splash screens should be made to the sizes of each of the available Windows phone resolutions in *.png format, and it will briefly be shown while the game assets are being loaded.

At the bottom there is the option to set the size of the Texture Page. The default (and most compatible) size is 1024x1024, but you can choose from anywhere between 256x256 up to 2048x2048. There is also a button marked Preview which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

Finally there is the option for interpolation and for scaling. Checking Interpolate colours between pixels turns on interpolation, which basically "smooths" pixels. For crisp pixel graphics, it should be off, but if you have nice alpha blends and smoothed edge graphics it is better left on. For scaling to the device screen, here you can choose to maintain aspect ratio (so a 4:3 room, for example, will be "letter boxed" on a 16:9) or to scale fully (stretching the image to fit the full screen).

WARNING! Switching off the application surface will disable all the scaling options set in the Global Game Settings until it has been switched back on again. See The Application Surface for further details.

Tiles

The Tiles sub-tab is further split into three separate groups, of which you should choose one to represent how the Live Tile that represents your game or app will be shown on the device.

Flip

Flip tiles are ones that will change from one "side" to another every few seconds, and here you can add the different images that you wish each "side" to show. Note that the smallest possible tile size does not flip and so you only need to supply one 159x159px image for that, while the other two sizes (medium 336x336px and wide 691x336px) will. Beneath the images you can also supply to Content strings. These will be shown on the back tile only, with the first string being for the medium size and the second one being for the wide size.

Iconic

The Iconic tile setting uses two images (small at 110x110px and medium at 202x202px) and a series of different text messages to display information about your game. If the user has reduced the tile size to the smallest or the medium size, then the respective images will be shown only, however when the user has a wide tile size selected, then the image will be displayed as an icon in the lower right of the tile and various lines of text will be displayed starting at the top right of the tile. The image below illustrates this:

Note that an Iconic Tile image will only ever be white, so the image chosen should be a single "silhouette" with alpha. No matter what your image, it will only ever be shown on an Iconic tile as a white image over a transparent background.

Cycle

The final tile type is the Cyclic one. This permits you to specify a small image (159x159px for the small and medium sizes) and a series of 9 different wide tile images (691 x 336px) that will be cycled using various different transitions.

Back: Global Game Settings
Next: The Windows Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Windows 8 Tab

This section deals with the Windows 8 tab of the Global Games Settings Window.

In the Global Games Settings of GameMaker: Studio, you can find the different setup options related to how your final game will look when you create the executable for the target platform. Here we will look at the Windows 8 tab. It is split into three sub-tabs, each of which is explained in the sections below:

General

This section is where you should set up the details of your app like its name and any associated graphics. Below is a list of all the available options and what they represent:

  • Display Name: Specifies the friendly name for the app that is displayed to users (this string is localizable).

  • Package Name: This is the name of the package that you have created and should match that used for the Developer key that you have created for the game (see the Installation Sub-Tab, below).

  • Package Display Name: This is the "short name" of the package and should Ideally be the same as the Display Name

  • Publisher Display Name: This is the name of your company or the person that you wish to associate as the games publisher.

  • Version: The version number of your game.

  • Orientations: Specifies the orientations in which the game would prefer to be shown for the best user experience. The available options are:
    Landscape
    Portrait
    Landscape-flipped
    Portrait-flipped
    On devices that can be rotated, such as tablets, the game won't be redrawn for orientations that aren't specified with this property - for example, the game won't rotate if the device is rotated to a Portrait orientation but the property specifies only Landscape and Landscape-flipped orientations. On devices that can't be rotated, a game might be shown in that device's default orientation, and the game's preferred orientation will be ignored, however, your game's preferred rotation will be honored on devices on which a rotation lock has been activated. These orientation preference choices apply to both the splash screen and the game itself every time a new instance is launched.

  • Splash Screen: This is the screen that will be shown when you start your game, and it cannot be larger than 620 x 300 pixels. Click on the Update button to change it, then select set the Background colour for it.

  • Logos: These are the Windows8 tile and icon logos that your game will use. It is worth noting that these images can be transparent *.png files, in which case they will be drawn over the Background colour specified in the appropriate section.

    NOTE: The background colour specified here also applies to the button colour in any app-owned dialog boxes and to the App Description page in the Store!

    - The large image is the wide version of the logo image, which appears when the tile appears in its wide format and should be 310 x 150 pixels. If this image isn’t provided, the tile can display only in the square format and can’t accept notifications based on wide template types. Since the user can decide which format the tile uses it is recommended that you include a wide logo image. Also note that if a wide logo image is provided, the tile will appear initially in its wide format.

    - The square image specifies the smaller logo that appears in the tile to identify the game in the normal sized, square tile. It should be 150 x 150 pixels.

    - The next image is the store icon, which is a 50x50 pixel image.

    - The final small icon is the logo image that appears next to the App name in the search bar and other areas of the UI.

  • Foreground Text: Sets the value of the text colour relative to the background colour on the app’s tile in Windows. The value is either “Light” or “Dark”.

WARNING: If you have any functions in your Windows 8 game that require an internet connection, like an open URL call for example, then you must have the "internetClientServer" capability ticked for the game. Microsoft also specifies that if you use this capability you need to add a link to your Privacy Policy in the Settings pane of your Windows 8 game (see here for further details). This can be done using the Settings Charm Functions in your game.

Graphics

Here is the option to set the size of the Texture Page. The default (and most compatible) size is 1024x1024, but you can choose from anywhere between 256x256 up to 2048x2048. There is also a button marked View which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

You can also set the way that your game should react to being scaled in any way (either by dragging the window borders or by full screening it). This can either be keep Aspect Ratio or Stretch. There are also extra options for Native Windows 8 apps, which permit you switch on or off interpolation and v-sync for the game.

WARNING! Switching off the application surface will disable all the scaling options set in the Global Game Settings until it has been switched back on again. See The Application Surface for further details.

Installation

GameMaker: Studio supplies two default Developer Keys for Windows8 development (one each for the Native and JavaScript modules), but it is recommended that you generate your own and point to it here. To do this, create an empty project in Visual Studio Express then store somewhere safe a copy of the automatically generated *.pfx (the developer key) that it will have included in the empty project. You should then link that *.pfx file here.

After linking to the file, you should click on the associated Install button and then follow the instructions in the command prompt that will open. If you do not do this then using the Run/Debug buttons (or hitting F5) will fail and your game cannot be tested (however, if you use Create Application the certification installation process will automatically be launched if the *.pfx has yet to be registered).

Finally, for Native Windows 8 development there is a drop down menu where you can select the device to target, which can be either x86 or ARM.

NOTE: When it comes to uploading your app to the store you will need to get the correct *.pfx for your title. This is done via associating your app with the Windows Store in Visual Studio which causes Visual Studio to generate a new *.pfx specifically for the app. It is also worth noting that you can associate any app with the Windows Store in Visual Studio, meaning you can associate a blank project with the Windows Store app and simply copy the generated pfx to a safe location which can then be used within Global Game Settings.

Permissions

Depending on what you want your game to have access to, you may also need to check the permissions from the Permissions tab. If your game uses (for example) the function url_open() then you would need to check the "Use Internet" box. The available permissions are:

  • Use Internet: Marks the game as having access to internet.

  • Use Search: Marks the game as having access to the Windows8 search functions.

  • Use Microphone: Marks the game as having access to the microphone of the device.

Back: Global Game Settings
Next: The Windows UWP Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Windows Tab

This section deals with the Windows tab of the Global Games Settings Window.

This Windows tab is split into three separate sub-tabs (accessible on the left of the window) to make changing and updating the information for your game clearer and less complicated. These tabs are explained in the following sections.

General

The General tab for Windows games is where you should supply the necessary information for Windows to display when your game has been installed and is running. This information goes in the Version Information section, and should be filled out completely.

The other two sections of this tab are related to the way your final game is shown once started, with the Splash Screen being the graphic that is shown while your game is loading, which can be enabled or disabled using the appropriate check-box, and the Options controlling whether you should display the standard Windows cursor or not and the icon that your game should show. You may also choose where the game bundle is to be installed to, either the "%localappdata%" or "%appdata%" folders.

NOTE: Being able to change or enable/disable the splash screen is a Pro Only feature.

The final option is for setting the Windows Sleep Margin. This option is related to reducing stuttering when running your game on specific systems. Basically, if your game is running faster than your room speed GameMaker: Studio will "sleep" for the remaining time, but this sleep can be quite inaccurate and you can often end of sleeping for longer than necessary, causing your frame to take longer which causes stuttering. To get around this we can sleep for less time, then sit in a tight loop for the remainder of the time to make it more accurate - although the problem with sitting in a loop is that it causes CPU usage to increase, which in turn can cause your CPU temperatures to rise and your fan to run faster. By default, this value is set to 1, and in 99.99% of the cases you'll be fine with this, but for low end machines or for machines with a lot of background processes running this may not be an ideal solution and a value of 5 or 10 may be required. Note though that this is very much a system specific configuration and what works on your build machine may not be appropriate for another user, and as such if in doubt leave it set to 1.

Graphics

The graphics options are those that you should configure to determine how your game will use the graphics card of your target Windows PC. The following options are included for you to modify:

  • Start in fullscreen mode - If this is checked, the game will start in fullscreen mode.

  • Interpolate colours between pixels - Turns on interpolation, which basically "smooths" pixels. for crisp pixel graphics, it should be off, but if you have nice alpha blends and smoothed edge graphics it is better left on.

  • Force software vertex processing - This forces GameMaker: Studio to use the CPU for all graphics and is only recommended if there are compatibility issues with older machines.

  • Use synchronization to avoid tearing - This toggles v-sync on or off. Note, that if you have a game with a room speed of 120 and the player has a monitor with a refresh rate of 60, turning this option on will lock your game speed to 60 too. There is an alternative v-sync mode available should the game still have issues like stuttering or tearing even with v-sync on - see alternative synchronisation method below.

  • Allow the player to resize the game window - Checking this permits the user to change the size of the game window.

  • Scaling - Here you can choose to maintain aspect ratio (so a 4:3 room will be "letter boxed" on a 16:9) or to scale fully (stretching the image to fit the full screen).

  • Allow Switching To Fullscreen - With this ticked the user can switch from fullscreen to windowed and back again using the standard Windows shortcuts.

  • Borderless Window - Checking this will make your game run with a borderless window, removing the normal minimise, maximise and close buttons as well as the game title.

The following are considered advanced options for rendering to the Windows target module and should generally be left at their default values. However should you be experiencing graphics issues, in particular with older machines, then you may benefit from changing these:

  • Create Textures on Demand - Checking this will make the windows target work like all the other targets, ie: texture pages will be loaded into memory on demand and can be flushed again when required. This can cause a few milliseconds of pause in your game as the texture pages are loaded, and so should be optimised such that the textures required for a level are loaded at the start of the room to minimise impact.

  • Vertex Buffer Method - This option can be used to change the way that the game geometry uses the vertex buffer. The options are:

    • fast - This is the default method and is the one recommended by Nvidia - it should give the highest performance.
    • compatible - This is the deprecated method that GameMaker: Studio used to use before adopting the fast method - poorer performance on newer machines
    • most compatible - This is the legacy method that was used in previous versions of GameMaker - performance is poorer than the other two, but it should be compatible with almost any machine.
  • Alternative Synchronisation Method - Change the way that vertical synchronisation works to improve compatibility and resolve any issues with stuttering or tearing that the regular v-sync may show on older machines.
WARNING! Switching off the application surface will disable all the scaling options set in the Global Game Settings until it has been switched back on again. See The Application Surface for further details.

Finally there is the option to set the size of the Texture Page. The default (and most compatible) size is 2048x2048, but you can choose from anywhere between 256x256 up to a whopping 8192x8192! There is also a button marked View which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

Installer

Windows games are created with an installer (previous versions of GameMaker just made an *.exe) and here you can define the various settings and graphics that GameMaker: Studio will use when creating it. First of all we have the graphical options which will define the look of the installer itself:

  • Finished - The graphic that appears on the "Finished" page of the installer. Must be in *.bmp format and measure 164x314px.

  • Header - The graphic that appears while the installer is running. Must be in *.bmp format and measure 150x57px.

You can also point to a specific License Agreement (an example is supplied with GameMaker: Studio) and a custom NSI script (details here) should you need one.

Back: Global Game Settings
Next: The Windows UWP Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Windows UWP Tab

This section deals with the Windows UWP tab of the Global Games Settings Window.

In the Global Games Settings of GameMaker: Studio, you can find the different setup options related to how your final game will look when you create the executable for the target platform. Here we will look at the Windows UWP tab. It is split into three sub-tabs, each of which is explained in the sections below:

General

This section is where you should set up the details of your app like its name and any associated graphics. Below is a list of all the available options and what they represent:

  • Display Name: Specifies the friendly name for the app that is displayed to users (this string is localizable).

  • Package Name: This is the name of the package that you have created and should match that used for the Developer key that you have created for the game (see the Installation Sub-Tab, below).

  • Package Display Name: This is the "short name" of the package and should Ideally be the same as the Display Name

  • Publisher Display Name: This is the name of your company or the person that you wish to associate as the games publisher.

  • Version: The version number of your game.

  • Orientations: Specifies the orientations in which the game would prefer to be shown for the best user experience. The available options are:
    Landscape
    Portrait
    Landscape-flipped
    Portrait-flipped
    On devices that can be rotated, such as tablets, the game won't be redrawn for orientations that aren't specified with this property - for example, the game won't rotate if the device is rotated to a Portrait orientation but the property specifies only Landscape and Landscape-flipped orientations. On devices that can't be rotated, a game might be shown in that device's default orientation, and the game's preferred orientation will be ignored, however, your game's preferred rotation will be honored on devices on which a rotation lock has been activated. These orientation preference choices apply to both the splash screen and the game itself every time a new instance is launched.

  • Splash Screen: This is the screen that will be shown when you start your game, and it cannot be larger than 620 x 300 pixels. Click on the Update button to change it, then select set the Background colour for it.

  • Logos: These are the Windows 10 tile and icon logos that your game will use. It is worth noting that these images can be transparent *.png files, in which case they will be drawn over the Background colour specified in the appropriate section.

    NOTE: The background colour specified here also applies to the button colour in any app-owned dialog boxes and to the App Description page in the Store!

    - The large square image is the large live tile format and should be 310 x 310 pixels. Note that this will only be used on the desktop OS.

    - The next image is the wide version of the logo image, which appears when the tile appears in its wide format and should be 310 x 150 pixels. If this image isn’t provided, the tile can display only in the square format and can’t accept notifications based on wide template types. Since the user can decide which format the tile uses it is recommended that you include a wide logo image. Also note that if a wide logo image is provided, the tile may appear initially in its wide format.

    - The next square image specifies the smaller logo that appears in the tile to identify the game in the normal sized, square tile. It should be 150 x 150 pixels.

    - The final tile icon is for the small tile and should be a 71x71 pixel image.

    - The smallest icon is the logo image that appears next to the App name in the search bar and other areas of the UI.

  • Store Logo: Sets the icon to be used when shown in the Windows Store and it should be an image of 50x50px.

  • Foreground Text: Sets the value of the text colour relative to the background colour on the app’s tile in Windows. The value is either “Light” or “Dark”.

Graphics

In this section you can set the way that your game should react to being scaled in any way (either by dragging the window borders or by full screening it), and this can either be Keep Aspect Ratio or Fill Screen. Next is the option to set the size of the Texture Page. The default (and most compatible) size is 1024x1024, but you can choose from anywhere between 256x256 up to 8192x8192. There is also a button marked Preview which will generate the texture pages for this platform and then open a window so that you can see how they look. This can be very useful if you wish to see how the texture pages are structured and to prevent having texture pages larger (or smaller) than necessary.

NOTE: Be aware that the larger the size of the texture page, the less compatible your game will be.

WARNING! Switching off the application surface will disable all the scaling options set in the Global Game Settings until it has been switched back on again. See The Application Surface for further details.

Installation

For your game to run on the UWP platform it has to be certified correctly, and this is done from the Installation tab. You will first be required to give your publisher name, which is formatted as CN=<publisher_name_here>, and then give a path to your Developer Key. GameMaker: Studio supplies a default Developer Key for WindowsUWP development, but it is recommended that you generate your own and point to it here. To do this, create an empty project in Visual Studio Express then store somewhere safe a copy of the automatically generated *.pfx (the developer key) that it will have included in the empty project. You should then link that *.pfx file here.

After linking to the file, you should click on the associated Install button and then follow the instructions in the command prompt that will open. If you do not do this then using the Run/Debug buttons (or hitting F5) will fail and your game cannot be tested (however, if you use Create Application the certification installation process will automatically be launched if the *.pfx has yet to be registered).

NOTE: When it comes to uploading your app to the store you will need to get the correct *.pfx for your title. This is done via associating your app with the Windows Store in Visual Studio which causes Visual Studio to generate a new *.pfx specifically for the app. It is also worth noting that you can associate any app with the Windows Store in Visual Studio, meaning you can associate a blank project with the Windows Store app and simply copy the generated pfx to a safe location which can then be used within Global Game Settings.

The final option is to select the CPU architecture to target. You can choose between x86<&b>, x64 or ARM.

Permissions

Depending on what you want your game to have access to, you may also need to check the permissions from the Permissions tab. If your game uses (for example) the function url_open() then you would need to check the "Use Internet" box. The available permissions are:

  • Use Internet: Marks the game as having access to internet.

  • Use Microphone: Marks the game as having access to the microphone of the device.

Back: Global Game Settings
Next: The macOS Tab

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


More About Async Events

This is the event that will be triggered by any call-backs received.

An asynchronous event is one that is fired off when GameMaker: Studio receives a "call back" from some external source, which can be from the web or from the device running your game. Basically, you tell GameMaker: Studio to do something, like load an image, and it'll start to do this but continue doing whatever it else it has to do meanwhile its working. Then, when the request has been completed, a call-back will be sent to GameMaker: Studio and any Asynchronous Events defined for that type of call back will be fired. Please note that the Asynchronous Events are fired for all instances that have them, much like the key events, so you can do an http_get call in one instance, yet have the Asynchronous HTTP event in another.

NOTE: You should be aware that due to XSS protection in browsers, requests to and attempts to load resources from across domains are blocked and may appear to return blank results when using any of the following events.

There are various types of events associated with the Asynchronous event category, and they are all explained in the sections below:

  1. Image Loaded Event
  2. HTTP Event
  3. Dialogs Event
  4. IAP (In App Purchases) Event
  5. Cloud Event
  6. Networking Event
  7. Steam Event
  8. Social Event
  9. Push Notification Event
  10. Load/Save Event
  11. Audio Recording Event
  12. Audio Playback Notification Event
  13. System Event

Back: Advanced Use

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Audio Playback

Audio Playback Event

This is the sub event that will be triggered by any buffered audio queues being played back.

This event can only be triggered by the audio play functions and will return a ds_map stored in the variable async_load, containing different key/value pairs relating to the audio queue that has triggered the event. The event is triggered when you have selected an audio queue to playback and a buffer in that audio queue is finished playing.

The following keys will be available in the ds_map:

  1. "queue_id" - the queue index for the queue that has finished playing, as returned by the function audio_create_play_queue().
  2. "buffer_id" - the buffer ID for the buffer that is no longer being played from
  3. "queue_shutdown" - this is set to 0 during normal playback and 1 when the event is received because audio_free_play_queue has been called. When this is set to 1, you don't want to queue up any further data.

Since an audio queue can be created from multiple buffers, this event can be triggered multiple times for one queue as the end of each section of buffered audio is reached, hence the "buffer_id" key.

NOTE: The variable async_load is only valid in the asynchronous events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1. However, all further data-structures created from the event must be cleaned up using the appropriate functions.

Example of Use

In this example we will create an audio queue with 10 buffered audio sounds added to it and then play the queue:

audio_queue = audio_create_play_queue(buffer_s16, 11052, audio_mono);
for (var i = 0; i < 10; i++;)
{
audio_queue_sound(audio_queue, audio_buffer[i], 0, buffer_get_size(audio_buffer[i]));
}
audio_play_sound(audio_queue, 0, true);

Every game step now that the recording is detected will trigger an asynchronous Audio Recording event where you can deal with the recorded input something like this:

var queue = async_load[? "queue_id"];
var num = 0;
if queue = audio_queue
{
for (var i = 0; i < 10; i++;)
{
if async_load[? "buffer_id"] == audio_buffer[i]
{
buffer_seek(audio_buffer[i], buffer_seek_start, 0);
num = i;
}
}
if num == 9
{
audio_stop_sound(audio_queue);
audio_free_play_queue(audio_queue);
}
}

Here we check the queue ID and if it's the one we want, we then check the buffer ID to see which buffer has finished being played. We also then set a local var to that index value for checking later and set the buffer back to the start for that sound. Once our local variable reaches 9, indicating that the queue has finished, we stop the sound playing and free the queue.

Back: More About Async Events
Next: Audio Playback Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Audio Recording

Audio Recording Event

This is the sub event that will be triggered by any buffered audio recordings.

This event can only be triggered by the audio_start_recording() function and will return a ds_map stored in the variable async_load, containing different key/value pairs depending on the call-back from the function that has triggered the event.

The following keys will be available in the ds_map:

  1. "buffer_id" - the ID of the temporary buffer you can use to retrieve the audio data
  2. "channel_index" - the recording channel index as returned by the calling function that this data came from
  3. "data_len" - the length of data (in bytes) you've received

NOTE: The variable async_load is only valid in the asynchronous events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1. However, all further data-structures created from the event must be cleaned up using the appropriate functions. Also note that the temporary buffer in which all audio is stored with the map will also be removed at the end of the event so you should copy it to a custom buffer if you want to keep it for later use.

Example of Use

In this example we will create a custom buffer to store our recorded audio, and also set our game to record from input source 0:

channel_index = audio_start_recording(0);
audio_buffer = buffer_create(len, buffer_fast, 1);

Every game step now that the recording is detected will trigger an asynchronous Audio Recording event where you can deal with the recorded input something like this:

var channel = async_load[? "channel_index"];
if channel == channel_index
{
len = async_load[? "data_len"];
buffer_copy(async_load[? "buffer_id"], 0, len, audio_buffer, 0);
}

Here we simply check the "channel_index" key to make sure it matches the value returned when we started recording, and if it does we copy the contents of the temporary buffer created for this event into our custom buffer. After that you can do what you want with the custom buffer - you could play it using the dedicated buffer audio functions, you could process it and send it over the network, you could save it to disk... Once you have your recorded audio in a buffer, you can do basically anything you want.

Back: More About Async Events
Next: Audio Playback Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Cloud Event

This is the sub event that will be triggered by any of the cloud functions.

The Cloud Event is one that is triggered by the call back from one of the cloud_ functions, like cloud_synchronise. It actually generates a ds_map (more commonly known as a "dictionary") that is exclusive to this event and is stored in the special variable async_load (please see the individual functions for code examples that explain the use of this event in further detail). This ds_map has the following structure:

  1. "status": This holds the status code, where a negative value denotes an error, a description of which will be contained in the “errorString”. A value of 0 (or a positive value) indicates a success(see below for exact values), and the “resultString” will contain the returned data or a success message.

  2. "id": The id which was returned from the called function. If you fire off a series of cloud_ requests then you need to know which one you are getting the reply to, and so you would use this value to compare to the value you stored when you originally sent the request to find the right one.

  3. "description": The description of the last uploaded file.

  4. "resultString": This holds a string which is the data blob returned from the cloud.

  5. "errorString": returns an Error String for any error.

The exact meaning of the returned "status" map entry is explained in the following table:

Status Value | errorString / resultString | Description
-1 | errorString = "Not logged in to <SERVICE>" | You have not successfully logged in to the given Cloud Service
0 | resultString = recovered data | New game data downloaded from the cloud (following a cloud_synchronise call)
1 | resultString = "AlreadySynchronized" | No new data since you last called cloud_synchronise
2 | resultString = "ConflictDeferral" | A conflict was encountered, but the gamer chose to ignore it
3 | resultString = "GameUploadSuccess" | data from cloud_string_save or cloud_file_save was successfully uploaded to the cloud
-n | errorString = Description of error | Any other negative number means a synchronisation failure

NOTE: The variable async_load is only valid in these events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1.

Back: More About Async Events
Next: Networking Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Dialogues Event

This is the sub event that will be triggered by any user event function call-backs received.

Like the above events, the Dialogues event is only triggered when it gets a call back from one of the special asynchronous user functions, like get_login_async() (please see this function for an extended code example of how this event is used). These events are the ones that ask for some type of user input, which can be a name, login details, a number or a colour etc... As most devices do not like sitting in a loop waiting for a reply, they have to be asynchronous and GameMaker: Studio will continue to run in the background while these functions have a dialogue open and until they get the required user input which triggers this event.

Again, a ds_map is returned with the id held in the special variable async_load. The values held in this map will depend on the function used, and you should consult the individual entries for each function in this manual for more details.

NOTE: The map held in the async_load variable is only valid in these events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1 in all other events.

Back: More About Async Events
Next: IAP (In App Purchases) Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


HTTP Event

This is the sub event that will be triggered by any http call-backs received.

The HTTP Event is one that is triggered by the call back from one of the http_ functions, like http_post_string. It actually generates a ds_map (more commonly known as a "dictionary") that is exclusive to this event and is stored in the special variable async_load (please see the individual functions for code examples that explain the use of this event in further detail). This ds_map has the following structure:

  1. "id": The id which was returned from the command. If you fire off a series of http_ requests then you need to know which one you are getting the reply to, and so you would use this value to compare to the value you stored when you originally sent the request to find the right one.

  2. "status": Returns a value of less than 0 for an error, 0 for success and 1 if content is being downloaded.

  3. "result": The data received (string only), or the path to the file downloaded if you have used http_get_file().

  4. "url": The complete URL you requested.

  5. "http_status": The raw http status code (if available). This returns the standard web status code for most browsers, eg: 304 for "Not Modified" or 204 for "No Content", etc...

That is for when you use the http_post_string() function, but each of the http_ functions may return a slightly different map, so please refer to the manual entry for each function to find out the precise data that is returned for it.

NOTE: The variable async_load is only valid in these events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1.

NOTE: As async_load creates a ds_map, these functions are particularly useful when coupled with the json_encode and json_decode functions.

Downloading Files

There could also be additional data supplied by this map if you have requested files for downloading. In this case, the "status" will have a value of 1 and the ds_map will hold these extra keys:

  1. "contentLength": This is the size of file that the web server has said you should expect to receive (may be -1 if the server does not return this data).

  2. "sizeDownloaded": The size of the data that has already been downloaded.

Note that the event will not be triggered for every single data packet that is received, but will rather update at any time during the download within the main game loop. Also note that currently this functionality is only available for regular Windows target platforms.

Back: More About Async Events
Next: Dialogues Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


IAP Event

This is the sub event that will be triggered by any IAP call-backs received.

This event can only be triggered when you have activated In App Purchases for your game. If you have this functionality added, then the event will be triggered under the following circumstances:

  1. The store state changes.
  2. A product (or products) have been activated.
  3. The product and purchases have been restored.
  4. A product has been purchased.
  5. A product has been consumed.

The event will always create a special ds_map with an index ID stored in the built in variable iap_data. This map will always contain the key "type", which will hold one of the following constant values:

Constant | Description
iap_ev_storeload | This is triggered when a change is detected in the target platform store.
iap_ev_product | This event is triggered when a product is activated and will contain additional information about the product.
iap_ev_restore | This event is only triggered when you use the iap_restore_all function.
iap_ev_purchase | When a purchase has been completed, this event is triggered.
iap_ev_consume | When you use the function iap_consume it triggers this event.

Each of these possible event "types" will add extra keys to the iap_data ds_map, which can then be parsed to get the purchase or product information necessary. The exact contents of the iap_data map are listed below for each event "type".

iap_ev_storeload

When you activate your purchases, your game will try to contact the target store, triggering this event in the process. The iap_data map will then have an addition key "status", which will have one of the following constants as it's value:

Constant | Description
iap_storeload_ok | The store has been contacted and the connection is good.
iap_storeload_failed | There has been a connection error or for some reason the store is unavailable.

iap_ev_product

All activated purchases will trigger this event "type", but only once per purchase, so if you have activated ten products you should expect this event to trigger ten times. If you have received this event, the iap_data ds_map will hold the additional key "index" which holds the unique product ID string for the product being activated. You can then use the function iap_product_details along with this product ID to get further information.

NOTE: Google Play (Android) can only request details for products 20 at a time which can lead to quite long load times for applications with a significant number of products.

iap_ev_restore

When you call the function iap_restore_all it will trigger this event, adding a "result" key to the iap_data ds_map. This key will hold either true or false to indicate whether the purchase data has been successfully restored from the target store.

iap_ev_purchase

On requesting a purchase using the function iap_acquire this event type will be triggered. The iap_data ds_map will have the additional key "index" which holds the unique purchase ID value for the product being purchased. You can then use the function iap_purchase_details along with this purchase ID to get further information.

NOTE: If the product purchased is consumable then it must be used using iap_consume before a further purchase can be made.

iap_ev_consume

When using the function iap_consume this event type will be triggered. The iap_data ds_map will have the additional key "product" which holds the unique product ID string for the product being consumed.

NOTE: The iap_data ds_map created for the in app purchase event is only valid in this event and should not be accessed anywhere else in your game.

Back: More About Async Events
Next: Cloud Events

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Image Loaded Event

This is the sub event that will be triggered by any resource call-backs received.

This event is triggered when you load an image into GameMaker: Studio, as long as you have used a valid URL or path with the applicable load file function. For example say you want to load a background image, and only change the current background to the new one when it has loaded. Well you would have something like this in a create event or an alarm event (for example):

back = background_add("http://www.angusgames.com/game/background1.png", 0, 0);

This will now start to load the image into the device or the browser, but it will not block GameMaker: Studio while it waits for the file to be loaded. Instead GameMaker: Studio will keep running as normal until the image is loaded and the call back triggers the Image Loaded event, where a ds_map (more commonly known as a "dictionary") is created and stored in the special variable async_load. The map contains the following information:

  1. "filename": The complete path to the file you requested.

  2. "id": The ID of the resource that you have loaded. This will be the same as the variable that you have assigned the resource to.

  3. "status": Returns a value of less than 0 for an error.

You would then assign the newly loaded image to a background in this event. The above is also true for sprites and sounds, with a ds_map being generated for each of these resources as shown above, and the following code example demonstrates how the returned information would be used in this event:

if ds_map_find_value(async_load, "id") == back
{
if ds_map_find_value(async_load, "status") >= 0
{
background_index[0] = back
}
}

The above code will first check the id of the ds_map that has been created, then check the status of the callback. If the value is greater than or equal to 0 (signalling success) the result from the callback will then be used to set the background index to the newly loaded image.

NOTE: The variable async_load is only valid in these events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1.

Back: More About Async Events
Next: HTTP Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Load/Save Event

This is the sub event that will be triggered by certain loading and saving functions.

This event will be triggered by certain functions related to loading and saving buffers to files, as well as when loading or unloading audio from memory. The event itself will contain the built in async_load DS map which will be populated by the keys required for the specific function. These are listed below.

NOTE: The variable async_load is only valid in the asynchronous events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1 for all other events.

Buffers

When you use the functions buffer_save_async() or buffer_load_async() an asynchronous event will be triggered when the data transfer has been completed. This event will populate the async_load map with the following key/value pairs

  1. "id": the ID of the async function as returned by the function used.
  2. "status": will return true if the data was saved/loaded correctly, and false otherwise.

This permits you to poll the saving/loading progress and display a message or change rooms etc... when the process is complete.

Audio Groups

When working with Audio Groups, you can load them an unload them from memory using the functions audio_group_load() and audio_group_unload(). When using the load function, it will trigger this event when the full set of audio files set for the group has been loaded into memory and will populate the map with the following key/value pairs:

  1. "type": this tells us the type of event being called and will be "audiogroup_load" for loading audio.
  2. "group_id": will return the ID of the audio group that has been loaded (as defined in the Global Game Settings Audio Groups Tab)

When all audio has been loaded for a group, this event will trigger and it can then be used to change rooms, or play a music track etc...

Back: More About Async Events
Next: Audio Recording Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Networking Event

This is the sub event that will be triggered when using the networking functions.

The Networking event is one which will be triggered by any incoming network traffic, and is linked to the Network Functions. This event generates a special ds_map (more commonly known as a "dictionary") that is exclusive to this event and is stored in the special variable async_load. This ds_map will contain different information depending on the type of network event that generated it.

Common

The following keys are common to all received network functions and will always be present in the async_load map:

  1. "type": This will have one of the constants listed below as its return value, and designates the network event type.

  2. "id": The socket id (a real number, as returned by the network_create_server or network_create_socket function) that is receiving the event. In most cases the socket ID returned is the ID of TCP or UDP socket that triggered the event, however if the event is triggered in a server and it's a Data Event (see below) then the socket ID is that of the client that sent the data.

  3. "ip": The IP address of the socket (as a string).

  4. "port": The port associated with the IP address (useful when working with UDP).

The possible return values for the "type" key can be any of the three constants listed below:

Constant | Description
network_type_connect | The event was triggered by a connection.
network_type_disconnect | The event was triggered by a disconnection.
network_type_data | The event was triggered by incoming data.
network_type_non_blocking_connect | The event was triggered by a connection configured as non-blocking (you can use the function network_set_config() for this).

Connecting / Disconnecting

When you have an event of the type network_type_connect, network_type_non_blocking_connect or network_type_disconnect, the async_load map will have the following additional keys:

  1. "socket" or "id": This key will hold the connecting/disconnecting socket id.
  2. "succeeded": This key will be either 0 or 1, where 0 means the connection timed out and 1 means it succeeded and the socket is ready to use.

It is worth noting that the Networking Event does not get triggered in clients when the server disconnects, and that neither of the network_type_* events will be triggered in clients when the server they are connected to disconnects, even if the connection is TCP based.

Receiving Data

When you have a network_type_data type event, which signifies that your network has received data, the map created will have the following keys:

  1. "buffer": This is the unique "buffer id" which is generated by the event. A "grow" type buffer, byte aligned to 1, is created to hold the id should be stored in a variable and used for all further function calls to the buffer in this event. Just like the async_load map, the buffer created is automatically removed from memory at the end of this event. For more information on buffers, please see Reference - Buffers

  2. "size": This is the size (in bytes) of the buffer data that is being received.

NOTE: The map held in the async_load variable is only valid in these events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1 in all other events. If you have received data, then the same will happen with the buffer created - it is only available in this event and will be freed when the event is over.

Back: More About Async Events
Next: Steam Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Push Notification Event

This is the sub event that will be triggered by any of the push notification functions.

The Push Notification Event is one that is triggered by the call back from push notifications on the device OS, either from a local source using the function push_local_notification, or from a remote source (ie: your server). It generates a ds_map (more commonly known as a "dictionary") that is exclusive to this event and is stored in the special variable async_load (please see the individual functions that trigger asynchronous events for code examples that explain the use of this event in further detail). This ds_map has the following keys:

  1. "type": Value can be "local" for a device local notification, "remote" for a remote notification, or "register" for remote notification registration.
  2. "status": Value will be "1" for success or "0" for an error.

There may be additional key entries based on the "type" returned and the "status" value. For "status", if an error has been returned ("0"), then you will also have the following key:

  1. "error": Contains details of the error received.

If the "status" value is 0 (ie: no errors) then the ds_map will contain the following additional values, depending on the value of the "type" key:

  1. "reg_id": If the "type" received was "register", then this key will hold the device registration id for remote notifications.
  2. "data": If the "type" received was "local" or "remote", then this key will hold the string payload that you defined when you called the notification function.

Example of Use

In this example we will send a local push notification using the following code:

var fireTime = date_inc_day(date_current_datetime(), 1);
var data = "daily_reward";
push_local_notification(fireTime, "Ahoy!", "Catch The Haggis Has A Present", data);

This will set a timer to "push" a notification to the device when one day has passed. When the day is up, if your game is either in the background or not running, a notification will be shown to the user with the given title and message (on iOS, the game name is shown and the title is ignored), and then an asynchronous Push Notification Event will be called. Note that if the game is in the foreground when the time for the notification comes, it will not be shown, but the asynchronous event will still trigger. In the event itself you would handle the callback something like this:

var type = ds_map_find_value(async_load, "type");
var status = ds_map_find_value(async_load, "status");
if status == 0
{
//error of some kind
var error = ds_map_find_value(async_load, "error");
show_debug_message("error=" + string(error));
}
else
{
if type == "register"
{
global.reg_id = ds_map_find_value(async_load, "reg_id");
}
else
{
var data = ds_map_find_value(async_load, "data");
if data == "daily_reward"
{
global.Gold += 1000;
}
}
}

NOTE: The variable async_load is only valid in these events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1.

Back: More About Async Events
Next: Load And Save Events

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Social Event

This is the sub event that will be triggered by any Social API callbacks received.

This event can only be triggered by the various specific Social Functions and will return a ds_map stored in the variable async_load, containing different key/value pairs depending on the callback from the function that has triggered the event.

The ds_map will contain a number of keys, the most important of which is the "id" key. This will return a constant which can then be checked in code to determine which of the many callbacks the event has received. Once you have parsed this key and compared the value returned with the available constants, you can then continue to extract the rest of the information from the map.

Achievements And Leaderboards

The function pages on Social Gaming - Achievements and Leaderboards in the Reference section detail the functions and callbacks as well as the constants used to trigger this event, but there are also certain circumstances in which it will be triggered without a function call from the game that is running:

  • when your game is launched from the OS dashboard
  • when you complete a challenge
  • when another player completes a challenge
  • when the game is started from the OS dashboard by selecting a challenge

Any of the above callbacks will trigger the Social Event and an async_load map will be generated with the following details (note that there is a different "id" key value to define each of the different reasons that the event was called, but all other contents of the map are the same):

  1. "id" - The value of this key will depend on the type of callback triggering the event. it can be one of these constants:
    • achievement_challenge_received - A challenge has been received
    • achievement_challenge_completed - A challenge has been completed.
    • achievement_challenge_completed_by_remote - A challenge has been completed by the other player.
    • achievement_challenge_launched - The game was launched from the OS dashboard with the given challenge.
  2. "playerid" - The player id for the challenge.

  3. "issuerid" - The id of the person that issued the challenge.

  4. "state" - The state of the challenge, which will have a value of 0 - 3 (as a string) for invalid, pending, completed or declined.

  5. "message" - The text message for challenge.

  6. "issueddate" - The issue date for challenge

  7. "completeddate" - The completion date for challenge.

  8. "type" - The type of challenge given. Can be one of two constants:
    • achievement_type_score_challenge - A challenge based on the score value.
    • achievement_type_achievement_challenge - A challenge based on an achievement.
  9. "identifier" - The identifying string for the challenge.

  10. "score" - The score tied in with the challenge.

Example:

var ident = ds_map_find_value(async_load, "id" );
if ident == achievement_challenge_completed;
{
player_id = ds_map_find_value(async_load, "playerid");
issuer_id = ds_map_find_value(async_load, "issuerid");
state = ds_map_find_value(async_load, "state");
date_completed = ds_map_find_value(async_load, "completeddate");
date_issued = ds_map_find_value(async_load, "issueddate");
ach_type = ds_map_find_value(async_load, "type");
ach_ident = ds_map_find_value(async_load, "identifier");
ach_score = ds_map_find_value(async_load, "score");
}

NOTE: The variable async_load is only valid in the asynchronous events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1. However, all further data-structures created from the event must be cleaned up using the appropriate functions.

Facebook

Some of the Facebook functions will trigger a social asynchronous event and create a ds_map with some specific information. The information returned will depend on the "type" of event that has been called. You can check this by reading the "type" key from the ds_map, which will be the following string for a Facebook event:

  1. "facebook_permission_request"

When the event is triggered and is of this type, there will also be additional keys that can be checked:

  1. "requestId" - The request ID value returned by the facebook_request_xxx_permission() function that triggered the event
  2. "result" - This will be one of the following strings:
    • "granted" – permission(s) were accepted by the user
    • "denied" – one or more permissions were not accepted by user
    • "error" – an error occurred
  3. "error" - This will contain a description of the error, but is only present when "result" = "error".

Back: More About Async Events
Next: Push Notification Events

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Steam Event

This is the sub event that will be triggered by any Steam API call-backs received.

This event can only be triggered by the Steam API functions and will return a ds_map stored in the variable async_load, containing different key/value pairs depending on the call-back from the function that has triggered the event. The map will always contain the key "event_type" which can then be parsed to find the type of function that triggered the event and change the code required to suit.

NOTE: The variable async_load is only valid in the asynchronous events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1. However, all further data-structures created from the event must be cleaned up using the appropriate functions.

When calling any function to that triggers this event, it will generate a unique async ID value which should be stored in a variable and checked, as the async_load map will always contain an ID key which you can then parse and ensure that you are responding to the correct event. In fact, the map will always hold the following keys, regardless of the Steam function used to generate the async response:

  1. "id" - The async ID returned by the function that triggered the event

  2. "result" - The result of the operation (a real value). This will either be the GML constant ugc_result_success or some other real number. So you should check for this constant to ensure that the call was successful, and if otherwise somthing has not worked correctly. The rest of the possible values returned are shown as the result of the Steam "EResult" value and you should see steamclientpublic.h in the SDK headers for all 89 possible values.

  3. "event_type" - A string denoting the type of event (see below for the details)

Uploading

When using the Steam functions for uploading a leaderboard (either steam_upload_score() or steam_upload_score_buffer()) the returned ds_map will have the following key/value pairs:

  1. "event_type" - This key will hold the value "leaderboard_upload"

  2. "post_id" - This key should match the ID value returned by the upload calling function

  3. "lb_name" - This key holds the name of the leaderboard which was posted to

  4. "success" - Will be 1 if the post succeeded, 0 failed

  5. "updated" - Will be 1 if the leaderboard score was actually updated (ie: the new score was better) or 0 otherwise

  6. "score" - This key holds the score which was posted

You can see examples of this on the pages for the score upload functions.

Downloading Leaderboards

When using the Steam functions for downloading a leaderboard (steam_download_scores(), steam_download_scores_around_user() or steam_download_friends_scores()) the returned ds_map will have the following key/value pairs:

  1. "event_type" - This key will hold the value "leaderboard_download"

  2. "id" - This key should match the ID value returned by the download calling function

  3. "status" - The status of the callback, where -1 equals a failure or that no results were returned, and 0 equals a success.
  4. "lb_name" - This key holds the name of the leaderboard which was posted to

  5. "numEntries" - The number of "rows" of leaderboard data that is being returned.

  6. "entries" - A JSON object string that contains another ds_map, which will either contain the key "default" (signifying that no results are contained within) or the key "entries", which you can then get the value of. this returned value for "entries" will be a ds_list containing each of the ranks from the leaderboard, where each entry in the list will itself reference another ds_map which will contain the keys "name", "score" and "rank", and it may also contain a "data" key depending on the function used to upload.

Example of Use

In this example we will show how downloading score data works by requesting the top ten ranking for the given leaderboard and parsing its results in the Steam Async Event (for uploading examples, please see the appropriate function pages). To start with we need to request the scores with the following code:

score_get = steam_download_scores("Game Scores", 1, 10);

This will send off a request to the Steam Server for the scores from the leaderboard "Game Scores", storing the async ID of the request in the variable "score_get". This will then be handled in the Steam Async Event in the following way:

var async_id = ds_map_find_value(async_load, "id");
if async_id == score_get
{
var entries = ds_map_find_value(async_load, "entries");
var map = json_decode(entries);
if ds_map_exists(map, "default")
{
ds_map_destroy(map);
exit;
}
else
{
var list = ds_map_find_value(map, "entries");
var len = ds_list_size(list);
var entry;
for(var i = 0; i < len; i++;)
{
entry = ds_list_find_value(list, i );
steam_name[i] = ds_map_find_value(entry, "name");
steam_score[i] = ds_map_find_value(entry, "score");
steam_rank[i] = ds_map_find_value(entry, "rank");
if (ds_map_exists(entry, "data"))
{
var data = ds_map_find_value(entry, "data");
var buffId = buffer_base64_decode(data);
var message = buffer_read(buffId, buffer_string);
show_debug_message( " -- attached message: " + string(message));
buffer_delete(buffId);
}
ds_map_destroy(entry);
}
ds_list_destroy(list)
}
ds_map_destroy(map)
}

What we do here is first check the "id" key of the special async_load map. If this value is the same as the value of the original call-back function (stored in the "score_get" variable) we then continue to process the data. The first thing we do is parse the async_load ds_map for the key "entries" which will contain a JSON object containing the leaderboard data. This JSON object is then decoded (see json_decode) as another ds_map, and this new map id is stored in the variable "map".

This map is checked for the key "default" and if that is found then the map is destroyed and the event is exited. If no "default" key is found, the code will then parse the map to extract the necessary information about the leaderboard, by first extracting a ds_list from the "entries" key of the ds_map, and then looping through each entry of the list to get another ds_map with the name, score and rank of each entry. These values are then stored in arrays and then we check to see if there is an additional "data" key. If there is (ie: the score was uploaded with an additional data package) then we also parse that and send it to the compiler console for debugging, before destroying the buffer and then continuing on to destroy the map. Note that if the "data" key is included, it needs to be decoded using the buffer_base64_decode() before it can be correctly read.

Once the loop has finished, the entries list is destroyed as is the map that it was taken from. There is no need to destroy the async_load ds_map as this is handled for you by GameMaker: Studio.

Downloading UGC

When using the Steam functions for downloading User Generated Content (UGC), a number of them will trigger this event. However, each function will generate an async_load ds_map with differeing key/value pairs (although they will always contain the general "id", "result" and "event_type" keys), so please see the page specific to the function being used for details and examples.

Unique UGC Events

The Steam Async event can also be triggered when a user subscribes to an item outside of the game - for example, they tab away to a browser and subscribe to a new item then tab back to the game. In these cases the async_load map will only contain the following details (and none of the default values listed at the top of this page):

  1. "event_type" - This key will hold the value "ugc_item_installed"

  2. "published_file_id" - the ID of the newly installed UGC item (you can use the function steam_ugc_get_item_install_info() to get the path to the installed item)

The Steam Async event can also be triggered when a workshop item is subscribed to - either from within the app, or externally from a workshop browser - and in these cases the async_load map will contain the following key/value pairs:

  1. "event_type" - This key will hold the value "ugc_item_subscribed""

  2. "published_file_id" : This key has the published file ID of the newly subscribed item

The event will be triggered should any item be un-subscribed too, with the DS map holding the following:

  1. "event_type" - This key will hold the value "ugc_item_unsubscribed""

  2. "published_file_id" : This key has the published file ID of the un-subscribed item

Back: More About Async Events
Next: Social Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


System Event

This is the sub event that will be triggered by any system level event like adding or removing a gamepad.

This event can only be triggered by a system level event (currently the only event detected is the addition and removal of gamepads, but more shall be added) and it will return a ds_map stored in the variable async_load, containing different key/value pairs depending on the system level event that triggered the call-back.

Gamepads

When this event is triggered for a gamepad being connected or disconnected it will return one of the following key/value pairs in the async_load map:

  1. "event_type" - the type of system event received, which will be one of the following strings:
    • "gamepad discovered" - happens when the system reports a new gamepad has been connected
    • "gamepad lost" - happens when the system has lost connection to a gamepad
  2. "pad_index" - the index of the pad that has been added or removed

This event now permits you to move all your gamepad checking logic from the Step Event or an Alarm event into the System Event and only run it when it's actually required.

NOTE: The variable async_load is only valid in the asynchronous events, as the ds_map that is points to is created at the start of the event, then deleted again at the end, with this variable being reset to a value of -1. However, all further data-structures created from the event must be cleaned up using the appropriate functions.

Back: More About Async Events
Next: Image Loaded Event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


More About Backgrounds

This section deals with some of the more complex aspects of working with backgrounds and tiles.

When dealing with backgrounds and tiles (and to a lesser extent, sprites) in GameMaker: Studio it is important to understand how they are processed internally, as you may discover graphical artefacts or glitches in your games due to not configuring your textures correctly for the use you wish to put them to. This is normally not an issue unless you are scaling the image, but when designing for devices other than PC or Mac then scaling is almost inevitable due to the differing screen sizes and the need to adapt your game to them.

You also have to take into account how the images are stored internally by GameMaker: Studio on the generated texture pages, as, if not done correctly, this can also lead to your game being slow or buggy on devices.

The following sections deal with some of the more complex aspects of designing backgrounds and tiles for your games, as well as the use of texture pages:

  1. Designing Tiles
  2. Texture Pages

Back: Advanced Use Index
Next: More About Objects

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Designing Tiles

Tiles are a very important graphic resource for your games, but their design and use can sometimes be problematic.

Tiles are a graphic resource which can add colour, detail and interest to your games with very little processing overhead due to the fact that they have very few "built in" properties and do not generally interact with any instances once placed in a room. However, they do need to be prepared carefully before use, especially if your target device is something other then the PC or Mac, or if you are planning on scaling them up or down. Let's start by looking at an image of a typical problem that can occur when using tiles in your game and then having the view scaled: The image above shows the kind of visuals you can expect to get if you zoom in on a typical tileset that has been created with a space between tiles. Now, most tiles are like this, with spaces around the edges, or they are placed all together in one solid image where the tiles actually touch each other, but unfortunately when zooming out and (in particular) in, this can cause some really nasty issues to solve if your not sure why it's happening in the first place. It's also one of these bugs that you'll be convinced is GameMaker: Studio's fault, after all... if it allows you to scale the tiles, it should work! Well, it does work, but only if you know how the graphics are drawn and prepare your resources accordingly. Let's take a look at a couple of normal tile sets that you might create: These are the most common ways that people create tile sets - either all jammed up together or with little spaces separating them out. Now for a non-scaling game, this is normally fine and you can happily predict what the device will render meaning you pretty much create the tile set anyway you like. But... what happens if we scale them? What does the device actually do? The image shown below illustrates how tiles are mapped generally mapped by the device graphic drivers, with the red line around the tile showing where the U,V coordinates are mapped to (The letters "U" and "V" are used to describe the 2D texture mesh because "X", "Y" and "Z" are already used to describe room and object spatial coordinates): As you can see it picks the center of the texel (a texel is just a pixel in a texture map) to map directly when drawing the image in the room. Now 1:1, this is all well and good... but what will happen when we scale this tile down? The issue with scaling down is that when you shrink, the UVs also scale down and try to fit into a more compressed space, but this obviously can't happen, so graphics driver picks which pixels to draw based on the available pixel centers. So, if we are "just" moving into a new screen pixel then, because the graphics drivers use the center of the pixel to decide what to draw with, it'll pick a texel surrounding the tile, not a texel on the tile itself. Shown above is a tile being draw scaled down into 6 screen pixels, and this shows that when you overlap a little into the next screen pixel, the graphics driver has to make a choice to either drop that texel, or it try and fill it with what it thinks is a valid texel. Let's just say that in this case it decides to draw the overlapped texel into the screen pixel, and, since it's now clearly outside our tile it gets this pixel from either the next tile, or the little bits of space you provided around the tiles, which means that when it shrinks you'll get cracks between tiles "glitches" in how they are drawn and this is where a lot of confusion arises... Each graphics driver and device actually does this in its own way, meaning that the results can be unpredictable and look terrible... but if you're careful and plan ahead you can work around it.

With high end games if you draw from a single texture (not on a texture page or texture atlas), you have the option of using a texture mode called clamp and what this does is repeats the last row of texels infinitely off into the distance, allowing you to scale without problems as it forces the hardware to get the last row of pixels no matter what. However, when using a texture pages in GameMaker: Studio with tiles, you must "fake" this yourself (for more information on texture pages see More About Backgrounds: Texture Pages). Shown above is a "fixed" tile set and you can see it now has a repeated section around each tile meaning that when the hardware overruns, it will always pick the last texel from the tile rather than one of the spaces or the tile after that! When importing these new tiles into GameMaker, it is important to make sure you point GameMaker to the tile inside the "smear" using the x and y offset options in the background resource window as this means you will still get the original tile while the device hardware can use the external area if necessary. The space between tiles is optional and may help you keep track of the tiles better within the tile sheet, but that's up to you. The image below shows how this would finally look when loaded into GameMaker: Studio: Note: All the tiles used on this page courtesy of Lost Garden.

Back: More About Backgrounds
Next: Texture Pages

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Texture Pages

This section deals with how GameMaker: Studio creates texture pages.

When you create a game with GameMaker: Studio, you will surely have created graphics to go along with it. These graphics are stored on Texture Pages which GameMaker: Studio builds for you from all the image resources (backgrounds, tiles and sprites) that your game contains. Below is an example of a completed texture page: As you can see, the game graphics are all jumbled up together in such a way that they all fit on a power of 2 sized page, eg 512x512, 1024x512 etc... up to a maximum size of 2048x2048 pixels page. Please note, that even if you have a resource that is larger than 2048px in size, this will be scaled down by half (and half again if necessary) until it fits on the maximum page size, it will not be split into sections over various texture pages. The section below details the options available to you for defining how your image resources are stored on these texture pages.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

Texture Settings

The sprite resource window and the background resource window both have a section titled Texture Settings, shown below: Here you can define how the image is to be stored on the texture page as well as whether it is an image specifically for use with a 3D object and which texture page (if any) it has to be assigned to. The first two options, Tile Horizontal and Tile Vertical relate to how the edges of the image will be created when placed on the texture page. An image that is to be tiled will have the edges (horizontal or vertical) added to by the edges from the opposite side, while if no tiling is selected the sprite will be clamped and the edges pixels will be repeated. The following image illustrates this: Underneath those settings is the Used for 3D setting. This option is only available if the image size is a power of 2 (eg: 128x128 or 512x512) and it will force GameMaker: Studio to place this image on its own unique texture page ready for use as a texture in your 3D world. There are no options associated with this as the tiling or clamping is controlled directly through code. Note: Take care when using this option as you can quickly use up all the available texture memory, especially on mobile devices, if you have too many texture pages.

Now, when your game is large with a lot of artistic resources, it may be that the way GameMaker: Studio automatically creates these pages is not the optimum for getting the most out of the target device, due to the fact that if a room in your game needs resources from 4 different texture pages, the device will have to swap these pages into (and out of) memory constantly, which may cause a loss in performance. To that end, you have the option to tell GameMaker: Studio what images are to placed on any specific texture page, with the final aim being to minimise the number of swaps being done in a game at any one time (texture pages can added from the Global Game Settings: Texture Groups tab). It is also worth noting that in the individual platform tabs that can be found in the Global Game Settings there is a button that permits you to view the texture pages that you have defined, as they would be created for each target.

It is worth noting that should you have a texture in your game that is larger than the texture page size, this image will be automatically scaled down by GameMaker: Studio to make it fit within the texture page. This means that when you test your game on Windows, Ubuntu (Linux) or MacOSX the game may look fine as you are using larger texture pages, but on iOS (or any of the other targets that require a smaller texture page size for optimal performance) the texture may look blurred or have artifacts. It is essential that you make sure your images are all able to fit on the smallest of the texture page sizes that your game will use, and if not then you should split them into smaller images and then draw them together in your game to give the illusion of one large, complete, image.

Note: Before you go off splitting up your graphics over various texture pages, you should be aware that this is not always necessary, nor is it always the most efficient way to work. Some games may be more CPU bound than GPU bound (see Advanced Use: Debugging) and those games will not benefit greatly from this optimisation, and you should also consider whether it would not be better to have all your images on two texture pages and swap between them rather than spread out over several, with each one having a lot of empty space that is just wasting memory.

Back: More About Backgrounds

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


More About Objects

This section deals with some of the more advanced properties available within the objects window.

All the basic object properties have been covered in the section Defining Objects, but two of them need a bit of further explanation due to the complexity of how they should be used within a game. These properties are Parents and the new Physics and the sections below have more information on them:

  1. Parents
  2. Object Physics Properties
Back: Advanced Use Index
Next: More About Rooms

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Parents

Parents are objects that form part of a hierarchy, grouping multiple "child" objects together.

One of the most powerful options within the object properties is the ability to assign a parent. Every object in the game can have a parent object, but what does this mean? Well, when an object has a parent, it can share code, actions and events with that parent. This is called "inheritance" and an object that has a parent is called a "child". But that's not all! You can also do checks and run code on parent objects which automatically include the child objects too which saves a lot of time and energy. Another way to look at a parent object is as a way to "group" objects together under the same umbrella and have them share certain things without loosing their own identity. Now, this may seem a bit complicated to understand so let's give some examples:

Say you have a player object and four different enemy objects. Now, you want the player to die if he touches any of these four objects and this would normally entail four collision events with four sets of actions or code, one for each of the enemy objects. BUT if we make a parent object for all the enemies, then we can create one collision event with the parent object only and it will trigger no matter which one of the four "child" enemy objects touch the player. Handy stuff! In the actual GameMaker: Studio object you would see something like this:

Another example would be if you have a game where you want to create 10 different objects and have them behave in the same way. Well you would create one parent object and in that have all your behaviour actions or code, and then you would create your ten objects with no actions or code, but different sprites, and assign them your parent object. Now, when you place these instances in a room they will all behave the same, but look different.

Finally you can use parenting to "mix and match" events and behaviours. Say you want two monsters: one that moves up and down, while another that move left and right, but you also want the two of them to have the same health and shoot at the player. In this case you can see that almost all events should have the same actions except for one or two that govern movement. So, again, we can make one object the parent of the other, but in this case we also define certain events for the child object. These events "override" the parent events, meaning that whenever an event for the child object contains actions, these are executed instead of the actions contained in the event of the parent. If you also want to execute the parent event you can call the so-called "inherited" event using the appropriate action or code.

As indicated, wherever you use a parent object, this also implies the descendants (or "children"). This happens when, in an action, you indicate that the action must be applied to instances of a certain object. It also happens when you use the with() statement in code (see further on in the manual), and it works when you call code functions like instance_position, instance_number, etc... Finally, it works when you refer to variables in other objects too, like, in the above monster example, if I set the monster 1 speed to 10, then the monster 2 speed will also go to ten as it is a child object of monster 1.

It is actually good practice in most cases to create one base parent object and have this base object contain all the default behavior but never use it in the game. Rather use all the children objects and only use the parent in situations like those I have outlined above. You should also realise that parents can have parents too! Obviously you can't create a cycle of "parent1 is child of parent 2 is child of parent 1" but you can create what is called "object hierarchy" where "parent1 is child of parent2 is child of parent3". This is extremely useful to keep your game structured and you are strongly advised to learn to use this mechanism.

Now you can see why parenting can really save a lot of time and work, and why it is one of the most useful tools in the GameMaker arsenal. So take your time to get to know this function as it will really help you in the long run!

Back: More About Objects
Next: Object Physics Properties

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Object Physics Properties

You can set a number of physical properties for an object that will set how it behaves when placed in a physics world.

When you first create a new object resource, there is a checkbox at the bottom on the left marked Uses Physics, which is normally not checked. Selecting this option will radically change the behaviour of your object when an instance of it is placed in a room, as this switches on the object's physical properties and means that its "traditional" movement and collision functions are no longer valid (but only when the room it is placed on is also marked as being a physics room. See - More About Rooms: Physics). When you check this, the object resource window expands to show the following:

Collision Shape

With the normal collision system you had your collisions based off of the mask of the sprite assigned to the object, but with the physics switched on, this is no longer the case. We need to assign a mask to the object ourselves (actually, this is really a "fixture", see The Physics Functions for more information), which can either be a circle, a rectangle or a polygon shape that you yourself define. Once you have selected the shape you can then click on the Modify Collision Shape button which will open the following window: This looks similar to the Path Editor, and functions in much the same way, however, depending on the mask you have chosen, it can be rather more restrictive:

  • If you have a circular mask, then you can only pull any of the path points to make the circle diameter larger or smaller
  • If you have rectangular mask, then you can move any of the four corners, but the corresponding ones will adjust position automatically to always maintain a rectangle
  • If you have a custom mask, it must have a minimum of 3 and a maximum of 8 points to it, and it must be convex (see image below).

Physics Properties

Once you have set up your shape, you then need to define the basic physical properties that your object is to have. These are configured by changing the following parameters:

  • Density: The density of something is defined as its mass per unit volume, which basically means how much mass is crammed into the space it takes up in the world. So, a balloon would have a low density as it has little mass that occupies a large space, while a lead bar would have a high density as it has a great mass, yet occupies little space. In the GameMaker: Studio 2D physics world mass is calculated automatically for you from the values you input for the density and by the surface area of the shape you define for the fixture. This will have a direct impact on how much inertia a fixture has as well as how it reacts to collisions and forces, so if you make a small shape with a high density it will have a very large mass (like a bar of lead), but if you define a large shape with a low density it will have a much smaller mass (like a ballon).

  • Restitution: In physics, restitution is defined as "the return of an object or system to its original state after elastic deformation", but as the fixtures in the GameMaker: Studio are really rigid bodies and cannot be deformed, restitution is really a way of saying how "bouncy" the fixture is. This setting will affect how much an object "bounces" when it collides with other objects and is co-dependant on other forces that act on the instance like gravity and friction.

  • Collision Group: By default, the collision group for all physics objects is 0, and this means that they will interact as normal, which means they must have a collision event to interact (a simple comment will do to trigger the collision) otherwise no collision will be registered. However, you can also specify that an object should belong to a specific collision group. Now, by assigning objects to a positive collision group (ie: three objects are all in group "2") you are telling GameMaker: Studio that instances of these objects should always collide, even if they have nothing in their collision event, obeying the physical properties that you have assigned them and the room they are in. Conversely, if you have objects with a negative collision group (ie: four objects assigned "-1"), you are telling GameMaker: Studio that these should never collide, and any collision events between them will be ignored. Note: Using collision groups dramatically increases the processing required by the physics system and should be used only when absolutely necessary, and you should have as few groups as possible!

  • Linear Damping: Damping is used to reduce the physics world velocity of an instance, and differs from friction in that friction only occurs when two instances with collision shapes (fixtures) are in contact. Damping is also much cheaper to simulate than friction, but please note that damping is not a replacement for friction; the two effects can, and should, be used together.

  • Angular Damping: If you think about any rotating object in the "real world", unless it has a motor or is in space, it slows down over time due to the influence of external forces (like friction with the air around it). We can use set this option to simulate this effect and reduce the velocity of rotation of instances in the physics world, as, without it, any rotating instance would continue to rotate infinitely.

  • Friction: Friction is the force that resists the relative motion of material elements sliding against each other, which in the GameMaker: Studio physics world, translates as the loss of momentum caused by the collision of two instances with fixtures bound to them. So, when two instances collide, their motion is affected by this value, with a high friction causing a larger loss of momentum than a lower value.

Finally there are three extra options that can flagged as on or off for your fixture, Sensor, Start Awake and Kinematic. Each of these flags will change the behaviour of your fixture in the following ways:

  • Sensor - By checking this box, you are telling GameMaker: Studio to basically "ignore" the physical properties of the object, but still return a collision event with the objects around it. in this way you can have an instance with no physical presence in the room, but which can react to the collision of another instance, like the player, and do something in turn, like open a door, or trigger some sort of action in another place in the room.

  • Start Awake - This is checked by default and represents the initial "state" of the fixture at the start of the room it has been placed in. Normally you want it to be awake (ie: participating in the physics world) right from the start, but sometimes this can lead to certain instabilities and unwanted effects due to the abrupt start of the physics simulation. To avoid these effects, you can un-check this flag and the instance will be created with the fixture asleep, and it will not participate in the physics simulation unless something acts upon it.

  • Kinematic - There will be certain instances in a physics based game which you want to move around but do not wish to be acted on by forces such as gravity, nor forces incurred by collisions with dynamic objects (think of moving platforms in a platform game, for example). For such objects simply setting the density of the fixture to 0 will mean that the physics will assume that the object is intended to be static and it will not react at all to anything. However, checking this box will make a static object kinematic and although it will be unaffected by collisions and gravity, it can still be moved around or rotated using the appropriate variables.

NOTE: A sensor fixture will fire off the collision event when the collision first occurs only, meaning you don't get a stream of collision events as the two bodies continue to overlap (which is what would traditionally occur). If they stop overlapping and overlap subsequently there will be another collision event triggered.

Back: More About Objects

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


More About Rooms

This chapter covers the more complex aspects of Rooms in GameMaker: Studio.

In a previous section of the manual (see Using GameMaker: Rooms) we covered the Settings, the Objects, and the Backgrounds tabs, but there is still much that the room editor can do, and these advanced features will be covered in the sections below.

The Right Click Menu

A very important tool when it comes to using the room editor is the Right Click Menu. If you place an instance within the room and then right click on it with the mouse, you will see the following pop-up menu:

  • Delete: This will delete the instance selected.

  • Delete All: This will delete all the instances found at the point where you clicked in the room.

  • Edit Object: Use this to open the object properties window.

  • Creation Code: This option opens up a code editor where you can add code into the specific instance that you have clicked on. This is a very powerful feature that allows you to further change individual instances of objects and so give several instances different values or variables to change their behaviour. This code is run after the normal create event, but before the room start event (see Using GameMaker: Events for the complete order of events).

  • Instance Properties: Clicking this will open a further window where you can set some of the basic start properties for the instance, like blend colour, image angle, scale and alpha.

  • Change Position: All this does is permit you to place the instance exactly at any position within the room. A window will open where you can input a new x and y position, and when you close it the instance will change to the new position.

  • Snap to Grid: This will snap the instance to the nearest node of the defined room grid.

  • Copy Selection: This will copy the currently selected instance (or instances) to the clipboard. Multiple instances can be selected using <Shift> and Left Clicking on them.

  • Paste Selection: This will paste the instance (or instances) currently on the clipboard, and this can even be used in a different room so that you may copy instances from one room to another.

  • Locked: Clicking this will "lock" the instance, meaning that it cannot be moved or deleted from the room without previously unlocking it again (right click and select "Locked" again to unlock).

  • Rename Object Instance: This option permits you to give your instance a name. Normally an instance is given an "id" when it is created, which is usually something like "inst_A4F595D9". Now there are many moments when creating a game that you wish to refer to a specific instance through code, and remembering a name like that is not easy! So you can assign a name to it by selecting this and use that as a constant to refer to this instance from now on. Be aware that referencing an instance in this way after it has been destroyed may cause an error.

  • Copy Instance Name: Simply copies the name of the instance into the clipboard.

The remaining tabs in the room editor are detailed in the sections below:

  1. Tiles
  2. Views
  3. Physics

Back: Advanced Use Index
Next: Fonts

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Physics

This section deals with the use of physics in the room editor.

The addition of physics to GameMaker: Studio means that you can add a much greater level of realism to your games, with better collisions and movement than ever before. However this is not always necessary, nor is it the default behaviour for your game. If you do wish to use physics, you must tell GameMaker: Studio this and set up some basic parameters, both in your object resources (see - More about Objects: Physics) and in your rooms.

The Physics Tab

Before your room can use physics you must tick the option at the top of this tab labelled Room is Physics World. Once you have done that you can then continue on to set up the Physics World Properties, which are some basic properties that you must have pre-defined before your room will allow physics objects to work as such. For a more precise control over the world you can use code (see - The Physics Functions for more information).

The next thing you must do is set up the Gravity of the world, and the strength and direction of this is calculated as a vector of the x/y position that you set. So, an x of 0 and a y of 1 will set the gravity direction as being down with a force of 1 metre per second (for a more detailed explanation see - The Physics World: Gravity). Finally you must set the ratio of Pixels To Meters for GameMaker: Studio to use as a base for all its physics calculations. This is because the physics functions work on real-world measurements, which is why we must set this value, and you'll want to adjust this setting until the average pixel size of the objects you are using translates roughly into simulated physics objects of an appropriate size.

Back: More About Rooms

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Tiles

This section deals with tiles and how to use them in the room editor.

In many games you will want to have nice looking backgrounds, made up of many details and that are eye-catching and interesting to the player. For example, in a maze game, the walls of the maze should nicely match up, and in platform games you like to see beautifully drawn platforms, trees, etc. However, to create hundreds of static backgrounds would take forever, and also not be very efficient as they would need a lot more device memory, nor would creating hundreds of individual objects with different sprites be a very good idea. So, instead, GameMaker: Studio allows you to use tiles. Tiles are a purely graphical resource that have very few properties and none of the overheads that accompany an object, and so they are processed and dealt with much faster by GameMaker: Studio when the game is run on the target device. A simple tile would be one for a wall in a maze, where your game has just one wall object with a square sprite assigned to it for collisions. This object is then flagged as invisible so that when playing the game you can't see it, and you would then create some nice tiles that cover the places where the wall objects are and make your levels look great.

You can use this technique for any graphic that does not have to change its shape or position (you cannot use it when the image must be animated - for that you must use an instance), and you can create some incredibly beautiful graphics for your game with very few resources just by mixing and matching tiles on each level. It should be noted that tiles need to be designed properly to work without any graphical errors and this subject is covered in the section - More About Backgrounds.

The Tiles Tab

To add tiles to your room you first need to add a background resource to your game that has been properly prepared to contains the tiles you need, and when adding the background resource indicate that it must be used as a tile set in the background properties. For more details on how to load a background as a tileset, please see the section Using GameMaker: Studio: Backgrounds.

If you look at the tiles tab in the room editor (also shown above), you can see at the top left the current background being used for tiling, but this can be changed by clicking on the menu button underneath. A list will be brought up which contains all the background resources in your game, and from there you can select the one you wish to use. Note, that if you select a background that is not flagged as being a tileset in the properties, you can still place it as a tile, but it will be the whole image that is placed, and not just a part.

Selecting a tile and adding it to the room is a simple matter of clicking on the background image itself to select the part you need (this will be automatic and depends on the settings of the background resource), and then clicking in the room on the right to place it. If you have previously placed tiles at the same place (or if they over-lap) within the room and at the same depth too, then the tile underneath will be removed by default, but this behaviour can be switched off by un-checking the Delete Underlying box. You can also position the tile using the X/Y input boxes on the form.

When placing tiles in the room, you place with the left mouse button and delete with the right, but you also have a few extra commands:

  • hold the <Shift> key to add multiple tiles one after another.
  • hold the <Ctrl> key and click on a tile to move it to a new position.
  • hold the <Alt> key to temporarily switch off snapping to the gird.
  • use the <Cursor Keys> to shift the selected tile 1 pixel in any direction.
  • use the <Cursor Keys> and hold the <Shift> key to move the selected tile 10 pixels in any direction.
  • use the <Cursor Keys> and hold the <Ctrl> key to move the selected tile 5 pixels in any direction.
  • use the <Cursor Keys> and hold the <Shift> and <Ctrl> keys to snap the selected tile to the nearest grid position in any direction

If you hold down the <Ctrl> key and right click on a tile with the mouse, the following menu will open: The commands available are very similar to those that open when you right click an instance and are as follows:

  • Delete: This will delete the tile at the current depth.

  • Delete All: This will delete all tiles found at this position in the room (at the same depth).

  • Tile Properties: This will open the following window - [image] which allows you to easily change some of the most common tile properties, like scale, blending and alpha.

  • Change Position: Opens a window where you can input precise x and y coordinates for the tile.

  • Snap to Grid: This will snap the tile to the nearest grid square as set by the room properties toolbar.

  • Locked: This locks the tile in position and also prevents it from being deleted. You can unlock a tile again by re-selecting this option.

  • Rename Tile Instance: You can use this to set a constant which will always point to this tile unless you delete it through code or change rooms.

In some situations you might want to put a part of the background tileset in the room that is not exactly the size of a standard tile, or that consists of multiple tiles, or even one that is offset from the standard tile grid. Well, this can be done too! In the top-left background image press the left mouse button while holding the <Alt> key. Now you can drag the mouse to create rectangular area, which you can then place in the room in the same way as any normal tile. If you want the area you create to snap to the tiles, then hold the <Shift> key instead when dragging (note that this works best when there is no separation between the tiles). If you want to select an area that is multiple of the room grid size, hold the <Ctrl> key rather than the <Shift> key, and it should be noted that you can actually change the key you hold during the dragging, which can be very useful.

Tile Depth

Tiles can be placed in layers at different depths, and if you look at the bottom of the tiles tab in the room editor you see the current depth you are placing them at. Default for this is 1000000 which is normally behind all instances (the higher the number, the further "behind", and the lower the number the further "in front"). You can use the Add button to add new tile layers, each with a different depth which you define, and in this way you can create different layers of tiles, and even objects if you also give the objects different depths so they are between the different tile layers. If you press Delete you can delete a tile layer together with all its tiles, but you must always have at least one layer, so even if you delete the last one, GameMaker: Studio will recreate a new, empty one for you again. If you press Change you can change the depth of a tile layer, which if you have given it the same depth as another layer, will merge the two sets of tiles together on the one layer.

Since it can be awkward sometimes to see exactly what you are placing in the room when you already have multiple tile layers in the room, you can also check the "Hide Other Layers" option, and all tile layers will be made invisible except the one that you are working on. This is purely for ease of use in the room editor and will not affect how the tiles are drawn in your project.

Back: More About Rooms
Next: Views

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Views

This section deals with views and how to use them in the room editor.

Views give a mechanism for drawing different parts of your room at different places on the screen, or for drawing just a part of your room to cover the whole screen. For example, in most platform games, the view follows the main character, as if you could see the whole level on the screen your character would be too small to see and there would be no surprises for the player! Views can also be used in two-player games, as they permit you to create a split-screen setup in which in one part of the screen you see one player and in another part you see the other player. A third use is in games in which part of the room should scroll (e.g. with the main character) while another part is fixed (for example some status panel). This can all be easily achieved in GameMaker: Studio using views.

The Views Tab

At the top of the views tab there is a box labelled Enable the use of Views, and this must be flagged before any of the views can be active in a game. The next checkbox is the one that says Clear Background with Window colour, which clears the application surface with the window colour, and can be unchecked if you know that you are drawing to cover the whole surface.

Below this you see the list of available views (you can define a maximum of eight) with the information about where these views are to be drawn contained in the boxes below. First of all you must indicate whether the view should be Visible when the room starts by checking the appropriate box, and if you wish to use views, make sure at least one view is visible at the start of every room. Visible views are shown in bold in the view list above this.

The View and The View Port

A view is defined by two different sets of values, the view itself and the port on the screen. This can sometimes cause confusion so let's explain this a bit before explaining how we define each of them:

  • The view is considered as an area of the room that we are going to display on the screen.
  • The port is considered as the area of the display where we are going to draw the view.

So, this means that you can have a 640x480 view into your room, and then set the port to 320x240, which will display the view scaled down to that sized port on the screen, and you can also do the same and set the view to a smaller value and the port to larger making the image scale up to fit the port size and be shown on the screen larger than it is. In this way you can maintain a screen (port) size while changing the view and display more or less of the room in the same area of the screen.

The view is always defined as a rectangular area in the room, where you specify the position of the top-left corner, the width and the height of this area. Then you must specify where this area is shown in the window on the screen by defining the view port, where again you specify the position of the top-left corner and the size (note that anything other than 0,0 for the top left corner can give strange results). You can have more than one port and they can overlap, in which case they are drawn in the indicated order one on top of the other. Please realise that the over all screen area is always defined as a rectangular area, so your ports, even when offset, will form a rectangle, with any empty spaces being filled in by the window colour, meaning that in these circumstances you should always have Clear Background with Window colour checked or else you will get odd artefacts drawn in the spaces between ports.

NOTE: On Windows SurfaceRT devices, there is a canvas limit of 2048x2048, which means the drawing canvas cannot go above those dimensions (neither with views, nor by setting the game window directly) otherwise your game graphics will be corrupted or degraded.

Object Following

The "Object Following" option is for when you want the view to "follow" (ie: maintain the view focused on) a certain object. To do this you must click on the menu icon and select an object from the list that pops up (if there are multiple instances of this object in the room, only one of them is followed by the view). The normal behaviour for a view is to only move when the instance being followed gets too close to a "buffer" zone that makes an invisible boundary around the edge of the view. This zone can be defined by you using the Hbor and Vbor values, where Hbor is the horizontal border zone, and Vbor is the vertical border zone. So, setting these values to, for example, 64, will mean that the view will not start to move and follow the character until he reaches 64 pixels from the edge of the view.

Finally you can indicate the speed at which the view moves when the character has reached the buffer zone, and this has a default value of -1. This default value is basically "instantaneous" and means that the moment the follow object is outside the Hbor or Vbor buffer zone, the view will skip to its current position. Now, this is not always what you want and so you can set the vertical and horizontal scrolling speed for the view by setting the values for Hsp and Vsp to something other than -1. Note that a value of 0 will cause the view to not move at all, and any other positive value is how many pixels it will move in any step, so setting the Hsp to 5 will have the view follow the object at 5 pixels per step horizontally.

Back: More About Rooms
Next: Physics

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


More About Sprites

This section deals with the more complex parts of the sprite properties window.

In a previous section (Loading Sprites) we saw how to add a sprite resource into our game through loading it as a pre-made graphic. However, GameMaker: Studio can do much more than that and so this section will take you through the more advanced options available to you from the sprite resource window.

Origin

At the bottom-left, you can indicate the origin of the sprite, which is the point in the sprite that corresponds to its position within the room, ie: when you create an instance at a particular x/y position, the origin of the sprite is placed there. Default it is the top left corner of the sprite but it is often more convenient to use the center, which can be found easily by clicking the Center button, or some other point on the sprite. You set the origin manually by clicking in the sprite image which will move the cross to the point you clicked, or by inputting different values for x and y in the corresponding boxes. Note that you can even set an origin outside the area of sprite by using negative numbers (for left and up) or positive numbers larger than the sprite width and height (for right and down), which can be very useful when dealing with objects that need to draw composite sprites.

Collision Checking

The collision checking options are very important ones for your game, as they will directly influence how your objects interact and how your game runs, with the wrong settings even having a negative impact on the over all performance. Why is that? Well, whenever two instances meet, and both instances have a valid mask, a collision event is generated by checking the overlap of the mask, which can either be precise or not, and adapted to the image index or not. Below is an image to illustrate this: As you can see, when precise collisions are involved then they are resolved on a per pixel basis, and this can be very slow, so if you don't need them, always have precise collisions turned off! The same rule of thumb goes for the separate masks option (as long as "precise" is checked), as this generates a new collision mask for every single frame of an animated sprite (rather than just apply one "best fit" average mask for all sub-images). See below for more information on collision masks.

Texture Settings

This section of the sprite properties window deals with how GameMaker: Studio stores the images that make up your sprite on texture pages for use with devices and browsers. Now, for Mac and Windows platforms this is not normally too important, but when you start to develop for iOS, Android or HTML5 the proper management of your image assets (textures) becomes very important as poorly managed textures can have detrimental effect on your game, causing performance issues.

The Tile:Horizontal and Tile:Vertical check boxes are, by default, not normally checked as most times you do not want to tile sprites. However, in certain circumstances you may wish them to tile, meaning that you should check these options, especially if you are going to be scaling the view or room as scaling can introduce artefacts into the graphics of a game if the texture page is not generated properly.

If your sprite is going to be used as a texture map for a 3D game, then you should check the Used for 3D box and the sprite will be given a texture page all of its own. Note: This will increase the texture memory needs of your game tremendously and so great care must be taken when using this option. Also note that all 3D textures must be a power of 2 (ie> 128x128, 256x256, 512x512 etc...).

Finally, you can chose the texture group that you wish the sprite resource to belong to. Basically, a texture group (previously defined in Global Game Settings: Texture Groups tab) is something that you can set up so that all the image resources that you need for specific rooms or levels of your game can be stored together. So, for example, you can have all your level 1 images in one texture group, all your level 2 images in another etc... and GameMaker: Studio will try to place all those grouped resources on the same texture page to reduce texture page swapping while your game is running on the chosen target platform. Note: This may not always be necessary and performance increase from this method will depend on whether the target device is CPU bound or GPU bound (see Advanced Use: Debugging).

For more detailed information on texture pages and how they are generated, please see More About Backgrounds: Texture Pages.

Sprite Editing

GameMaker: Studio has a complete suite of tools for editing your sprites, and that includes the order in which their sub-images are displayed, what mask properties they should have and even a graphic editor so you can create your own sprites from scratch! These things are all covered in the sections below:

  1. Editing Sprites
  2. Editing Subimages
  3. Editing Collision Masks

Importing Vector Images

GameMaker: Studio permits you to import graphic assets that have been made in the SWF format. You can find out further details of this feature on the following page:

  1. Importing Vector Images

Importing Skeletal Animations

Skeletal animations are sprites that have been made with a specialist program (like Spine) which permits bone animation and skinning. Gamemaker: Studio permits you to import this type of sprite and you can find all the details in the following section:

  1. Importing Skeletal Animations

Back: Advanced Use Index
Next: More About Backgrounds

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Advanced Tools

This section covers the advanced functionality of the Image Editor.

Apart from the tools listed on the page covering the Image Editor, there are also a number of advanced tools available to you to make editing sprites and backgrounds easier. These tools are listed below.

Scratch Page

The Scratch Page addition enables you to store parts of images that have been cut out, or draw your own temporary images and manipulate them, away from the main sprite frame being edited. Think of it as a sort of "scratch pad", where you can test or change things without fear of editing the actual sprite itself.

You can switch between the current animation frame and the scratch page by pressing "J" on your keyboard and the scratch page is treated exactly the same as any other image frame. You can cut and paste images, use the built in effects and even save the results out as a PNG file. However this scratch page image is not stored with the sprite itself, and when you close the editor its contents will be removed.

Custom Colour Pallets

GameMaker: Studio permits you to define custom colours from the colour checker box for the left or right mouse buttons for drawing. However this approach is not very flexible and you need to recreate the palette of custom colours each time you open the program when using that method of colour mixing. However there is another way to create your own custom palettes easily and save and load them as you require. In the image editor you can see on the right of the window the selection of colours available, and normally these are fixed hues. But, if you middle-click on any of the default colours, you will open up the colour mixer window (as happens when you click on the left or right draw colours), only now you can create your own colour and - without having to add it to the custom colours of this window - and click "Okay" to have it saved as part of the default palette you are working with in the main IDE.

Once you have created your custom palette, you can then save it out from the File dialogue. There you will see the option to Save Colour Palette which will save the palette as a *.PAL file. You can then re-load it for use at any time later from the same menu by using the Load Colour Palette option. Note that the *.PAL file created is non-standard so trying to load in palette files made with software other than GameMaker: Studio will not work.

RMB Erase

In the Image Editor, you can set the Eraser Tool to work on the right mouse button instead of implicitly selecting it. Normal behaviour is that you have the pencil tool and the eraser tool and you switch between them from the buttons on the interface, however if you right-click on the eraser tool button, it will set the right colour of the mouse to be the eraser, with all the same properties that have been assigned to that tool. This means that you can draw with the left mouse and erase with the right. When you have selected the right mouse erase option, you will see that the right colour is now shown as a "checker-board" to show that you are using it as an eraser instead of a pencil.

Back: Editing Subimages
Next: Drawing Tools

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Drawing Tools

The drawing tools are those used in the image editor to manipulate and create sprites or backgrounds.

Below you can find a list of all the available drawing tools for use in the Image Editor.

Pencil

With this tool you can paint on the image, using either the left or the right mouse button (the colours can be set independently) and the size of the area being painted can be set by selecting the one of the sizes from the section beneath the draw tools. If you hold <Shift> when starting to paint you only paint horizontal or vertical lines and if you hold the <Ctrl> key, the cursor temporarily turns into the colour dropper allowing you to select another colour from the image and then continue painting.

Airbrush

With this tool you can "airbrush" paint onto the image. Airbrushing works like the pencil except that the brush is partially transparent at the sides and has a certain texture to it. You can use the left or right mouse button to paint in the different colours you have selected and you can set the size of the brush using the buttons at the bottom. There is also a "hardness" setting for this brush which lets you adjust the transparency of the edges of the lines you paint. As with the pencil tool, if you hold <Shift> when starting to paint you only paint horizontal or vertical lines and if you hold the <Ctrl> key, the cursor temporarily turns into the colour dropper allowing you to select another colour from the image and then continue painting.

Eraser

With this tool you can erase parts the image. It works a lot like the airbrush but erasing what is below the mouse rather than drawing. How much you erase depends on the opacity setting, where a value of 255 will erase completely down to 0 which will erase nothing, with all values in between making the image a bit more transparent. You can also set the hardness of the eraser so that it has softer or harder edges and if you hold <Shift> when you start to spray, you only paint horizontal or vertical lines. Note that you can use the right mouse button on the eraser and it will change the right colour to use the eraser settings, permitting LMB paint / RMB erase, as used in many popular paint programs.

colour Picker

With this tool you can use the left or right mouse button to select the colour directly beneath as the draw colour for that button. Note that the opacity value is also set.

Draw A Line

Use this tool to draw straight lines, with the width of the line set by you in the options below, where you can also choose to have it draw an arrow rather than just a line. By checking Anti-alias the line is drawn with partially transparent pixels on the side to make it appear smoother and if you hold <Shift> when drawing then you can snap to draw horizontal, vertical, or 45° diagonal lines only.

Draw A Polygon

With this tool you can draw a closed polygon. You start by clicking on the position of the first vertex, then you can either drag to the position of the next vertex or just click there, and then continue to add more points until you have the shape you wish to create. You can end the polygon with the <Esc> key or by selecting another tool from the menu. As with the other tools, you can hold <Shift> to draw horizontal, vertical, or 45° diagonal lines and you can set the width of the line and whether the polygon should be filled or not. By checking Anti-alias the polygon is drawn with partially transparent pixels on the side to make it appear smoother.

Draw A Rectangle

Use this tool to draw a rectangle, or, if you hold <Shift>, a square. You can set the width of the outside line and whether the rectangle should be filled or not from the options at the bottom, and by checking Anti-alias the rectangle is drawn with partially transparent pixels on the side to make it appear smoother.

Draw An Ellipse

Use this tool to draw an ellipse, or, if you hold <Shift>, a circle. You can set the width of the outside line and whether the ellipse should be filled or not from the options at the bottom, and by checking Anti-alias the ellipse is drawn with partially transparent pixels on the side to make it appear smoother.

Select A Region

With this tool you can select a rectangular region for copying, cutting, or moving. The selection is made by clicking a position and dragging the mouse, which will create a rectangular area bounded by a dotted line. This area can then be clicked on again to "pick it up" and move it around the image with the mouse. If you use the right mouse button, then you will get the same effect, only you will have a copy of the selected region. You can extend the current selection by holding the <Shift> key, you can remove parts by holding the <Ctrl> key, you can delete the contents of the selection with the <Del> key, and you can clear the selection using the <Esc> key.

Select With Magic Wand

In this case you make the selection by clicking on a pixel, and all touching pixels with the same colour and within the set tolerance will be selected. You can indicate the tolerance with which to select pixels and whether only the colour or also the transparency value should match from the options beneath the toolbox. As above, you can extend the current selection by holding the <Shift> key, and you can remove parts by holding the <Ctrl> key. Once you have the selection you can manipulate it as explained above.

Select With Brush

With this tool you make the selection by "brushing" with the mouse on the image. You can set the size of the brush using the controls beneath the toolbox, and the selection can be treated as explained for the above tools.

Add Text

Use this to add text to the image. You start by clicking the image and a pop-up window appears in which you can enter the text (you can use the # symbol to insert a newline), and once you press OK the text is put in the image, with a selection box around it. You can now move the text by clicking and dragging it with the mouse. If you wish to change the text, simply click with the right mouse button in the box. You can also change the font and alignment (left justified, right justified or centered) from the options that are beneath the toolbox.

Flood Fill

Click on a point in the image, with either the left or the right mouse button, and all touching pixels with the same colour or within the tolerance setting will be turned into the chosen colour. You can set the tolerance with which the colour should match from the settings beneath the toolbox, and you can also set whether to only match on the colour value or also take the transparency value into account too. Note that when the colour Mode is set to Blend the fill colour is blended with the existing one, and to replace it, set the colour Mode to Replace.

Change colour

When you click with either the left or right mouse button using this tool, all pixels in the image with the same colour or within the set tolerance will be turned into the new colour. You can set the tolerance with which the colour should match from the settings beneath the toolbox, and you can also set whether to only match on the colour value or also take the transparency value into account too. Note that when the colour Mode is set to Blend the fill colour is blended with the existing one, and to replace it, set the colour Mode to Replace.

Back: More About Sprites
Next: Advanced Drawing Tools

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Editing Collision Masks

This section deals with the collision mask editor.

Once you open a sprite resource, you can edit its collision mask, which is the area that GameMaker: Studio uses to calculate when two instances are in collision or not and trigger a collision event. To get the collision mask editor, open a sprite resource and press the button Modify Mask. The following window will show:

The Mask Properties window is split into various sections (explain in more depth below) and on the right you can see a graphical representation of the sprite with the current mask overlaid in dark grey. All changes that you make to the mask will be reflected here, making it far easier to visualise how they will affect how your game plays.

Image

This part shows you some basic information about the sprite, including the width and height and the current sub-image. There is a check-box at the bottom where you can switch on and off the visual representation of the mask in the view on the right, and the zoom controls beneath this can also be used to change the scale of the view to help fine-tune the size of the mask better.

General

This section has two options which you can change, with the first being the separate collision masks toggle which is the same as in the actual sprite resource itself. All this does is tell GameMaker: Studio to create a separate collision mask for each sub-image of the current sprite (Note that if you set the bounding box manually, a single bounding box will be used for all sub-images, regardless of this setting) but only if you have selected "precise" from the properties on the right. You can also indicate the tolerance with respect to the transparency of the sprites pixels: with a higher tolerance pixels that are partially transparent are left outside the mask, while with a lower tolerance the mask will take into account those pixels. This influences both the bounding box (when not set to manual) and the mask for precise collision checking.

Bounding Box

The bounding box is the name given to the rectangular area that the sprite mask fits in. Only pixels inside this bounding box are used for the mask and will be involved in collision checking, and by default this is automatically computed, taking the alpha tolerance into account. If you have precise checked then this will be separate for each sub-image too. You can also set it to the full image (the actual width and height of the sprite, irrespective of the transparencies that the sprite may have) or you can set it to manual, where you can specify the bounding box yourself. When setting it yourself, you can input the values in the boxes for left, right top and bottom, or you can click in the sprite view and drag to "draw" it over the sprite. Note that when "drawing" the bounding box, the mask is automatically generated to fit within the end values.

Shape

Here you can indicate the shape of the mask you wish GameMaker: Studio to base its collisions off of. The default is precise, per-pixel collision checking, but you can select here also to use a rectangular, elliptical, or diamond shaped mask too, with all of them being faster for GameMaker: Studio to process than precise collisions, but no one of the three being faster than the other. Here you can see how the different shapes are applied to a sprite:

Choosing A Collision Mask

It is important to carefully decide on the collision mask you use for your sprites. Although precise collision checking might seem the most logical option, in many cases game play is improved by using rectangles or ellipses, or simple masks that are a bit smaller than the actual sprites themselves. Only on a very few occasions should you need precise masks, and, in general, it is better to have as few instances with precise collisions as possible.

Please note too that if you want even further control over the mask, then you can specify an actual sprite to use as mask within the object properties themselves. In this way you can make the collision mask completely independent of the sprite image assigned to that object, which can be very useful, for example, when making isometric games and you want to have a only a small collision mask at the feet of the player.

Back: More About Sprites
Next: Importing Vector Images

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Editing Sprites

This section explains the functions associated with the GameMaker: Studio sprite editor.

In previous sections of the manual we have seen how to load simple sprites from files, but it is also possible to create and modify them within GameMaker: Studio. To do this, open the sprite property window by double clicking on one of your sprites (or by creating a new one) and pressing the button labeled Edit Sprite, which will open up the following window:
The main area of the sprite editor is taken up by the various sub-images that make up the sprite. These sub-images all have the same over-all size, with any smaller image having generally transparent pixels around to make it "fit" the maximal size, although this will depend on whether you are importing images from a file or not (see the "File Menu" section below) and the choices you make when doing so. The other sections are explained in more detail below.

Preview

To get a preview of the sprite you must tick the check-box labelled "Show Preview". This will cause the area beneath to show an animated preview of the current sprite as well as a number of options that affect how this preview looks, all with the aim of getting a good idea of how a finished sprite will look when placed in the game world. You can change the speed at which the animation is displayed by changing the corresponding value in the box, and you can also choose a colour for the background of the sprite (this only affects the preview, not the actual game). Should you wish, you can also specify a background image from your resource tree by clicking on the "Background" menu and so get a more realistic idea of how the sprite will look in the game, with the option of stretching the background to fit the size of the sprite available beneath that too. Note that these options will only be visible if you have transparent areas in your sprite!

Infobar

This bar at the bottom gives you some very basic information about the current sprite you are working with:

  • Frames: The number of sub-images that the sprite has.
  • Size: The width and height of the sprite.
  • Memory: This is the approximate texture memory that the finished sprite will take up on any device, and is calculated as: image_number * width * height * 4.

Toolbar

The toolbar contains a number buttons that allow you to change and manipulate the position and the actual sub-images that make up your sprite:

Confirm

This will close the sprite editor and save any changes you have made. Be aware that there are no confirmation messages asking if you want to save.

New Sprite

Click on this to create a new sprite. You will be prompted to input a base width and height. Note: This will delete all previous sprite information!

Create A Sprite From A File

This will open the standard window for loading a sprite (see Defining Sprites) . This will replace any existing sprite images with the loaded one.

Add A Sprite From A File

This will open the standard window for loading a sprite (see Defining Sprites) , which is then added to the current sprite. If the dimensions of the new sprite do not match up with the current sprite you will be shown these options:

Save Strip

This will save your current sprite as a *.png strip, ready to be used in another game or some other animation program. Below you can see an example of an animated sprite along with the strip that GameMaker: Studio would produce when saved using this option:

Insert Empty Frame

This command simply inserts an empty frame into the list of sub-images. This frame will always be inserted before the currently selected sub-image.

Add Empty Frame

This command adds an empty frame onto the end of the current sub-images.

Undo

This will undo the last action, and you can repeatedly undo consecutive actions with this button, but note that the number of undos that can be performed is limited to 16.

Redo

If you have used the undo function, you can use this to go back to the state that you undid. This is limited to the number of undos that you have done previously.

Cut

You can use this to "cut" a sub image out of the list of sub-images. This cut image is stored to the clipboard and can then be pasted into another part of the same sprite, another sprite resource or even into some other program, independent of GameMaker: Studio. Please note that the transparencies may not be the same when pasted into another program.

Copy

This button will copy the currently selected sub-image into the clipboard for use in another place, either the same sprite, another sprite or even an alternate program.

Paste

You can use this button to paste whatever image you have previously stored in the clipboard (with cut, or copy) into the current sprite as a new sub-image. If the pasted image is larger or smaller than the current sprite, you will be shown the "Inserting Image" window (see "Add A Sprite From A File", above).

Shift Image

These buttons will move the currently selected sub-image left or right in the image order for animation.

Edit Sub-image

This button will open the GameMaker: Studio Image Editor where you can edit on a per-pixel basis the selected sub-image. More on this in the section Editing Sub-images.

Pre-Multiply Alpha

This button will pre-multiply the alpha of all sub-images of the chosen sprite. This is normally only necessary when dealing with surfaces and drawing sprites to them, or for some specific special effects and for normal sprite use you should not see any noticeable difference between the normal sprite and the pre-multiplied one. Note that this cannot be undone..

Menus

For information relating to the different menu options, please refer to the following pages:

File Menu
Edit Menu
Transform Menu
Images Menu
Animation Menu

Back: More About Sprites
Next: Editing Subimages

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Editing Subimages

GameMaker: Studio has a built-in image editor that can be used to edit individual sub-images of sprites and background images.

To aid you in your task of creating a good game, GameMaker: Studio provides you with its own editor for editing backgrounds and sprites. Both resources share the same editor so although this page refers to sprites, the exact same commands are available for backgrounds too. To call the editor for a sub-image of a sprite, select the sub-image in the sprite editor and choose Edit Image from the Image menu (or double click on it, or press the "Edit Image" button on the toolbar), and to edit a background, open the background properties window and press the button labelled Edit Background.

The built-in editor is primarily meant for making changes to images, not for creating sprites and backgrounds from scratch, as, although the built-in image editor is pretty powerful, it does not have all the features of full-blown paint and drawing package. It is great for roughing out some place-holder images but for brand new sprites and graphics you probably want to use a separate paint program, save the images as PNG files, and then load them into GameMaker: Studio for further work. Note that you can also set an external image editor in the Preferences and so bypass this section all together.

When you start the image editor it will typically looks as follows:

As you can see, the image to be edited takes up the space in the middle of the screen with the editing tools and menus arrayed around it. At the bottom of the screen is the Infobar where you can get basic information about the state of the editor, with the current mouse x/y position and the percentage of zoom being applied shown at all times. It will also show the x/y coordinates of any selection along with the maximal width and height of the selection.

Menus

The drop down menus at the top of the screen are almost exactly the same as those found in the Sprite Editor, particularly the Edit Menu, the Transform Menu, and the Image Menu. The File Menu is similar too, but has a few less options and they work in different ways:

  • New: Creates a new image. This basically wipes the current sub-image ready for you to start from scratch, but it does not change the size.

  • Save as PNG file: Saves the current image as a one frame *.png file.

  • Previous Image, Next image: Switches sub-images either one frame to the left, or one frame to the right. In this way you can edit multiple sub-images, one after another. Note: This will effectively save any changes to the current sub-image, so use with care as you get no prompt.

  • Close saving changes: As it says, this will close the editor and save any changes to the current image.

You also have a View Menu for controlling how the image being created is shown in the editor.

Toolbar

Like the drop down menus, the toolbar features a number of commands that are covered in the section dealing with the Sprite Editor, however there are a couple of new ones at the end which we will cover here:

Zoom In

Zoom the image in the editor to see better the individual pixels. The mouse wheel can also be used for zoom too.

Zoom Reset

This resets the zoom to a 1x1 ratio.

Zoom In

Zoom the image in the editor out to see better the overall image. The mouse wheel can also be used for zoom too.

Toggle Pixel Grid

You can click this to toggle the pixel grid on or off (the grid is only visible when you zoom in).

Zoom In

This will toggle on and off the preview panel (situated below the colour tools) so you can see the image at actual size even when zoomed in or out.

Drawing Tools

The drawing tools permit you to select different brush sizes, select regions, draw forms, etc... You can use them by left clicking on one and then left clicking in the image being edited. The full list of available draw tools can be found from the following page:

  1. Drawing Tools

Colour And Blending Tools

The right hand side of the window is mostly taken up with the colour tools. These are simple to use, yet give you great control over the colours that you can draw with. At the top you have the section labelled colours with two boxes labelled "Left" and "Right" which set the colour for the corresponding mouse buttons (these boxes also set the colours for certain drawing tools, which we cover in the Drawing Tools section below. Beneath that you have a basic colour picker which covers a very limited range of the most used colours, while beneath that you can find a more advanced colour picker for fine-tuning your choice. The Opacity setting controls the transparency of what is being drawn, with 255 being fully opaque and 0 being fully transparent, while the last control, colour Mode, tells GameMaker: Studio to draw and blend the alpha channel, or to overwrite it using the current alpha.

Note that you can also create custom colour pallets, see the section on Advanced Drawing Tools.

Image Preview

The Image Preview shows you an image of the sprite as it would appear in the game. If you double click on it, you can switch between x1, x2 and x3 scaling, giving you a much clearer picture of the sprite and how it looks while editing it in the main window. Note that you may need to expand the sprite editor window to see this. The preview window can be enabled or disabled from the View Menu.

Onion-Skinning

At the bottom right of the window you can see the controls for the Onion-Skinning function of the image editor. What onion-skinning means is that in a single frame of any sprite animation, you can choose to see any of the preceding or succeeding four frames as a semi-transparent layer under the image frame you are currently working on.

You can choose the alpha value that each frame will be drawn with, from 0 to 255, as well as how many of the frames to show. By setting the Forward value you can see those frames that come after the frame currently being edited and by setting the Backwards value, you can see those that come before. You can set these to a value from 0 (none) to 4 (all four frames will be drawn), permitting you a far greater control over animations and positioning than was previously possible.

Note that we suggest using the onion-skinning over a colour-fill background rather than a transparent one (you can set this option from the View menu of the image editor and selecting Set Transparency Background), as it makes the transparencies of the various skins easier to see.

Advanced Drawing Tools

Apart from those tools listed above, there are also a number of advanced options available to you when working with the Image Editor. You can find more about these options from the following page:

  1. Advanced Tools

Back: Editing Sprites
Next: Editing Collision Masks

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Importing Skeletal Animations

Here you can find information on importing skeletal animations into GameMaker: Studio.

A sprite made using skeletal animation, is one in which a base "skeleton" has been created and animated using key-frames to move the component parts of the skeleton over time. This skeleton is then skinned from a texture atlas and the resulting animation exported in one of many file types. Gamemaker:Studio permits you to import this type of sprite as long as it has been exported as a *.json format file and has the correctly associated texture atlas file (*.atlas) and image file (as a *.png) in the same directory.

IMPORTANT: GameMaker: Studio only supports a single texture atlas per sprite.
NOTE: This feature currently only supports files created using the program Spine.

How To Import A Skeletal Animation

Currently GameMaker: Studio can only import vector images from JSON format files made by the program Spine, however the way to import them into the program is almost identical to that for adding a normal bitmap image. To add a skeletal animation, you need to create a new sprite, which will bring up the standard Load Sprite dialogue, but make sure that you have selected *.json from the file filter at the bottom.

Hitting the "load" button will add the skeletal animation to the resource tree as a sprite, with a progress bar being shown as the file is processed. Note that, depending on the complexity of the file, this may take a moment or two. When processing has finished you'll be returned to the sprite properties dialogue, which will now look like this:

Once you have imported the animation, you can set the collision properties, but note that you are limited here to simply using precise collisions or bounding box collisions, and that the collision data for a skeletal animation is explicitly taken from the data provided. GameMaker: Studio does not generate any collision mask if the data is missing from imported file, meaning you simply won't get working collisions if the masks are not set correctly in the program used to create the image being imported.

NOTE: Due to the complexity of skeletal animations, the preview image shown in the sprite editor is not intended to accurately represent your animation, but rather give you a simple image that represents the animation for visualising in the room editor.

Unlike bitmap sprites, the imported skeletal animation sprite cannot be modified in the editor in any way, but there are a number of functions available within the GameMaker Language (GML) which can be used to change skins, set properties, and control other aspects of the animation.

Important

There are a number of things that you should be aware of when importing skeleton animation sprites, with the most important being that some of the sprite drawing and sprite management functions are not supported for technical reasons, particularly those draw functions that draw only part of a sprite, or that "skew" the position in some way (see the individual draw_sprite_*() functions for exact details of which). However the basic sprite drawing functions are fully supported as are the built in sprite variables. Apart from these functions and variables, you can also set and change animation properties using special skeleton_* functions, which are listed and explained in the reference section on Skeletal Animations.

Back: More About Sprites
Next: Editing Sprites

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Importing Vector Images

Here you can find information on importing vector based images and animations into GameMaker: Studio.

GameMaker: Studio has limited support for vector sprites. Generally all sprites in GameMaker use bitmaps which, while flexible in terms of content, place limitations on both the size and number of frames possible in a sprite before memory usage can become prohibitive. Vector sprites work around these limitations by storing and drawing their contents differently - instead of a grid of pixels, which can become blocky or fuzzy when scaled, they are drawn as triangles which can be scaled up without losing definition, as illustrated in the image below:

To help you visualise how this is done, the image below is of the same vector Fireman sprite only now we can see the polygons that are used to make the image within GameMaker: Studio:

However, nothing is ever for free when it comes to programming games, and the tradeoff here with vector sprites is that they are more expensive to draw than bitmap sprites and this speed difference increases as the complexity of the animation being imported increases. Also, their memory usage is affected by their visual complexity, unlike bitmap sprites. Baring that in mind, they do make it possible to add large animated graphics in ways that would be impossible using traditional bitmapped sprites.

On the flipside of the performance equation, because vector sprites only draw the pixels absolutely required (unlike bitmap sprites which also "draw" the empty space around the image) they can be cheaper from a GPU perspective. Also, in general vector sprites are much smaller than their bitmap equivalents - for the fireman example above the sizes of the various sprite types are as follows:

Bitmap at 70x68 = 4x70x68 bytes x 12 frames = 223k
Vector = 54k

If you quadruple the resolution of the sprite:

Bitmap at 280x272 = 4x280x272 bytes x 12 frames = 3570k
Vector = 54k

So as you can see a lot of memory can potentially be saved by using vector sprites, and we still have a lot of potential for future space savings.

How To Import Vector Images

Currently GameMaker: Studio can only import vector images from SWF format files, and the way of importing them into the program is almost identical to that for adding a normal bitmap image. To add a vector sprite, create a new sprite, which will bring up the standard Load Sprite dialogue, but make sure that you have selected *.swf from the file filter at the bottom.

Hitting the "load" button will add the vector image or animation to the resource tree, with a progress bar being shown as the file is processed. Note that, depending on the complexity of the file, this can take a while (up to a minute for more complex animations). When processing has finished you'll be returned to the sprite properties dialogue, which will now look like this:

As you can see it looks like the normal sprite dialogue, with the first frame of the vector file shown in the image preview window on the right. There are a couple of changes from a normal sprite dialogue though. Firstly, the Edit Sprite button has gone since there aren't any bitmaps to edit in this sort of sprite, and secondly, a new Show Sprite button has been added. This button will open the vector file in whatever application is associated with it. This would normally default to your web browser, but if you do not have a program associated with the file, then nothing will happen and as the button is disabled (you can resolve this by opening Windows Explorer and right-clicking on a vector file, then using "open with" to choose the program to associate with these files). You can also associate a viewer for these sprites in the Editor Preferences within GameMaker: Studio and the Show Sprite button will open that instead of the default viewer.

NOTE: How the image looks in your chosen preview editor will not be the same as how it looks in your game, nor how it looks in the preview window of the sprite editor. The vector image will be imported at the size it was created at, which is not necessarily the size that the preview is shown at (browsers will normally scale the image to fit, for example).

You can also set the quality of the vector sprite when drawn. This will simply reduce or increase the number of triangles used to generate the sprite, with the default quality value of 50 being sufficient normally for most games, however you should experiment with this value if you are using extreme scaling, or are having performance issues. From this point the other parts of the editor should function the same as they do for bitmap sprites.

Important Things To Note

There are a number of things that you should be aware of when importing vector sprites, with the most important being that some of the sprite drawing and sprite management functions are not supported for technical reasons, particularly those draw functions that draw only part of a sprite, or that "skew" the position in some way (see the individual draw_sprite_*() functions for exact details of which). However the basic sprite drawing functions are fully supported as are the built in sprite variables. You can also set different anti-aliasing (AA) values for the SWF sprites being drawn using the functions found here: Drawing Sprites and Backgrounds.

You should also be aware of the following:

  • When importing a *.SWF file, Actionscript is not supported, so if your SWF relies on it to work correctly then it probably won't turn out right. Similarly, any embedded movie clips that have their own timeline will only have their first frame shown throughout the animation - all animation must be on the main timeline.

  • If your vector file has particularly fine detail you may occasionally find that holes or strange triangles will appear in the resulting sprites. This is because at small scales geometry can sometimes collapse together to create shapes that just don't triangulate well. In this case you have two options - you can scale up the contents of the vector file which will give the importer more room to play with, or you can try to reduce the level of detail in the object that is breaking.

  • GameMaker: Studio uses the stage size of the SWF as the bounds of the resulting sprite. However, if you have anything on the stage outside these bounds it is still drawn. This means that you should either try to avoid putting anything outside your stage bounds if you don't want it to be shown, or use a mask layer to limit drawing to this area.

  • The stage size also affects the size of any collision masks that are generated, therefore if you have a large stage size and a lot of frames in your animation you can potentially eat up a lot of memory. So, only use precise collision masks if you really need it.

  • As a SWF file is created from multiple layers, some of which potentially overlap, alpha doesn't work quite the way it does with bitmap sprites - overlapping areas will not look as transparent as other parts of the sprite, as the pixels there are being drawn over multiple times.

  • Bitmap fills are supported though if you use tiled bitmap fills as part of your SWF file you need to make sure the bitmap is a power-of-two in size, otherwise it won't tile properly. Text rendering is also supported, but you need to embed the font in your SWF file for it to show up in the resulting sprite. Also, currently only left-aligned single line text is supported.

Back: More About Sprites
Next: Editing Sprites

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Sprite Editor Animation Menu

This section explains the actions available from the animations menu.

Under the animation menu you can create new animated sprites out of the current sub-images. There are many options and you should experiment a bit with them to create the effects you want, as most of them work well when used together, rather than as individual effects. Also, don't forget that you can always save an animated sprite and later add it to the current one to create a single, larger animation. The following options exist for you to edit animations:

  • Set Length: Here you can change the length of your animation. To achieve this, GameMaker: Studio duplicates the sub-images from the beginning to end, repeating them again and again until the required number of sub-images has been reached.

  • Stretch: As above, this command will also change the length of the animation, but this time sub-images are duplicated or removed to get the right number. So if you increase the number of frames the animation goes slower as more sub-images are generated between the current ones, and if you decrease the number it goes faster.

  • Reverse: This reverses all the sub-images so the animation of the sprite plays backwards.

  • Add Reverse: This option will duplicate all the sub-images, then add them on at the end of the animation in reverse, doubling the number of sub-images. You may want to remove the double first and middle frame that occur with this to maintain a smooth animation.

  • Translation Sequence: With this command you can create an animation in which the image slightly translates (moves) in each frame. You must provide the number of frames and the total amount to move horizontally and vertically, and GameMaker: Studio will do the rest.

  • Rotation Sequence: This creates an animation in which the image rotates. You can either choose clockwise or counterclockwise rotation, and you have to specify the number of frames and the total angle in degrees (360 is a complete turn) that should be completed in within those frames. You might need to resize the canvas first to make sure the total image remains visible during the rotation.

  • colourize: Creates an animation that turns the image into a particular colour, as shown below:

  • Fade to colour: Creates an animation that fades the image to a particular colour, as seen below:

  • Disappear: Makes the image disappear by making it more transparent in each step. An example is provided below:

  • Shrink: Shrinks the image to nothing in the direction indicated (center, left, right, top or bottom). Below is a shrink towards the center:

  • Grow: Grows the image from nothing in the direction indicated (center, left, right, top or bottom). Below is a grow towards the center:

  • Flatten: "Flattens" the image to nothing in a given direction (left, right, up or down) ie: gives the sub-images a perspective effect that looks like it's being laid flat, as shown below:

  • Raise: Similar to the above command, this "raises" the sub-images from a given direction (left, right, up or down):

  • Overlay: This command will ask you to select a file for overlaying with the currently selected sprite. The file can be a single image (in which case it is repeated over every frame) or a strip (in which case it must have a file name that ends in _stripXX or GameMaker: Studio will treat it as a single image). When the image from the file has a different size it is stretched to the maximal size of the sprite being overlaid.

  • Morph: Morphs the animation to an animation or image from a file. Note that morphing works best if the two animations cover the same area of the image, otherwise, halfway certain pixels disappear and others suddenly appear. This is due to it not really being a "true" morph, but rather a fade in/out of alpha (transparencies).

Back: Editing Sprites

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Sprite Editor Edit Menu

This section explains the edit menu functions associated with the GameMaker: Studio sprite editor.

The edit menu contains a number of commands related to the edition of sub-images within the sprite (most of these commands are the same as those found on the toolbar as buttons):

  • Undo: This will undo the last action, and you can repeatedly undo consecutive actions with this button, but note that the number of undos that can be performed is limited to 16.

  • Redo: If you have used the undo function, you can use this to go back to the state that you undid. This is limited to the number of undos that you have done previously.

  • Cut: You can use this to "cut" a sub image out of the list of sub-images. This cut image is stored to the clipboard and can then be pasted into another part of the same sprite, another sprite resource or even into some other program, independent of GameMaker: Studio. Please note that the transparencies may not be the same when pasted into another program.

  • Copy: This button will copy the currently selected sub-image into the clipboard for use in another place, either the same sprite, another sprite or even an alternate program.

  • Paste: You can use this button to paste whatever image you have previously stored in the clipboard (with cut, or copy) into the current sprite as a new sub-image. If the pasted image is larger or smaller than the current sprite, you will be shown the "Inserting Image" window (see "Add A Sprite From A File", above). If the image has been copied from a source other than GameMaker: Studio, then transparencies may not be the same.

  • Erase: As you might imagine, this command erases one or all images to a particular colour. The following window will open when you select this: What this does is it removes all the current pixel information, but not the sub-image itself, and replaces it with a single colour of your choice. You can also adjust the transparency and select whether you want to erase all the sub-images, or just the currently selected one.

  • Delete: Delete the currently selected sub-image, removing it from the sprite completely.

  • Move Left: Move the currently selected sub-image one position to the left in the sequence.

  • Move Right: Move the currently selected sub-image one position to the right in the sequence.

  • Add Empty: Add a new empty sub-image at the end of the sequence.

  • Insert Empty: Insert a new empty sub-image before the currently selected subimage.

  • Edit: Edit the currently selected sub-image using the built-in image editor. More on this in the section Editing Sub-images.

  • Set Transparency Background: Here you can indicate how the transparent area of the sprites should be shown in the sprite editor. You can either use a customizable block pattern, or a colour that you can change by clicking on the colour box, as shown in the following image (note that this does not affect the sprite itself, only how you view it in the editor):

Back: Editing Sprites
Next: The Sprite Editor Transform Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Sprite Editor File Menu

This section explains the file menu functions associated with the GameMaker: Studio sprite editor.

The file menu contains a number of commands related to loading and saving sprites, which are all explained below:

  • New: This will create a new, empty sprite with the dimensions you specify in the following window: The width and height that you input here will be the base size for all sub-images of your sprite.

  • Create from File: You can use this option to select a file and use that to create a new sprite. Many file types can be used, including bmp, png, jpeg and gif, and they will all generally create a sprite consisting of a single sub-image, except for animated GIF files that are split into the sub-images. If you use a strip and the name of the file ends with _stripXX then GameMaker: Studio will also split this sprite up into its component sub-images. For more details on the various load options see Defining Sprites

  • Add from File: Adds an image (or multiple images) from the selected file to the current sprite. If the images do not have the same size you can choose where to place them or to stretch them from the window that pops up. You can also select multiple images from the file manager and they will all be loaded into the sprite as separate sub-images.

  • Save as PNG File: This will save the sprite as a strip in a *.png format file. A name is automatically generated from the name of the sprite in the resource tree, and when the sprite has multiple sub-images the text _stripXX (with XXbeing the number of sub-images) is automatically appended. Of course you can name the image file whatever you wish, but if you want GameMaker: Studio to be able to load it at a later date and maintain the sub-images, then you should maintain the _stripXX format at the end.

  • Create from Strip: This option permits you to load a non-standard (ie: the name does not have _stripXX at the end) image file into GameMaker: Studio as a strip of sub-images. The following window will open where you can set how this is to be achieved: GameMaker: Studio has a number of options to help you adjust the spacing of the sub-images within the sprite strip to get the optimum results. These options are:
    Number of images: This is the total number of sub-images that the sprite contains.
    Images per row: Here we specify the number of sub-images that are in each row of the image file.
    Image width and image height: The width and height (in pixels) of each sub-image.
    Horizontal and vertical cell offset: A "cell" here is one space the size of the above mentioned width and height, so setting this will offset the starting point of the sub-images.
    Horizontal and vertical pixel offset: As above, but this time the starting coordinates are defined in pixels rather than cells.
    Horizontal and vertical separation: Sometimes a sprite strip has spaces ("buffer" zones) around each of the individual sub-images. these zones can be eliminated by this setting.

  • Add from Strip: Use this to add sub-images to the current sprite from an external file where they are in a strip format. See above for the window that this opens.

  • Close Saving Changes: Closes the form, saving the changes made to the sprite. If you don't want to save the changes, click on the close button of the form.

Back: Editing Sprites
Next: The Sprite Editor Edit Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Sprite Editor Images Menu

This section explains the functions associated with the GameMaker: Studio sprite editor "Image" drop down menu.

The "Images" drop down menu offers a number of handy options to change the colours, transparencies and other details of the sub-images of your sprite. If you use these commands from the actual sub-image editor then the options chosen will only be applied to the currently selected sub-image, however if you use these commands from the sprite editor they can be applied to all sub-images by ticking the appropriate check-box.

  • Cycle Left and Cycle Right: Cycles all images one place to the left or to the right, so that the order of the sprite animation is changed.

  • Greyscale: Converts the image (or images) into greyscale.

  • colourize: Here you can change the colour (hue) of the image(s). There is a slider which you can use as well as an input box to directly input a new value. The normal effect is to colourize the image(s) with the selected hue, but when you mark the "shift hue" check-box, the original colours are shifted over the amount indicated giving some rather interesting effects.

  • colourize Partial: Here you can change the colour (hue) of part of the image(s). You use the top slider (or the input box) to select the new colour you wish, then change the second slider (or input box) to select the colour you wish to change (or click the left image on the colour). The tolerance slider changes the dynamic range to be changed, from a very narrow selection to a very broad selection, meaning that you can single out specific colours or whole ranges to change.

  • Intensity: Here you can change the intensity (luminosity) and saturation (amount of colour) in the selected image(s).

  • Invert: Inverts the colours in the image(s).

  • Make Opaque: Remove all transparency information from the image(s), making them opaque.

  • Erase a colour: You can select a colour to erase with this either by clicking on the colour box or by clicking somewhere in the left image. You then specify the tolerance with a slider to set the "range" of pixels to be included in the action. All pixels with a colour close the selected colour and within the tolerance level will be made transparent.

  • Smooth Edges: This will smooth the edges around the opaque part of the image(s) to make them look nicer. Should you require a stronger effect, this can be achieved using Blur (see below) but only selecting to blur the transparency.

  • Opacity: Here you can change the opacity (transparency) for the whole image (or images). You can either set it relative to the current opacity, meaning that it will be added/subtracted from the existing transparency values, or absolute so that the existing transparencies are overwritten by the new value. Note that fully transparent pixels always stay fully transparent.

  • Set Alpha from File: This is a very interesting function that takes the luminosity values from a file and applies them to the alpha channel (transparency) of the image. These values are calculated based on how light or dark each pixel is, with white being fully opaque, black being fully transparent and everything else somewhere in the middle. The ideal images to use are those that have no colour information and are purely greyscale, and it should be the same size as the target sub-image(s) of the sprite (however, if it is larger or smaller it will be scaled to fit). The image below illustrates how it works:

  • Fade: Here you specify a colour and an amount and the pixels in the image(s) are now faded towards this colour with the given amount.

  • Blur: This option can be used to blur the image(s). There are options to choose the quantity of blur to be used as well as to select whether you wish to blur just the colour information, the transparencies or both. Only blurring the transparency values can be a nice way to smooth the boundary of the image(s).

  • Sharpen: This option can be used to sharpen certain details within an image (or images). This is sort of the reverse of blurring as sharpening enhances the edges of the image, with you choosing how subtle or strong you wish the effect to be and whether to sharpen the transparent edges only, the coloured edges only or both. The special sharpening puts additional emphasis on details and can leading to an interesting effect.

  • Outline: You can use this command to create an outline around the image(s). You are asked for the colour and a thickness of the outline, as well as whether to position it inside the image or not. You can also indicate that you wish to remove the image(s) as well, leaving only the outline itself. Finally, there is an option to smooth the outline, which lightly blurs the edges to give it a more rounded feel.

  • Shadow: This command will create a "drop" shadow below the image(s). The available options permit you to select the colour of the shadow and the position, as well as the alpha (transparency) and whether you wish the edges of the shadow to be hard or soft (blurred or not).

  • Glow: Create a coloured glow around the image, where you can indicate the colour of the glow, the opacity and the thickness. You can also indicate to place the glow inside the image.

  • Buttonize: Turn the image(s) into a button. You specify the colour of the button and the opacity of the effect. You must also indicate the thickness of the button boundary and whether it should be smooth or not, with a smooth button having a much more rounded look to it.

  • Gradient Fill: Adds a gradient fill to the image(s). You can specify the two colours to create the gradient between, the overall opacity and the type of gradient to use. Default the image is replace by the gradient although the transparency is maintained, but by un-checking the "Replace" box the gradient is blended onto the image. By checking the "Change Transparency" box the alpha value of the original image is changed as well.

Back: Editing Sprites
Next: The Sprite Editor Animation Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Sprite Editor Transform Menu

The transform menu contains a number of commands related to changing the general size and shape of the sub-images.

From the transform menu you can perform any of the following general transformations on the sub-images of your sprite:

  • Shift: This option opens a window where you can choose to shift the current sub-image (or all of them) by a certain amount. The image can be made to wrap horizontally or vertically so that it either disappears out the side of the screen or "wraps" so that any pixels that go out one side will be shifted to the opposite side.

  • Mirror/Flip: With this you can mirror the selected image (or all sub-images) horizontally and /or flip them vertically too:

  • Rotate: This gives you the option to rotate the image. There are buttons supplied for the most common amounts (90°, 180° and 270°) as well as a slider and an input box so you can specify any angle from 0-360°. Please note that the sub-image size does not scale to take into consideration areas of the image that may be outside the window when you finish, so you may wish to resize the canvas (see below) before using this option.

  • Scale: Using this command will open the scale window where you can change the scale of the sub-image (or images). Like "rotate", above, any pixels that are scaled outside of the bounds of the sub-image will not resize the sub-image, but rather be "cut off" and the image trimmed to size. To get around this, you can resize the canvas (see below).

  • Skew: This command skews the image(s) horizontally and/or vertically by a given amount, which can be input directly or changed by the sliders. As with many of these functions, the canvas size is not changed to accommodate any part of the image that may be lost outside of the window. To get around this you can use the "Resize Canvas" command (see below).

  • Resize Canvas: With this command you can resize the canvas of the sprite (this will affect all sub-images!). You can specify a new width and height in either pixels or as a percentage of the current size, and you can instruct GameMaker: Studio to maintain the aspect ratio of the canvas (so, changing the height will change the width in proportion and vice-versa) as well as maintain the position of the origin. The box on the right at the bottom labelled "Position" permits you to choose the "anchor" for the resizing (default is the center).

  • Stretch: Here you can stretch the sprite to a new size. This will affect all sub-images and resize the sprite to the match the size you input, stretching it or shrinking it to match. As with "Resize Canvas", You can specify a new width and height in either pixels or as a percentage of the current size, and you can instruct GameMaker: Studio to maintain the aspect ratio of the canvas (so, changing the height will change the width in proportion and vice-versa) as well as maintain the position of the origin. You also have the option to set the quality of the scaling, which basically sets the interpolation level.

  • Crop: This is an automatic tool that aims to make the sub-images as small as possible. This is very useful because the larger the images, the more video memory GameMaker: Studio will use, which for mobile devices is not what you want. There is only one option you can set in the pop up window for this and that is the "border", which sets a transparent border around the images. If you provide a negative value to this , the outside of the images will be cut off by the amount that you specify.

Back: Editing Sprites
Next: The Sprite Editor Images Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Sprite Editor View Menu

This section explains the view menu functions associated with the GameMaker: Studio sprite editor.

The view menu contains a number of commands related to the visual aspect of the image editor:

  • Zoom Out: Zoom the main image view out to see more of the sprite.

  • No Zoom: Set the zoom level for the editor to have a 1:1 pixel ratio for the sprites on the screen.

  • Zoom in: Zoom the main image view in to see less of the sprite and focus on smaller details.

  • Toggle Grid: With this you can toggle a transparent grid of lines that show the individual pixels of your image (note this is different to the background grey/white squares that show transparency).

  • Grid Settings: Here you can specify the size of the pixel grid that you want to use, the base overlay colour for the grid lines as well as how to blend them ("exclusive or" on or off), and you can also enabled grid snapping, which will snap what you draw to the nearest grid square when active.
  • Show Preview: This will toggle the preview window for your sprite on or off. The Preview window appears in the main editor window, and if you double click on it, you can switch between x1, x2 and x3 scaling, giving you a much clearer picture of the sprite and how it looks while editing it in the main window.

  • Set Transparency Background: This option will open the Transparency Settings window where you can change the grid of squares shown when any part of your sprite is transparent. The menu permits you to change the block colours, as well as their size, or select a flat colour:
  • Toggle Scratch Page: This will toggle the current drawing canvas to be either the current image index, or the scratch page.

Back: Editing Sprites
Next: The Sprite Editor Edit Menu

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Preferences

The section details the preferences that customise the global features of GameMaker: Studio.

The drop down File in the main GameMaker: Studio window has an option marked Preferences. Selecting this will open the following window: Here you can see, change and save a number of things related to how GameMaker: Studio looks and works, like the skin to use, any external editors you wish to link to as well as server information for testing your games and other internal preferences. The sections listed below outline the use of each of the available tabs, and in all cases if you press Okay will close the window and confirm all changes, while pressing Cancel will close the window without saving:

  1. General Preferences
  2. Form Preferences
  3. Scripts Preferences
  4. Editor Preferences
  5. Server Preferences
  6. Source Control Preferences
  7. Steam Preferences
  8. Android Preferences
  9. Windows 8 Preferences
  10. UWP Preferences
  11. Windows Phone 8 Preferences
  12. macOS Preferences
  13. iOS Preferences
  14. Ubuntu Preferences

Back: Advanced Use Index
Next: Debugging

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Android Preferences

The section details the Android device preferences tab.

For GameMaker: Studio to work with Android device, a number of things need to be set up. First, you must have installed the Android SDK along with the API packages required for your game to run (as well as a test device with Android installed), the Android NDK, and you must also have installed the Java SE Development Kit (JDK). Once you have them installed and updated you should set up your Web Server Preferences before continuing with the configuration of this tab. You can get up-to-date information on whgat version of the SDK and NDK is currently required from this helpdesk article: SDK Version Support.

Keystore

The KeyStore is a file that will be used to "sign" all your Android apps - including those created for the Amazon Fire target platform - so please fill in all the details correctly:

  • Name: This is the name of the KeyStore file. Note: This is not your name or the company name, but the name of the file to be generated!

  • Password: Your security password for the KeyStore file which must be at least six characters long.

  • Alias: This is another name that can be used for the KeyStore file and should be different to the name entered above.

  • Password: The password for the alias file. Should be the same as the Name password.

  • Common Name: This would normally be your name.

  • Organisational Unit: The department within the company that you are a part of.

  • Organisation: The name of your company.

  • Location: The name of the town or city where you are based.

  • Country: The standard two letter code for the country where you are based.

Once this information is filled in and you are happy with it, press the button marked Generate for GameMaker: Studio to create the necessary KeyStore file. This may take a moment but once it is finished, you will see that the section marked Private KeyStore File will have been updated to reflect the new name that you have given it. Once this is done it normally will not need to be changed again.

There is a further option here marked Show Key Hash. Pressing this will generate two special security hash keys directly linked to your Keystore file that some web sites require for correct functionality (for example, Facebook, or Google Play for the Sha1 hash). Should you need this, simply press the button, then copy and paste the hash keys that are generated.

SDK

The SDK Tab is where you supply details of the installed components that GameMaker: Studio needs to compile Android *.apk files.

  • Android SDK Location: The location where you have installed the Android SDK. This should have been filled in automatically, but if not then you can use the button on the right to open a file browser and select the appropriate file location.

  • Android NDK Location: The location where you have installed the Android NDK. As with the SDK, this should be filled in automatically but if not you can browse to the file location manually.

  • Java JDK Location: The Location where you have installed the JDK. This should been filled in automatically, but if not then you can use the button on the right to open a file browser and select the appropriate file.

You should click the button marked Check Android SDK, as this will validate all the information and inform you of any errors (in which case you should revise all the information to make sure it is correct). When everything checks out you should receive the message "SDK + JDK + KeyStore OK".

There are a few final options at the bottom of the tab:

  • Always do full install of APK: Flagging this will make GameMaker: Studio remove any previous runners of your game from your device, as well as all associated files (for example, *.ini files) from your test device before installing a new version of the game.

  • Install on "Create Application": When this option is flagged, compiling a complete *.apk will install it automatically on any devices that are connected.

  • Use Mac for ADB connection: Should you wish to connect your Android device to a Mac, you can click this option to have GameMaker: Studio connect to your Mac and test your games that way. Note that you must have set up the Mac Preferences correctly, have the Android SDK installed on the Mac and given the correct ADB directory (see below).

  • ADB Directory on Mac: When you have the above option, Use Mac for ADB connection, enabled you can set the directory for ADB here.

  • ADB IP Address: By default this is blank, but you can input a specific device IP and use this to force ADB to connect to that over Wifi rather than over USB for testing (useful for the Amazon Fire target platform, for example).

  • Java Max Heap Size: Set the size of the Java Memory Heap for the Android JDK

Back: Preferences
Next: iOS Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Editor Preferences

The section details the editors preferences tab.

It may be that when making games you are more accustomed to using another suite of tools, and that you really only want to use GameMaker: Studio to bring all that work together in one place. Well, thankfully, GameMaker: Studio offers you the flexibility to keep using those tools by allowing you to define them as your default editor for the chosen resource. In this way you can have an external sound editor, or image editor etc... that will open instead of the default one whenever you open the specific resource for editing.

Code Editor

Here you can choose whether to use the built-in code editor (highly recommended) or an external editor. In the case of an external editor, the script text is saved as a *.txt file and the editor is called with this file as an argument. After editing it you should save the file and close the editor such that GameMaker: Studio can read the file back in.

Image Editor

You can also choose whether to use the built-in image editor or an external editor. In the case of an external editor, the image is saved as a *.png file and the editor is called with this file as an argument. After editing it you should save the file and close the editor such that GameMaker: Studio can read the file back in.

Sound Editors

You can indicate the different external editors for the sound files you want to use asGameMaker: Studio does not contain internal sound editors yet. There are two possible editors, one each for handling .wav and .mp3 files. In the case of an external editor, the sound is saved as a *.wav or *.mp3 file and the corresponding editor is called with this file as an argument. After editing it you should save the file and close the editor such that GameMaker: Studio can read the file back in.

You can also set your own player to play back the sounds that you add to your game by setting the path in the External Sound Player option. After setting this, when you press the "Play" button in the sound editor window, it will use the program linked here instead of the built in playback device.

SWF Viewer

This option for the tab permits you to define an external viewer for any SWF sprites that you have imported into GameMaker: Studio. This can simply be set to Internet Explorer or some other browser, or you can set it to any other program that correctly reads and shows the format. Once this is set, you can click the Show Sprite button in the Sprite Editor and it will launch the chosen program to show the complete vector animation.

Spine Editor

This final option for the Editor tab permits you to point GameMaker: Studio to the location of your Spine binaries. In this way you can click the Show Sprite button in the Sprite Editor and it will launch Spine to show the selected Skeletal Animation and permit you to edit it.

Back: Preferences
Next: Server Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Form Preferences

The section details the form preferences tab.

The Forms Preferences tab deals with the visual aspect of some of the standard GameMaker: Studio windows. It is split into four main sections, each of which is outlined below:

Sprite Form

  • Show the origin in the sprite image: If checked, in the sprite image of the sprite properties form, the origin for the sprite is indicated visually with a cross.

Object form

  • In object properties, show hints for actions: If checked then in the object properties form when you hold your mouse over one of the actions, a tooltip description is shown.

  • Default Tab to select: This allows you pick the default action tab when opening the object window. This can be handy, for example, if you only ever use the code action as you can then set this to select tab 4 and it will save you having to pick it every time. This option also works for Timelines.

Room Form

  • When closing, remove instances outside the room : If checked, the program warns you when there are instances or tiles outside a room and gives you the option to remove them.

  • Remember room settings when closing the form: If this is checked, then a number of room settings, like whether to show the grid, whether to delete underlying objects, etc. are remembered when you edit the same room later.

  • Room Grid ON by default: This allows you to disable the room grid each time a new room is opened or created.

  • Fill room with colour when no background colour selected: If you create a room and don't give it a fill colour it will normally fill it with the user definable default colour. If you untick this box then you will see the default user definable grid through the room. This can sometimes be useful to help visualise a level.

  • Show minimap in room editor: Unchecking this option will remove the minimap from the GameMaker: Studio minimap.

General

  • Open forms as maximised by default : If checked, the program will try to open all windows maximised.

  • Resource Group Open/Close Hover Delay : This option sets the delay time (in milliseconds) after which the GUI will detect any assets being relocated to a group folder in the resource tree.

  • Restore Resource Tree On Empty Search: This option will restore the resource tree to its default layout if an empty search is given.

Back: Preferences
Next: Scripts Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


General Preferences

The section details the general preferences tab.

The General Preferences tab deals with the visual aspect of GameMaker: Studio as well as certain general behaviours. The following options are available:

  • Show recently edited games in the file menu: If checked the eight most recently edited games are shown under the recent files in the file menu.

  • Close compile form after execution: When you run your game, it is compiled by GameMaker: Studio to run on the target platform, and this process is shown in the compile window. Normally this window is always open (and can be docked at the bottom of the main window), but you may wish to only see it when only when compiling, in which case you should tick this option as it will automatically close the compile window when finished.

  • Delete from resource tree deletes from disk: If this option is checked, when you remove a resource from the resource tree, it will also be removed from the computer. Use with caution! This may lead to the accidental loss of resources.

  • Do not launch game in fullscreen: When checked, this option will override any other fullscreen functions when you launch your game and force it to start windowed. This is provided as a debug tool.

  • Show commands in compile window: When you create a new final app or are testing the current one (normally or in debug mode) the compile window will show the currently running commands. Un checking this flag will switch off most of them and prevent the compile form from showing what is being done. The default (and recommended) value is to have this switched on.

  • Show commands with verbose flag: This check-box is used to switch on (or off) verbose messages in the compile window. When switched on, the default command messages that are shown in the compile window (when the above "Show commands in compile window" is checked too) will contain far more information about the current status of the app being compiled. This may slow down the app as it runs and is flagged as off by default.

  • Show compile form on startup: Flagging this will open the compile form automatically when you start GameMaker: Studio. If it is not flagged, then the compile form will only appear when you first test your game or when you create the final executable.

  • Enable backup on save: This option can be used to switch on the automatic backups that GameMaker: Studio can make of your project. When this is enabled, you can select a Backup Directory to save a full backup copy of the current project too, as well as the Number of backups that you wish to keep. Once this is enabled, every time you save the current project you will also have a backup copy saved to the chosen directory. These backups are numbered concurrently, starting at 0. Please note that the current (newest) backup is always the first! Each time you save, previous backups are re-numbered with an increment of one (removing those that are numbered larger than the specified number of backups) and the latest save is numbered as 0.

  • Enable backup on run/debug/create: As above, only this will enable or disable the creation of backups when you run the game normally or in debug mode, or when you create a final executable.

  • Toggle resource scoping on resource tree: When you use F12 (or the middle mouse button) on a resource in your code, it will jump to that resource in the editor and then open its properties window. However if you don't want the currently selected resource to change when you use this action, you can disable this option, and only the properties window will open for the selected resource while the scopewill not change in the resource tree.

  • Directories: You can set the different directories that GameMaker: Studio will use to save the asset cache, the temp files and any backups of your projects. Note that each of the given directories also has a "Clear..." button which will wipe all the accumulated data from the given folder.

  • Show news on startup: Sets whether to show the GameMaker: Studio news when you start the program.

  • Show news in default browser: Sets whether to display the GameMaker: Studio news in your default Internet browser, rather than in the program itself.

  • Always reload changed files: This option is to permit GameMaker: Studio to reload files that are changed on the disc automatically. If this is flagged, then any images, sounds or scripts that are changed from the project *.gmx file itself will be silently re-loaded into your game. if it is not flagged, you will get a message prompt asking you if you wish to change the files.

  • Automatically increase build number: When checked the build number will increase automatically.

  • Automatically add build number and date constants: When checked, the internal constants for build number and version ( GM_build_date and GM_version) will be increased automatically. This option will switch these off as they may interfere with any SVN solutions that you are using.

  • Add config and version to filename on create executable: Flagging this will generate a build number (including config name, if configs are used) automatically when you create an executable of your game.

  • Do not show YoYo Games Logo in the main window: When checked the image and link to the YoYo Games website in the main window are not shown.

  • Do not show prompt on closing code editor: Flagging this option will prevent the code or script editor asking you if you wish to save any changes and instead will silently save on close always. The default (and recommended) setting for this is to have it switched off.

  • Big resource tree icons: Checking this will make all the resource tree icons larger (GameMaker: Studio must be restarted for this to show).

  • Enable Pop Out Windows: Checking this will permit you to drag the component windows out of the main IDE and position them elsewhere (useful if you have more than one monitor).

  • Automatically Clean Temp Data On Shutdown: Checking this will force GameMaker: Studio to automatically clean any temp folders when the IDE is closed.

  • Automatically clear Temp Data on shutdown: This option will clear the Temp Data folder every time you close GameMaker: Studio. The Temp Data folder can quickly fill up with unnecessary files, especially if you have been working on different projects, so this option will help to keep things tidy.

  • Open properties on Duplicate: This option will enable or disable the opening of the resource properties window when you use the Duplicate option from the right click menu.

  • Disable Thumbnail Icon Generation: This option will enable or disable the generation of resource thumbnails. This is general best disabled, but when working with larger projects, enabling it can help maintain a smoother IDE response time.

  • Show filter tree option on main form: With this option you can enable or disable the resource tree filter options in the bottom left of the IDE.

  • Home directory: Here you can set the directory that you want GameMaker: Studio to use for projects by default.

  • Select Skin: Check to use a different skin for the GameMaker: Studio GUI (GameMaker: Studio must be restarted for this to show). It should be noted that custom skins must placed in the Local app data folder (%localappdata%) otherwise they may be overwritten or removed when GameMaker: Studio updates.

Back: Preferences
Next: Form Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iOS Preferences

The section details the iOS preferences tab.

From this tab you can set the xCode build target for iOS games to be either a device or the iOS Device Simulator. This is done by clicking the initial input box and selecting the appropriate device/simulator to use.

Under that you have the option "Suppress Build and run". This option is for those users who have a Mac running macOS Sierra or above. With macOS, you need to suppress the default build action from GameMaker: Studio, and instead simply send the app archive to Xcode and then build and run it yourself from the Xcode UI.

Finally, you can supply a default Team Identifier for all future iOS apps that you make with GameMaker: Studio. This will be used to have Xcode automatically sign your apps with the correct profile and certificate, and you can find the Team Identifier from here (you must be signed in to your Apple Developer Account). As with the above option for suppressing builds, this is only applicable to macOS Sierra and above. This default identifier will be used to populate the iOS Global Game Settings, but can be over-ridden on the Provisioning sectio0n of the Global Game Settings if required.

Back: Preferences
Next: Ubuntu (Linux) Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Ubuntu (Linux) Preferences

The section details the Ubuntu (Linux) preferences tab.

For GameMaker: Studio to work with a Linux OS system, a few things need to be set up first in the preferences. Once you open this tab you will see the following sections that need to be filled in for GameMaker: Studio to be able to communicate properly with your Linux system (either as a Virtual Machine or a separate computer running Linux) and for you to test your games:

  • Linux Host Name - This is the name (or IP address) of the Linux system on the local network that you are going to use.

  • Linux User Name - This is the name of the user account that will be active for testing your games.

  • Linux Password - The password for the user account specified in the section above.

  • Linux Install Directory - The place on the Linux system that you wish GameMaker: Studio to install the necessary files to test and run your games.

Below these inputs is a button labelled Check Linux Connection which you can use to test the information you have supplied to make sure that the connection to your Linux System is correct and working.

Next, there is a button marked Clear SSH Keys which is used to clear the Secure Shell Hash. This is provided as an option for those users that have changed systems, or re-installed the Ubuntu (Linux) OS on their current one, and need to re-configure their secure keys.

Finally you can choose to have your game install and run when on the Linux OS when you create any final versions of your application, as well as set where it is installed to.

NOTE: GameMaker: Studio is configured to work with the latest Ubuntu OS. Your games should work on any Linux OS, but due the nature of linux as an open Source OS, it is impossible to guarantee that your games will work on any OS other than Ubuntu.

Back: Preferences
Next: Mac Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Mac OS Preferences

The section details the Mac OS preferences tab.

For GameMaker: Studio to work with an Apple Mac, a few things need to be set up first in the preferences. Once you open this tab you will see the following sections that need to be filled in for GameMaker: Studio to be able to communicate properly with your Mac and for you to test your games:

  • Mac Host Name - This is the name (or IP address) of the Mac on the local network that you are going to use.

  • Mac User Name - This is the name of the user account that will be active for testing your games.

  • Mac Password - The password for the user account specified in the section above.

  • Mac Install Directory - This is where the Application Oven/Xcode build output files go - the *.app.zip backup copy, plus any intermediate build files, splash screen images, configuration files, etc...

Below these inputs is the option to Suppress build and run. If this is enabled, GameMaker: Studio will not try to build and run your game on the target Mac device, but instead simply push the files to xCode.

Next is the button labelled Check Mac Connection which you can use to test the information you have supplied to make sure that the connection to your Mac is correct and working. Please note that you must have enabled Remote Login on the target mac. This can be done by going to Preferences -> Sharing and enable Remote Login for the user you want to be able to login.

Underneath the Check Connection button there is another button marked Clear SSH Keys which is used to clear the Secure Shell Hash. This is provided as an option for those users that have changed Mac, or re-installed the OS on their current one, and need to re-configure their secure keys.

Finally you have the Default Team Id field. Here you can supply a default Apple Team Identifier which will then be used for all Mac OS builds. If you leave this blank or you wish to override this ID, you will need to supply one in the Mac OS Global Game Settings, otherwise your game will not build.

Back: Preferences
Next: Windows UWP Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Scripts Preferences

The section details the scripts preferences tab.

These settings relate to the way the built in script and code editor works (explained in detail in the section about Scripts).

  • Group undo operations: When grouped multiple actions (like typing a whole line) becomes one operation for undo.

  • Number of undo: You can use this to change the number of "undos" that GameMaker: Studio stores. The default is 1000.

  • Automatic indentation: When set Enter and Backspace keys automatically add and remove indents based on the line of code above.

  • Indent amount: How much to indent with each tab (in spaces, with the default value being 4).

  • Smart tabs: When set tabs go to the position below the first non-empty space in the previous line (automatically indenting the code).

  • Allow cursor beyond end of line When checked you can place the cursor at any position in the editor screen, also beyond the end of line (if unchecked this is not possible). This also changes the behavior of the left and right arrow keys.

  • Show auto-completion options: When set, help is given, in the form of a pop-up window, in which functions and variables that start with the letters you are typing will be shown.

  • Delay (msec): The delay in milliseconds before the auto-complete is shown. Set to 1 for immediate (default 2000).

  • Update Delay (msec): The delay in milliseconds before the auto-complete window refreshes (after being shown). Set to 1 for immediate (default 2000).

  • Syntax Check (msec): The delay in milliseconds before the syntax checker will check the code you have just written. Set to 1 for immediate (default 750).

  • Show function argument help: Checking this option will show the function and its available arguments on the statusbar at the bottom of the editor.

  • Show find string: If this is checked then whenever you are typing in a find string, all locations of that string are shown in the editor.

  • Show line numbers: Whether the code and script editor should display line numbers (this will affect actions too).

  • Show code snippets with F2: When set, pressing F2 will bring up a number of useful code snippets.

  • Debugger Manual IP Entry: With this option checked, the debugger will permit you to input an IP to connect to instead of auto-configuring. This option should only be checked if you are having an issue connecting to mobile devices when debugging.

  • Debugger Port: Here you can set the port that the debugger uses for communication.

  • Tooltip Display Time: This can be used to set the display time (how long they are displayed for for tooltips (in milliseconds).

  • Show matching brackets: Whether the editor should indicate matching open en close brackets.

  • Check code while typing: When set the code is constantly checked and errors reported.

  • Enable BOLD on script keywords: Allows you to have all script keywords in BOLD. Please select a FONT where the width of the BOLD string, is the same as the width of the NON-BOLD string.

  • Use colour coding: Whether to use colour coding in the editor.

  • colours: Here you can set the colours used for colour coding in the editor (You can also save, load and reset the colours).

  • Font Here you can select the font for the editor. Note that only fixed pitch fonts are shown. Also note that only the font and the size are used.

Back: Preferences
Next: Editor Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Server Preferences

The section details the web server preferences tab.

Here you can set up the web server that GameMaker: Studio is going to use. The available options are:

  • Web Root Directory: Normally you can just leave this blank but if you get any errors you can use this to point the server to a specific place on your computer.

  • Web Browser Location: This is where you must select the default browser for testing your GameMaker: Studio Html5 project.

  • Web Server Port: This is set to 51268 to 51280 by default. There is no need to change this unless these ports are already in use.

  • IP Allowed List: Enter your local IP Address here as seen in this example: 192.168.1.1/24. You can also add other device IP addresses as necessary.

If you are not sure of your IP address, then you can find it by following these instructions:

  • Hold down the “Windows key” and press “R” on the keyboard to bring up the "Run" window
  • Type “cmd” and hit the enter key to bring up a command line prompt
  • Type “ipconfig” and then hit enter
  • Find where it says ipv4 and your IP address is the following number

The Micro Web Server

The Micro Web Server is a small program that GameMaker: Studio uses for HTML5 games and for connecting remotely to other computers and devices. It shows the currently connected IP addresses as well as a log of events for each address, and also has the permitted IPs that you entered in to the Preferences, above.

Note that you cannot change any of the information displayed here in the Micro Web Server itself, except for the network speed. This has a slider (and accepts direct keyboard input too) which can be used to "throttle back" the server connection speed and so simulate poor or limited network conditions, which can be very useful for testing HTML5 games.

Back: Preferences
Next: Source Control Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Source Control Preferences

The section details the source control preferences tab.

From this tab you can point GameMaker: Studio to the version of SVN that you wish to use for Source Control Management (SCM), or choose a custom SCM solution. By default this points to the latest version of SV that is bundled with the program and we recommend that you always use this version as GameMaker: Studio has been optimised for it. However, you may have installed a different SCM solution, like GIT or Mercurial (or wish to use a different solution altogether), in which case you would need to set the two file paths to point to the correct binary executable for the solution (for example C:\Program Files (x86)\Git\bin\git.exe) and then the location of the configuration file for the solution.

If you do not have a config file, you will need to create one and include all the commands that you require GameMaker: Studio to use. These will then be added as part of a context menu that pops up for SCM in the GameMaker: Studio IDE. You can find out how to make configurations for Mercurial and GIT from the Source Control Tutorials available from the YoYo Games Knowledge base, although below you can find a general outline of the procedure for all SCM solutions.

You can also choose to have the SCM solution output to the Compiler Message window Source Control tab. Ticking this will show the log of actions, and should generally be left on. The next option "No Folder Commits" is designed specifically for the Mercurial SCM solution, and should not be ticked for either SVN or GIT. All this does is not commit the SCM solution. So, for example, if you have this: C:\FolderA\FileA.txt. SVN assumes you'll add and commit FolderA and then FileA - and will tell at you if you don't. Git doesn't really care, but it is best to follow the same as SVN anyway for consistency. However Mercurial assumes you'll only add and commit FileA - and will error if you attempt to add and commit FolderA as well. So, tick this option for Mercurial (or any other SCM solution with a similar behaviour).

If you are using anything except the built-in SVN tools, then you should also select the Enable Advanced SCM Options check-box here. This will give further options when defining your SCM config file for the chosen tools.

If you do not wish to use any of the built-in SCM options, then you can disable it completely by ticking the check-box "Disable SCM Usage" and then restarting GMS. Note that this will remove all SCM options from the user interface, so if you wish to add source control to a new project later, you must first enable it here again.

Finally, you can choose to have the Conflicts Editor use colour coded conflicts or not (default is on).

Custom Configurations

Since there are a wealth of commands and possibilities open to you and each SCM solution has a slightly different way of doing things, all the SCM tools in Gamemaker: Studio are taken from a configuration file. This file is generated automatically for you for SVN, but for GIT, Mercurial or any other solution, you will have to set this up yourself (as mentioned above, there are tutorials available from the YoYo Games Knowledge Base).

To create a new SCM configuration you need to click the button marked "Create SCM Config" which will open the following window: As you can see this window has three tabs, and each tab is split into it's own sub-sections. Each tab relates to a specifc aspect of SCM and can be set to suit your own SCM solution based on the documentation that is provided with it. When you create a new SCM config, it is created pre-populated with the default values for SVN, so be sure to revise and change these to what you require.

The tabs are:

  1. General: The General tab deals with the Common SCM commands and External SCM Tools (which currently only covers the merge tool to use). Each command as a pre- and post- stage, and is split across the top two windows. The windows available in this tab are:

    • The first window (top left) describes a common key and the command value to run.
    • The second window (top right) describes any parameters to be sent. For example, in the default SVN config, the Add command has the parameters "$FILE --parents --force".
    • The third window (bottom left) describes the external tools to use.
    • The fourth (bottom right) is for defining the SCM parameters.

  2. Status Log: The Status Log tab helps GameMaker:Studio understand the log structure of the SCM solution. This is split into three windows:

    • The first window (top left) describes the log header names. In the case of the default SVN config, this would include status, props, locked, history, switched, lock-info, tree-conflict, out-of-date and filepath.
    • The second window (top right) describes the values that each of these fields support. For example, in the default SVN config, status supports ' ,A,D,M,R,C,X,I,?,!,~'. The filepath key can also use a special $STRING named $PROJECTPATH which ensures that the files in the list only belong to the current project's path (note that the asterisk '*' can be used to denote "accept anything").
    • The third window (bottom left) describes what the status symbols mean, in a common format. For example, SVN's ' ' ( space ) is generally meant to mean unmodified in the status log.

  3. Functions: The Functions tab allows you to define the Source Control right-click menu in the Resource Tree, as well as add additional functions to the menu that not every SCM solution has - such as lock/unlock, or push/pull. This is also split into three windows:

    • The first window (top left) describes the common functions to be displayed in the right-click menu. New functions can be added by clicking the Add Function button. Clicking on a cell in the Command column will bring up a drop down box with the available commands to choose from. The Title is what will be displayed on the menu.
    • The second and third windows (bottom left and bottom right, respectively) are similar to the previous tabs, in that the left one describes the commands, and the right one describes the arguments. Again, both Command columns must match up - the Title column describes what will be displayed on the menu, and the Options column can contain the $FILE string.

At any time you can reset a tab to it's default values by clicking the button labelled "Set To Defaults", and you can also save any configuration to a specific place for safe-keeping by clicking the button "Save As". these can then be loaded again at any time from the file path selector of the Preferences (as mentioned above).

You can find further information on Source Control Management from the pages on Source Control and there are additional articles that cover how to set up GameMaker: Studio to work with GIT (for example) from the YoYo Games Knowledge Base.

Back: Preferences
Next: Steam Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Steam Preferences

The section details the Steam API preferences tab.

From this tab you can point GameMaker: Studio to the version of the Steamworks SDK that you have installed on your development machine. This SDK will only be available to you from the Steam Developer Area, meaning that your game must have been approved for Steam previously to use this (either through a publisher or through the Greenlight system).

Once you have directed GameMaker: Studio to the Steamworks SDK, you should then click the Check Steam SDK button to ensure that GameMaker: Studio can communicate correctly with the necessary SDK components. If everything is correct, you should see "OK" displayed.

Back: Preferences
Next: Android Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


UWP Preferences

Windows UWP Preferences

The section details the UWP preferences tab.

For GameMaker: Studio to work with the UWP (Universal Windows Platform) target, you need to specify the path to Visual Studio. Visual STudio is required to build the games, and once you have supplied the path to your installation, you should click the button labeled "Check Native SDK" to ensure that it has been discovered correctly by GameMaker: Studio. You will also need to supply the Minimum and Target SDK platform version before you are able to compile anything.

Back: Preferences
Next: General Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Windows Phone Preferences

Windows Phone 8 Preferences

The section details the Windows Phone 8 preferences tab.

The first thing to do before starting to test or create a Windows Phone 8 game is to set up this section of the preferences for the Windows Phone 8 module. All you really have to do here is check that SDK Status says "OK" (GameMaker: Studio should have already performed the necessary checks when you upgraded to the module, but if not you can use the "the click the "Check SDK" button (Read the section on SDK Problems for help) to force GameMaker: Studio to perform this action.

Next is the part where you can select the device that you wish to have the emulator use for testing your game on. The available devices are:

  • Device - Your own Windows Phone 8 test device, plugged into your PC by data cable.

  • WVGA (512mb) - Emulates a memory-constrained Windows Phone 8 phone with a display size of 480 x 800.

  • WVGA - Normal Windows Phone 8 with a display of 480 x 800.

  • WXGA - Large Windows Phone 8 display at 768 x 1280.

  • 720p - HD display at 720 x 1280.

Note that you can change the emulator target at any time through the preferences, and should you have any problems with the emulator, as long as the SDK is installed and checked, you can always test using a Windows Phone device connected to the PC.

WARNING! When building your final game package, you must have this set to "Device" otherwise your submission to the Windows Store will fail.

Back: Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Windows 8 Preferences

The section details the Windows8 preferences tab.

Here you can set up the preferences that GameMaker: Studio is going to use with your installation of Windows8 for testing games. Before stating to use the Windows8 target platform you must have installed the Visual Studio Express 2012 SDK that supports building Windows Store JavaScript applications (this can be found here). Once that is installed the values for these preferences should be automatically generated. If these values are incorrect or are not generated automatically for you, you should do the following:

  • Make sure that the section titled VS2012 Cross Tool points to the "vcvarsall.bat" in your MS Visual Studio installation. Without this you won’t be able to successfully create Windows Store packages.

  • The WinJS API reference and WinJS Api Version need to match with the WinJS API that comes with your version of Visual Studio. To check this, create a blank Windows Store JavaScript app in Visual Studio and, under References, right-click the Windows Library for JavaScript reference and select Properties. You should see an SDK Identity property that tells you all you need to correctly fill out these details.

You should also note that for GameMaker: Studio to generate your app correctly, you will need a Developer Key. Please refer to the section Global Game Settings - Windows8 Tab: Installation.

Next you need to point GameMaker: Studio to the Windows 8 SDK Tools which you can find in the folder "../Windows Kits/8.0/bin/x86". Finally you should click on the Check Native SDK button to confirm that your selections are okay and that everything works as it should. If you get an error or you are not sure that your Developer Licence is correct, you may also click on the button labelled Acquire Developer Licence which will open up a command prompt and automatically go through the necessary steps to get you one.

Back: Preferences
Next: Windows Phone 8 Preferences

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Source Control

Source Control Management

GameMaker: Studio incorporates a complete source control management system, ready to use with any one of the SCM packages available.

Source Control Management (SCM) is the name given to the method of working with sub-versions or backups of your projects through a repository and local source. Basically, an SCM solution is an independent software package which controls all the aspects of maintaining, changing and comparing versions of your project as you work on it. This is especially useful to those that work in a team and need to be able to control who does what and not worry about losing data or making changes that may need to be undone at a later date, but individuals can benefit from this powerful yet flexible system too.

We recommend that you have some working knowledge of how source control works before attempting to use it in GameMaker: Studio.

There are various SCM tools available to you, and GameMaker: Studio permits you to use the three most popular:

  • SVN
  • GIT
  • Mercurial

NOTE: You can use other SCM solutions, but these are the ones that GameMaker has tutorials and default configurations for. Other tools will require you to set up custom profiles, which are explained briefly on the page Source Control Preferences.

If you are not too familiar with SCM solutions then we recommend you use SVN and install a user-interface like TortoiseSVN. GameMaker: Studio comes bundled with the 1.7 and 1.8 versions of SVN by default, so if you use this option make sure that the user-interface you use is for the either of the those versions (preferably the 1.8 version). Both GIT and Mercurial are advanced SCM solutions and require that you have a good working knowledge of how SCM works, and prior experience with both is a benefit if possible.

It is important to note that we recommend that you change the following Preferences before continuing to activate SCM in GameMaker: Studio:

  • General - Automatically increase build number
  • Forms - When closing, remove instances outside the room
  • Forms - Remember room settings when closing the form

The following sections outline the necessary steps that you need to take to get Source Control working in GameMaker: Studio:

  1. Getting Started With Source Control Management
  2. Setting Up GameMaker: Studio For Source Control Management
  3. Using Source Control Management with GameMaker: Studio

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

Back: Advanced Use Index
Next: Global Game Settings

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Getting Started With Source Control Management

This is the basic setup guide to get you started using Source Control Management with GameMaker: Studio and any one of the SVN Client packages available.

Before even opening GameMaker: Studio and working with Source Control, you will need to setup your PC (and that of your co-workers if you are in a team). GameMaker: Studio comes bundled with versions of SVN that have been tried and tested with the software for compatibility, and if you do not have any other SVN versions on your machine this will be the default version that you use. However, if you already have SVN installed, you can choose which to use from the Source Control Preferences Tab (the default is that which is installed with GameMaker: Studio).

Please note, that for optimum performance and to minimise problems all machines involved should be using the same version of the software, so if one machine is on (for example) v1.8.72, then they all should be using the v1.8.72 of that software. This is one of the reasons that we recommend you use the version bundled with GameMaker: Studio as it will ensure that your whole team is using the same version at all times.

Once you have installed your SVN tools, you will need to make your Repository. This is where all your files, backups and edits will be stored and is normally hosted on a separate server, either on-line or locally. To create the initial repository, and generally use your SVN, you can do it in one of two ways:

  • either use command line functions to directly communicate with SVN or
  • download and install some form of windows interface like TortoiseSVN

We recommend some form of windows based UI for dealing with all the SVN functions as it greatly simplifies everything and some of the functions that it offers (like conflict resolution and log files) are easier from outside the GameMaker: Studio IDE, but the final choice is up to you and depends on what you feel most comfortable with!

NOTE: These guidelines are still generally applicable to GIT or Mercurial solutions, only you will have slightly different tools and setting up repositories works differently. You should see the documentation for your chosen SCM solution to get information on how to set up the initial repository and to find out the commands available, as it is not covered here.

Using The Command Line

If you are happy using the command line functions then you can create the repository easily by opening the windows command prompt, browsing to the network location where you wish to create the repository (or just make sure to use the full path to the location) and typing:

svnadmin create NAME

where "NAME" is the name you wish to give your central repository (something like "Source" or "Repository"). Please note, that if the repository is to be created in a sub-folder then that sub-folder must already exist, although the repository itself will be created by SVN. The code should look something like this:

Then press Enter and your repository will be created. Note that the above example is showing a path to a local repository (on the same computer) but you can change the path to a web address for an online repository (recommended).

Using A Windows SVN Client

Local Repositories

Once you have installed your windows client for SVN, you should browse to the network location where you wish to create the repository and there create a new folder. Give this folder the name you want to use for your central repository (something like "Source" or "Repository") and then right click on this folder. You should then go down the pop-up window to your SVN client and find where it says "Create repository here." It should be something like this depending on what SVN client you have installed on your system:

The above image was made using Tortoise SVN, so the exact method of going about this may vary depending on your client application, however all windows SVN Clients have basically the same toolset used for creating your repository.

Online Repository

If you have a network for your group then you may want to create a repository on your server, or you may wish to create an online repository using one of the many free repository services that are available out there. if you are using an internal server or local network, then the simply follow the above instructions for a local repository but instead of creating the folders on your own PC, you will create them on your server. However, if you are using an online repository then you will need to follow these steps:

  1. Sign in (or register) with your chosen site
  2. Create a new project
  3. Make sure that when filling in the details of your project that you have selected Subversion (SVN) as your version control system

Your online repository has now been created.

NOTE: Each online repository is slightly different so read the documentation related to the one that you choose! This is only a rough guide to get you started.

Back: Source Control Index
Next: Setting Up GameMaker: Studio

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Setting Up GameMaker: Studio For Source Control Management

Once you have your repository created and your SCM solution installed, you need to tell GameMaker: Studio to activate Source Control Management for your projects.

When you have prepared your computer with the necessary SCM applications, you have to tell GameMaker: Studio to add your projects into the SCM repository. This can be done for new projects as well as projects that have been started previously but never versioned. The steps to follow in either case are outlined below.

Preferences

By default the GameMaker: Studio Preferences will be set to use the latest version of SVN that is bundled along with the program, but should you wish to use a different version or another type of SCM solution, you will need to open the Source Control Preferences Tab to point to the installed solution that you wish to use.

If you select a "Custom" solution, then you will also need to set the two file paths to point to the correct binary executable for the solution (for example C:\Program Files (x86)\Git\bin\git.exe) and then the location of the configuration file for the solution. If you do not have a config file, you will need to create one, which is explained in more detail from the Source Control Preferences Tab page of this manual. Note that if you are using Mercurial, the final option in the preferences "No Folder Commits", should be checked (but only for Mercurial).

Adding Source Control To A New Project

When you create a new project, you can tell GameMaker: Studio to add it directly into Source Control so that all further work done on this project can be versioned. To do this, you must first create the project and make sure that you have selected "Use source control" from the new project form, like this (note that if you have disabled source control in the Preferences, you will not see this):

You would then click on the "Create" button as normal, but before you can actually start working on your new project you are presented with another form where you can enter your username and password (whoever administers the system will have given you this, otherwise just leave it blank), as well as point GameMaker: Studio to the location where you created your repository:

Once you have done that, just click "OK", and now you are ready to work on your project with source control keeping track of all the changes that you make. Note that this dialogue also has a "Checkout" button, which enables you to pull down an existing repository (based on the settings the user has typed into the form) to use as a base, rather than a blank new project.

Adding Source Control To An Existing Project

If you have been working on a project without having it configured for source control, it's still not too late and you can actually version it too and have it protected the same as any new file. To do this, you have to go to the Global Game Settings and select the Source Control tab, then fill in the relevant details. It should look something like this:

The Username and Password fields should be filled in with the name and password proportioned to you by whoever administers the system (if you have none, or don't know them, then just leave it blank) and the URL should point GameMaker: Studio to the location where you created your repository. Finally, click on the "import Project to repository" button to version your current project and add it to the source control repository. Note, that this only needs to be done once for any project and you should never need to do this again. Make sure to tick the "Use Source Control" checkbox at the bottom before closing the window and saving the settings.

Summary

Whether you choose to start a new project or add a previously started one into your source control repository, it is essential that you understand what is happening and how this system should work from now on. Basically, you now have two copies of your project - a local one stored on your own computer and a versioned one stored in the repository. All changes you make to your project from this point onwards will be made to your local copy, not the copy stored in your repository.

When you have worked on your project and are happy with the changes you have made, this project is then committed to the repository along with a short comment about what you have done, and it is given a version number. What this means is that you can go ahead and make changes to your project safe in the knowledge that at any time you can "turn the clock back" and recover a previous version from your repository... you can even go back several versions if it is necessary! This also means that several people can work on the same project knowing that should someone make an error, it can be easily fixed and doesn't need to negatively affect the other people in the team.

For a more detailed explanation of how to add and commit files to your repository, please continue to the next section "Using Source Control".

Back: Source Control Index
Next: Using Source Control Management

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Using Source Control Management with GameMaker: Studio

Once you have everything setup correctly, GameMaker: Studio has its own set of tools for working with Source Control.

When working with your game in a source controlled setup, it is important that you follow the same steps all the time when creating, committing or reverting files in your game. To make things easier, below you can find a brief overview for the three main procedures that you will need to work with.

Adding New Files

When creating a new resource for your game (whether it be a room, a sprite or a time line), there are a couple of steps that you should always take to ensure that it is correctly versioned in your source control repository:

  • Create the resources by adding the scripts, objects, sprites etc...

  • Save the project as the resources do not exist outside of the IDE and this will add them to the SCM repository for committing.

  • OR run/test the project which will also add the resources to the SCM project repository for committing.

Now that you have added your resources to the repository, you can continue working on them as before, with each save or test run of the game updating the files to be added to the repository. however, just adding them does not actually commit the changes. This is explained in the following section.

Committing Files

Adding files (as explained above) only marks the files as "to be added" to your source control repository but doesn't actually save them there. So we must now commit the files in order for the repository to hold these files. This step is very important as without it, your repository will not be up to date and you cannot use any of the source control features.

To commit files to the repository, follow these simple steps:

  • Right click on the resource in the resource tree and select Source Control -> Commit All (you can also select Commit directly from the menu but that is for individual files and also we have a lot more than just your new files to commit, as you will see).

  • You will now get a commit dialog. At the top you can add a message which will be logged along with your commit so that others can get a general idea of what you committed, and below this you will see all files that you are going to commit.

  • You will see that there are a lot of files in there, with most of them being the config files and images. You can choose just what to commit here by deselecting items in this dialog. The left panel shows file names and the check-boxes for deselecting and selecting them, while the right panel shows you the status of the file (A=added, M=modified, D=deleted, ?=un-versioned, C=Conflicted and !=Missing).

  • For this first commit, it is recommended that you do not deselect anything and commit everything, adding in as a message log something like "initial commit". Now press "Ok".

  • You will now see in the compile messages it is adding and committing to the repository. This can take a while depending on your connection and the amount of files. The first commit can be quite lengthy but you are looking for the message "Refreshing SVN Status...finished" which tells you that everything has been done and you can continue to work on the game.

Now that you have done your initial commit, the process should be more or less the same from now onwards, with you editing something, saving the project and then committing the change(s) to the repository, either using the commit all or simple commit commands from the right click menu of the resource tree. Note that you can right click on files in the list and revert, if need be. This is useful when files become missing because of conflicts, or even just accidental modifications. Also note that the actual status information is dependent on the SCM system being used. The ones mentioned above are specific to SVN but may not match up with Git or Mercurial.

Reverting Changes

One of the principal uses for source control is the ability to "roll back" your game to a previous state and undo any changes that have been made. This can be of particular importance when you have added something that breaks the game or have made some design changes that you want to go back and add in. in situations like this you will need to use the Revert option.

The following steps outline how to revert to the last committed version of a file stored in the repository:

  • Right click on a resource you wish to revert and click "Source Control -> Revert".

  • You will see a message appear in the compiler form at the bottom of the IDE saying "Reverted 'xxxxx.gmx'".

  • Your resource is now back to the previously committed version.

Please note that this is not reversible, unless you are reverting from an already committed change. If you make some changes without doing a commit and then revert, once you have reverted there is no going back to your non-committed version.

The GameMaker: Studio Interface

Once your game file has been added to your source control repository you will see that a new set of icons have been added to each resource on your resource tree. These are the GameMaker: Studio source control indicators and are used to give you a graphic representation of the versions of each of your resources and while working on your project will look a bit like this:

Obviously the exact icons you see will depend on your project and what you have been working on, but you still need to know what they all mean! The list below shows each one and explains their significance:

Updated: This shows that the resource is updated to the current version as stored in the repository.

Added: This icon means that you have created a new resource and it has to be added into the repository. This will happen automatically when you save your progress.

Modified: When you change a resource in any way this icon will appear beside it to let you know that it is now different to the last version in the repository.

Not Versioned: If you see this icon it means that the resource is not recognised by the SCM solution and should therefore be added to the repository. There is an "add" command provided for this in the right-click menu from the resource tree.

Conflict: If you get this icon it means there is a conflict between two resources. This can only usually happen when two or more people work on the same source and cannot be resolved through GameMaker: Studio. For that you will have to use your windows SVN Client to merge the two files or manually edit the *.gmx files.

You can work on your game as normal, creating, changing and adding resources as necessary knowing that these changes are only being done to your local copy of the game, not the versioned copy stored in the repository. As mentioned in the sections above, a game with source control active also has an extra set of commands available from the right click menu of the resource tree. These new options deal with source control and look like this:

As you can see there are two most common actions that need to be performed:

  • Add To Source Control: This will add a resource to the repository. When you see the [image] "Not Versioned" icon showing you will need to use this action.

  • Commit To Source Control: This will commit the selected resource to the source control repository. If you have a folder selected then everything in that folder will be committed, otherwise it will only commit the selected resource. When you commit something you will also be prompted to add a comment where you can briefly explain what you have added or changed, and this will then be stored along with the updated version of your project.

  • Update from Source Control: This will update the selected resource (or resources if you have a folder selected) in your local copy of the project from the repository. Any changes, additions or conflicts will now show up in GameMaker: Studio

Below those actions, you also have a further sub-menu titled "Source Control". There are further actions that you can perform listed here:

  • Edit Conflicts: Edit any conflicts that have been found using the SCM interface set in the SCM Preferences.

  • Show Log: This will show the log file for your SCM solution so you can see recent activity.

  • Show Status: Shows a status window for your SCM solution.

  • Commit All: Commits everything into the repository. You will be prompted to save your work to the local copy before committing.

  • Refresh: This simply refreshes the source control icons beside the resource (or resources if you have a folder selected) to reflect the current versioned status.

  • Refresh All: This simply refreshes the status icons beside all the resources.

  • Revert: With this action you revert the selected resource, or resources if you have a folder selected, to the last version you have updated to from the repository.

  • Revert All: Use this to revert all changes that you have done back to the last version you have updated to from the repository.

  • Update All: This will update all resources in your local copy of the project from the repository. Any changes, additions or conflicts will now show up in GameMaker: Studio.

  • Add All: Adds all resources in the resource tree that have not yet be versioned to the repository.

  • Cleanup: Cleans up your SCM files, refreshing status and icons and checking for conflicts etc...

It should be noted that there is no option to rename any resource as this is handled internally. So, when you have source control enabled and you rename (for example) a sprite, GameMaker: Studio will automatically change and update your local copy of the project without any need for your intervention. these changes will then be added to the repository on the next commit.

Also note that you can add your own commands to this menu at any time through the Source Control Preferences.

Conflicts

If you have any conflicts when committing your added files, you can select the Edit Conflicts option from the context menu (see the section above). This will open up the Conflicts Editor, where you can decide what to do. This editor will list the conflicting files on the left and present you with a number of options for what to do, available from the buttons on the right:

  • Edit Conflict: Edit any conflicts that have been found using the SCM interface set in the SCM Preferences.

  • Resolved: Mark the conflict as resolved.

  • Use Theirs: Update the conflicted file to use the other version.

  • Use Mine: Update the conflicted file to use the version being committed.

  • Refresh: This simply refreshes the current versioned status.

When finished you can close the Conflict Editor and then re-commit the conflicted files as normal.

Back: Source Control Index
Next: Getting Started With Source Control


Reference

This section contains all the information on the Game Maker Language

GameMaker: Studio contains a built-in programming language, commonly called GML, which gives you much more flexibility and control over your games than the standard Drag and Drop actions do. In this section we describe the language GML and we give an overview of all the functions and variables available to control all aspects of your game.

Getting Started

This section contains an overview of the GameMaker Language, with the rules for structure and syntax, as well as examples of how to use expressions and different operations:

  1. GML Overview

Function List

The following sections all detail the many different functions that are available to you when using GML. They have been split into different groups of associated functions and, where necessary, have been cross referenced with related functions and sections.

Real Numbers And Strings

  1. Maths
    1. - Real Number Functions
    2. - Vector Functions
  2. Date and Time
  3. Strings

Game Play

  1. Game Assets
    1. - Sprites
    2. - Backgrounds
    3. - Sounds
    4. - Fonts
    5. - Paths
    6. - Timelines
    7. - Rooms
  2. Objects and Instances
    1. - Objects
    2. - Instances
  3. Movement and Collisions
    1. - Movement
    2. - Motion Planning
    3. - Collisions
  4. Mouse, Keyboard and Other Controls
    1. - Virtual Keys
    2. - Keyboard Input
    3. - Mouse Input
    4. - Device Input
    5. - GamePad Input
    6. - Immersion Haptics

Drawing And Display

  1. Drawing
    1. - colour And Blending
    2. - Drawing Basic Forms
    3. - Drawing Sprites And Backgrounds
    4. - Drawing Text
    5. - Drawing Primitives
    6. - Drawing 3D
    7. - Drawing Surfaces
  2. Surfaces
  3. The Display, Windows And Views
    1. - The Game Window
    2. - Views
  4. Shaders
    1. - Vertex Formats
    2. - Primitive Building
    3. - Shader Constants

Advanced Functions

  1. Data Structures
    1. - Stacks
    2. - Queues
    3. - Lists
    4. - Maps
    5. - Priority Queues
    6. - Grids
  2. Particles
    1. - Simple Effects
    2. - Particle Systems
    3. - Particle Types
    4. - Particle Emitters
  3. Physics
    1. - The Physics World
    2. - Forces
    3. - Fixtures
    4. - Joints
    5. - Physics Variables
  4. File Handling
    1. - File System Limits
  5. Operating System
  6. Buffers
  7. Networking

Platform Specific

  1. HTML5
  2. Windows8
    1. - Windows 8 Phone
  3. Advertising and Analytics
  4. Social Gaming
    1. - Facebook
    2. - Achievements and Leaderboards
    3. - Local High Scores
  5. In App Purchases
  6. Asynchronous
  7. Push Notifications
  8. Cloud Services
  9. Steam API

Extras

  1. Debugging
  2. Miscellaneous
  3. Obsolete Functions

Back: Contents

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


GML Overview

GameMaker: Studio has its own proprietary programming language called the GameMaker Language (abbreviated to GML).

The GameMaker: Studio programming language, GML, gives you much more flexibility and control than the standard actions that are available through the Drag'n'Drop interface. There are a number of different places where you can use this language to create and control your game:

  • Scripts. A script is a (usually) short snippet of code in GML that you write to create your own functions.

  • Events. You can use code within object events to control the behaviour and interactions of instances of those objects. You can even mix Drag'n'Drop with code!

  • Room Creation Code. Each room can have a special "create event" specific for that room. Here you can add the code you need and it will be run when every time the room is entered.

  • Instance Creation Code As well as the code you insert into the events of an object, you can also add code to individual instances when you place them in the room. This code will run after the create event of the object and is specific to the instance that you add it to. So you can have four instances of the same object, yet each one can be made to have some different properties thanks to this code.

In this section we will describe the basic structure of GML functions and how they are used to create your own programs and generally control your games. Please note that before programing in GameMaker: Studio there are a few conventions that you should follow! First of all, for all your resources (sprites, objects, sounds, etc...) you must use names that start with a letter and only consist of letters, digits and the underscore '_' symbol (for example "spr_Fish" is acceptable but not "spr Fish" or "6fish") otherwise you will not be able to refer to them with any GML functions. Also, make sure all resources have different names (there is a function in the Scripts section of the main IDE that can check this for you), and do not name resources self, other, global, or all because these have special meaning in the language.

Information on the GML language can be found in the following pages:

  1. Code
  2. Variables and Variable Scope
  3. Addressing Variables in Other Instances
  4. Data Types
  5. Arrays
  6. Functions
  7. Assignments
  8. Expressions
  9. Accessors
  10. The "If" Statement
  11. The "Repeat" Statement
  12. The "While" Statement
  13. The "Do" Statement
  14. The "For" Statement
  15. The "Switch" Statement
  16. The "Break" Statement
  17. The "Continue" Statement
  18. The "Exit" Statement
  19. The "With" Construction
  20. Scripts
  21. Comments in Code
  22. Evaluation Order

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Code

Here you can find out how a basic code block is structured using GML.

A code block consists of a set of instructions, called statements, that are then interpreted by GameMaker: Studio and used to make something happen within your game. That "something" can be as simple as adding 2 and 2 to get 4, or as complex as making an enemy run away when their health gets below a certain value. The actual structure of the program can vary greatly, depending on the functions it uses, but broken down to basics it just looks like this:

<statement>;
<statement>;
...

Statements should be separated with a ';' symbol to prevent errors with variable declarations and to keep your code clean and tidy, and can consist of variable declarations, expressions and calls to specific functions or scripts. Here is a more visual representation of how a code block can look, this time created as a script in the GameMaker: Studio Script Editor:

There are a number of different types of statements and functions, which are discussed at length in subsequent sections of the manual.

Back: GML Overview
Next: Variables and Variable Scope

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Assignments

This section explains the various assignments available.

An assignment simply stores a value in a variable and has the form:

<variable> = <expression>;

An expression can be a simple value but can also be more complicated, so, rather than assigning a value to a variable, one can also add a value to the current value of the variable using +=, for example:

a = 100; // Assigning a simple value
b = 200;
c = 300;
a += b; // Assigning with operation
a = b + c; // Assigning with expression

Similarly, you can subtract using -=, multiply using *=, divide using /=, or use bitwise operators using |=, &=, or ^=. You can also add or subtract one from a value using ++, --. For further information see the section on Expressions.

Note that you cannot do the following (or any variation):

var a, b, c;
a = b = c = 4;

And instead it should be done as:

a = 4;
b = 4;
c = 4;

Back: GML Overview
Next: Expressions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Expressions

This section deals with the different mathematical expressions.

Expressions can be real numbers (e.g. 3.4), hexadecimal numbers starting with a $ sign (e.g. $00FFAA), strings between single or double quotes (e.g. 'hello' or "hello") or more complicated expressions. For expressions, the following operators exist (in order of priority):

Assigning

= - Used to assign a value to a variable. Note that this can also be used for comparing variables in GameMaker: Studio and you may see this in examples and other peoples codes. However, this is a legacy from old GameMaker versions and you should use the == operators for comparing and = for assigning, as shown in these examples:

a = 12;
speed = 5;
val = (old_val + 5);

Combining

&&, ||, ^^ (and, or and xor) - Combine Boolean values to give either true or false. If any of the following examples resolves to true then the code would be run:

if (a == b && c == d) {do something...}// and
if (a == b || c ==d) {do something...}// or
if (a == b ^^ c == d) {do something...} // xor

Comparing

<, <=, ==, !=, >, >= - These are comparisons and can only give a true or false result (where true can also be interpreted as 1, and false as 0). Examples of use:

if (a < b) {do something...}
if (a != b) {do something...}

Bitwise

|, &, ^, <<, >>: You can perform bitwise operations with these, where | = bitwise or, & = bitwise and, ^ = bitwise xor, << = shift left, >> = shift right. Examples of use:

x = (x & $ffffffe0) + 32;
if (y ^ $1f) > 0 {do something...};

Arithmetical

+, -, *, / - Add, subtract, multiply and divide. Examples of use:

c = a * b;
str = a + "world";

Increment/Decrement

++, -- - Add or subtract one from a value. It is worth noting that placing this before or after the value to be added to or subtracted from will have slightly different results. For example:

  • ++a will increment the variable and return the incremented value.
  • a++ will increment the variable but return the value before it was incremented.

Therefore, if you have something like this:

var a = 1;
show_debug_message(string(a++));
show_debug_message(string(++a));

The debug output would be 1 and 3. Here are some examples of use:

for (var i = 0; i < 10; i++;) {do something...};
if hit == true score--;

NOTE: On the YoYo Compiler target platforms (those marked (YYC)), these expressions are evaluated from left to right, while on all other target platforms they are evaluated from right to left, meaning that this:

val = max(num, ++num, num++);

will give different results depending on the platform.

Division and Modulo

div, mod (%) - Division and modulo, where div gives you the amount a value can be divided into producing only an integer quotient, while mod gives you only the remainder of a division. Examples of use:

secs = time mod 60;
time_str = string(time div 60);

Unary

Also, the following unary operators exist:

  • ! (not): not, turns true into false and false into true
  • -: negates the next value
  • ~: negates the next value bitwise

Summary

As values in all expressions you can use numbers, variables, or functions that return a value, and sub-expressions can be placed between brackets too. All operators work for real values, but comparisons also work for strings and + concatenates strings.

When doing multiple operations in a single expression, it is very important that you use brackets () to separate out the order of operation, as different platforms may perform them differently if nor explicitly stated in this way. For example, consider the following code:

a = b == c || d;

The different target compilers will perform the operations in different orders since they are not explicitly shown, giving rise to "odd" results that you may not expect when you play your game. to avoid this, use the () to separate out the parts, like this:

a = (b == c || d); //better
a = ((b == c) || d); //best

Here are some final examples of the various different expressions:

{
x = 23;
colour = $FFAA00;
str = 'hello world';
y += 5;
x *= y;
x = y << 2;
x = 23 * ((2 + 4) / sin(y));
str = 'hello' + " world";
b = (x < 5) && !(x==2 || x==4);
}

Accessors

There are also expression "short-cuts" called accessors for use with certain Data Structures, which enable you to add, or replace data within these formats quickly and easily and without the use of any function calls. For full details, please see the following page:

  1. Accessors

Back: GML Overview
Next: The "If" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Addressing Variables in Other Instances

Here you can find various methods for addressing variables in other Instances.

In the sections dedicated to variables you found out how to create and create and use variables within a single instance, or on a global scope, but what happens if you want to one instance to access a variable in another, different one? There are many cases when you may want to do this, for example in a collision with a bullet object, you may want to find out how much damage the bullet does by accessing a variable in the bullet, or you might want to stop the motion of all the balls in a puzzle , or you might want to move the main character to a particular position, or any number of other situations you typically come across in any game. Thankfully the GameMaker Language comes equipped with mechanisms to achieve this.

One of the most common methods for accessing or changing a variable in another instance is to use its object name as an identifier and then use a point "." to tell GameMaker that the variable used after is to be assigned or changed in that object. In practice it would look like this:

obj_ball.speed = 0;

With the above code you are setting the speed of an instance of "obj_ball". However if you have more than one instance of the given object in the room, then it will apply to ALL of them equally - unless you are using one of the JS targets or HTML5, in which case it will affect only one, but you have no way of knowing which one it will affect - so if you need to access all instances of an object, you should be using with, as that is 100% cross platform compatible. In general, this format should only be used when you have a single instance of the object in the room, or (as you will see in the next part) when you have a specific instance ID.

You can also access a single instance of an object when there are multiple instances within the room using the instance id to tell GameMaker: Studio exactly which instance we wish to address. The instance id is the unique identifying number that is given to each and every instance created in your game. When you put instances in a room in the room editor, this instance id is shown at the bottom of the screen when you hover the mouse cursor over the instance, but even if you create an instance through code it still has its unique id number. These numbers are always larger than or equal to 100000, and such a number can also be used as the left-hand side of the point.

Note: The dot will get interpreted as the decimal point in a real number normally, so, to avoid this, put brackets around it!

The following code is an example of how this should be written:

(100012).speed = 0;

Note that you cannot use the special keyword "all" with this method to target all instances, but you can use the keywords "other" and "self" without issues. You can also use variables, as long as the variable in question has stored a valid instance id. The following examples illustrate this...

Using a variable to set an instance value:

var inst = instance_position(mouse_x, mouse_y, all);
if instance_exists(inst)
   {
inst.speed = 0;
}

Note that the above code has an instance_exists() call in the code block. This is because using the point method to access or change another instances value will give an error and crash the game if the instance does not exist. Therefore if there is the possibility that the instance could be destroyed, deactivated, or otherwise removed from the room while using this method, you should always check before hand using the instance_exists() function or the instance_number() function.

These are all perfectly valid ways of reading, changing and setting variables in other instances, and work because the point is actually an operator. It takes a value as left operand and a variable (address) as the right operand, and returns the address of this particular variable in the indicated object or instance. All the object names, constants, IDs etc... simply represent values and these can be dealt with like any other value.

Back: GML Overview
Next: Keywords

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Arrays

This section deals with arrays, special variables that can hold more than one value.

Arrays may seem confusing at first, but they can be extremely useful and are an essential part of making games. Why? Well, here are just a few things that would be impossible without arrays -

  • Menus. An array or two can make it much easier to create a good menu system.
  • RPGs. Arrays are essential for making RPGs, because instead of having a jumble of variables, you just have a few lines, which you can refer back to at any time.
  • Card Games. Good for keeping track of cards and hands and can even be shuffled!
  • High scores and other statistics. Much easier to keep track of one array than multiple variables.

That's just the tip of the iceberg as arrays are one of the most fundamental and useful programming tools you can use, and you'd be surprised at the applications they can have! Let's find out a bit more about them then...

1D Arrays

Okay, we can use an array for those things mentioned above, but what is an array? What does it look like? Well, something like this...

array[0] = 1.25;

This is a 1D (one dimensional) array which we are now going to break down the parts of to see what it means:

array

This is the array's name. Just like any other variable, it can be anything you want from simply "a" to "mymumscow".

[0]

This is the position within the array that we are checking or changing. You see, an array is basically a container with a number of spaces to store values, and each position in the container has a specific number to identify it, which is what we put in the []. It's worth noting that an array always starts at 0 and can never be negative! Now let's expand our array to include different positions...

array[2] = 0;
array[1] = 0;
array[0] = 0;

Our array now contains three positions (0, 1 and 2) and we have initialized our array to 0. What does that mean? Well, an array has to be initialized before we can use it or GameMaker: Studio will give us an error. Initializing an array just means that we give each position of the array an initial value in preparation for it to be used elsewhere in the object or code. This is important to remember as it means that you have to do a certain amount of planning before using arrays, but it is easy enough to initialize one using a repeat loop like this...

var i;
i = 9;
repeat(10)
{
array[i] = 0;
i -= 1;
}

This simple code will initialize a ten position array (0-9) to 0, in that each position in the array contains the value 0. You will notice that the array has been initialised backwards, with the last value being defined first. This is not strictly necessary but is the optimal way to do it as it will reserve a space in memory that is the exact size of the array, whereas if you initialize an array from 0 upwards, the memory has to be re-allocated for every additional value added. The speed difference is negligible for smaller arrays, but larger ones should be optimised as much as possible in this way.

But what if we want to initialize the array with different values for each position? Well for that we have to manually type each and every position ourselves, but there is a nice trick to help us keep track of things there too!

count = 3;
array[count] = "you?"
count -= 1;
array[count] = "are "
count -= 1;
array[count] = "How "
count -= 1;
array[count] = "Hello!"
count -= 1;

As you can see, we haven't used any numbers in the actual array, rather a variable to count down through the values. This has two benefits - One, we don't have to worry about typos or errors when writing out the array positions, and two, we have in the variable "count" the number of positions that the array contains, which can then be used elsewhere in the object. Very useful!

With that done how do we use an array for practical things? Exactly the same as we would use a normal variable, as shown by the following examples:

total = array[0] + array[5]; //Add two array values together

if (array[9]) == 10 //Check an array value
{
//do something
}

draw_text(32, 32, array[3]); //draw an array value

Since arrays are numbered consecutively, this means you can loop through them to perform extra actions too, like we did to initialize it:

var total = 0;
for (var i = 0; i < 10; i++;)
{
total += array[i];
draw_text(32, 32 + (i * 32), array[i]);
}
draw_text(32, 32 + (i * 32), total);

The above code will add up all the values in our array, draw each of them and draw the total value at the end.

2D Arrays

Now that we know what a normal array looks like, let's look at a 2D (two dimensional) array.

array[0, 0] = 5;

As before, each number points to a position within the array, only this time each position has an "a" and "b" coordinate. Think of it as an extra dimension to our container, as it now has height and width whereas the 1D array only has height. Here is an extended example:

array[1, 2] = 1;
array[1, 1] = "hello";
array[1, 0] = 55.5;
array[0, 2] = sprite_index;
array[0, 1] = "world";
array[0, 0] = -67.89;

A 2D array needs to be initialised before use, the same as a 1D array, and can hold real numbers, strings and constants, just like any other variable, making them ideal candidates for any game that needs to store large amounts of data in an easily accessible way (remember, you can loop through an array easily). Here is one final example of how this may be used in an actual game... Say you want to spawn four different enemies at four different points in your game depending on a random value. Well, we can use a 2D array to do this and save writing out a load of code.

First we should initialize the array we are going to use in the create event of our "controller" object:

enemy[3, 2] = 448; //y position
enemy[3, 1] = 32; //x position
enemy[3, 0] = obj_Slime; //Object
enemy[2, 2] = 448;
enemy[2, 1] = 608;
enemy[2, 0] = obj_Skeleton;
enemy[1, 2] = 32;
enemy[1, 1] = 608;
enemy[1, 0] = obj_Knight;
enemy[0, 2] = 32;
enemy[0, 1] = 32;
enemy[0, 0] = obj_Ogre;

We now have the objects to spawn instances of and their corresponding x and y spawn coordinates within the room all stored in our array. This can now be used as follows in another event of the controller object (an alarm for example, or a key press event):

var i;
i = irandom(3); //get a random number from 0 to 4
instance_create(enemy[i, 1], enemy[i, 2], enemy[i, 0]); //Use the array to create the object

That short code will now spawn a random enemy in the game room, and it uses far less code than an "if / then / else" structure or even a "switch", and as the array is initialized all together in the create event it is MUCH easier to edit and change any of those values as they are not hard-coded into the rest of the object codes. It is also worth noting that the length of each 2D array can be different, so you can have an array with a height of 2, but entry 0 could be 2 in length, entry 1 could be 4 in length and entry 2 could be 3 in length:

array[0, 0] = 1;
array[0, 1] = 2;
array[1, 0] = "one";
array[1, 1] = "two";
array[1, 2] = "three";
array[1, 3] = "four";
array[2, 0] = "1";
array[2, 1] = "2";
array[2, 2] = "3";

Advanced Array Functionality

Just like normal variables, you can pass arrays through to scripts to be used and then returned to the instance that called the script. To do this, you simply have to specify the array variable (no need for each of the individual entries, nor the [] brackets) and the array will be passed by reference into the script. However, should you change any of the array values, the array will be copied into a temporary array just for the script. Note the use of the word temporary here! You are not actually passing the array itself into the script (as you would a variable), but instead you are requesting that the script create a copy of this array, which you will change in the script. This means that you must always return the array from the script if you wish to change any array values.

NOTE: Due to the way that this works internally, passing arrays to scripts may affect performance, especially if the array is very large. So use this functionality with care!

As an example, consider the following code. First we create the array we want to use, and then we pass that array to the script:

for (var i = 9; i > -1; i--;)
{
a[i] = i;
}

scr_Return_Array(a);

The script itself is something simple like:

for (var i = 9; i > -1; i--;)
{
a[i] = i * 100;
}

Now you would expect the final array to hold the values 900, 800, 700, etc... BUT this will not be the case, since we did not return the array from the script, so all we changed was the temporary copy that was created when we passed the array as an argument into the script. To rectify this we should have formatted the code as follows:

for (var i = 9; i > -1; i--;)
{
a[i] = i;
}

a = scr_Return_Array(a);

And the script should now look like this:

for (var i = 9; i > -1; i--;)
{
argument0[i] = i * 100;
}

return argument0;

NOTE: The above is not necessary if you are not changing any of the array values, but rather simply referencing them. Referencing an array will not copy it and be faster to parse.

You can also delete an array simply by "re-assigning" the variable that defines it to a single value. This will free up the memory associated with all the entries and values for that array. For example:

//Create the array
for (var i = 9; i > -1; i--;)
{
a[i] = i;
}
//Delete the array
a = 0;

It is also worth noting that you can use the accessor @ to reference an array from a script and change its values directly, which saves the CPU overhead of having it copied into the script. You can find out more information on accessors and how they work, along with an example for arrays, from the following page:

  1. Accessors

Array Functions

There are a few functions associated with the use of arrays too. These are designed to give you flexibility in your code, and will permit you to create more functional and dynamic arrays when making your games. These functions are:

  1. is_array
  2. array_create
  3. array_copy
  4. array_equals
  5. array_length_1D
  6. array_length_2D
  7. array_height_2D

Back: GML Overview
Next: Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "If" Statement

This section outlines how to use the "if" statement

A simple "if" statement takes this form:

if (<expression>) <statement>

or it can have the slightly more complex "if... else..." form:

if (<expression>) <statement> else <statement>

In this case the expression will be evaluated, and if the (rounded) value is < = 0 (false) the statement after else is executed, otherwise (true) the other statement is executed. It is a good habit to always put curly brackets around the statements in the if", and take a new line in the block for each statement, so the end code will have this form:

if (<expression>)
{
<statement>
...
<statement>
}
else
{
<statement>
}

As a small example, consider the following code which will move the instance towards the position x=200 in the room:

if (x < 200)
{
x += 4;
}
else
{
x -= 4;
}

Back: GML Overview
Next: The "Repeat" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "Repeat" Statement

This section explains how to use "repeat".

A "repeat" statement has the form

repeat (<expression>) <statement>

The statement is repeated the number of times indicated by the rounded value of the expression. For example, the following program creates five balls at random positions.

{
repeat (5) instance_create(random(400), random(400), obj_ball);
}

This can be very useful to avoid typing out the same code multiple times, or for using arrays, or for counting through a number of operations etc... For example:

{
var i, total;
i = 0;
total = 0;
repeat (10)
{
total += array[i];
i += 1
}
draw_text(32, 32, total);
}

Back: GML Overview
Next: The "While" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "While" Statement

This section deals with the "while" statement and its use

A "while" statement has the form

while (<expression>) <statement>

As long as the expression is true, the statement (which can also be a code block) is executed. Be careful with your while loops! You can easily make infinite loops, in which case your game will hang and not react to any user input anymore. Below you can find an example of a typical way to use "while":

{
while (!place_free(x, y))
{
x = random(room_width);
y = random(room_height);
}
}

The above program tries to place the current object at a free position (this is about the same as the action to move an object to a random position).

Back: GML Overview
Next: The "Do" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "Do" Statement

Here you can learn about the "do" statement.

A "do" is really the "do... until" statement as you cannot have one without the other. It has this form:

do <statement> until (<expression>)

The statement (which can also be a code block) is executed until the expression is found true, and the initial statement is always executed at least once. Be careful with your do loops, as you can easily make them loop forever, in which case your game will hang and not react to any user input anymore. Below you can find an example of a typical way to use "do... until":

{
do
{
x = random(room_width);
y = random(room_height);
}
until (place_free(x, y));
}

The above program tries to place the current object at a free position (this is about the same as the action to move an object to a random position).

Back: GML Overview
Next: The "For" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "For" Statement

This section explains the use of "for".

A "for" statement has this form:

for (<statement1> ; <expression> ;<statement2>) <statement3>

This works as follows - First statement1 is executed, then the expression is evaluated and, if it is true, statement 3 is executed. Then statement 2 and then the expression is evaluated again. This loop will continue until the expression is found to be false.

Now, this may sound complicated when written like that, but you should interpret it as:

  • The first statement initializes the for-loop.
  • The expression tests whether the loop should be ended.
  • Statement2 is the "step" statement that goes to the next loop evaluation.

This extremely useful for doing repetitive tasks that would involve multiple lines of code in any other way, and is commonly used as a counter for evaluating arrays, or drawing things. the following code example illustrates a typical use for this type of statement:

{
var i;
for (i = 0; i < 10; i += 1)
{
draw_text(32, 32 + (i * 32), string(i) + ". "+ string(scr[i]));
}
}

The above code initialises a for loop, starting at 0 and counting up until 9, and then uses the loop value of "i" to draw the values stored in an array down the screen. Note how the "for" loop variable "i" is used to not only loop through the array, but to draw a number as well as tell GameMaker: Studio where to draw the values to in the room. This flexibility is one of the main reasons why "for" loops are so important in programming.

Back: GML Overview
Next: The "Switch" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "Switch" Statement

This section deals with the uses of "switch" in GameMaker: Studio.

In a number of situations you want to let your instances complete an action depending on a particular value. You can do this using a number of consecutive "if" statements but when the possible choices gets above two or three it is usually easier to use the "switch" statement. A switch statement has the following form:

switch (<expression>)
{
case <expression1>: <statement1>; ... ; break;
case <expression2>: <statement2>; ... ; break;
...
default: <statement>;
}

This works as follows:

  • First the expression is executed.
  • Next it is compared with the results of the different expressions after each of the case statements.
  • The execution continues after the first case statement with the correct value, until a break statement is encountered.
  • If no case statement has the right value, execution is continued after the default statement (it is not required to have a default statement, in which case no action will be taken).

Note that multiple case statements can be placed for the same statement. Also, the break is not required, and if there is no break statement the execution simply continues with the code for the next case statement. This means that you can create a hierarchy "switch" in which different sections of code are run depending on the input value. here is an example of a typical "switch" from a game:

{
switch (keyboard_key)
{
case vk_left:
case ord("A"):
x -= 4;
break;
case vk_right:
case ord("D"):
x += 4;
break;
case vk_up:
case ord("W"):
y -= 4;
break;
case vk_down:
case ord("S"):
y += 4;
break;
}
}

The above code uses "switch" to check for a keyboard event and then compares that to the cases listed. If it meets any of the required values then the corresponding code is executed. Note how in the code we have used the way that "switch" can check multiple cases and continue if no break is encountered to permit various keys to be used to get the same result. This is just one of the ways that you can permit multiple configurations for movement in your games.

Back: GML Overview
Next: The "Break" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "Break" Statement

This section explains the various uses for the "break" statement.

The "break" is used to end prematurely a for, repeat, while, do... until loop of some kind, or to tell a switch statement to end at that point, or to prematurely end a with function. Below you can see a few examples of how this can be used, and its syntax is simply:

break;

"break" in a for loop:

{
var i;
for (i = 0; i < 10; i += 1)
{
if array[i] = 234 break;
}
num = i;
}

"break" in a repeat loop:

{
var i, temp;
i = 0;
temp = 0;
repeat (10)
{
temp += array[i];
if temp > max_total break else i += 1;
}
}

"break" in a while loop:

{
var i;
i = 0;
while (!place_free(x, y))
{
x = random(room_width);
y = random(room_height);
if i > 50 break else i+=1;
}
}

"break" when using with:

{
var count = 0;
with (obj_Enemy)
{
count++;
if count > 10 break;
hp = 100;
}
}

Back: GML Overview
Next: The "Continue" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "Continue" Statement

This section covers the "continue" statement.

The continue statement has the form:

continue

If used inside of a statement that forms a loop (repeat, while, do... until or for), it will immediately jump back to the beginning of the loop as if the loop had run through and looped back (if used outside of a loop it acts as an exit statement, exiting the event). It will also do the same when using the with function, where it will cause the code to skip to the next instance and run again.

Below is an example of its use in a "for" loop:

{
var i;
for (i = 0; i < 10; i += 1)
{
if array[i] = "" continue;
array[i] = "";
}
}

The above code will skip back to the beginning of the loop if the array[i] value is already an empty string.

Back: GML Overview
Next: The "Exit" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "Exit" Statement

Here we explain how to use the "exit" statement.

The exit statement has the form:

exit;

"Exit" simply ends the execution of the current script or event. Note the difference here, as if you use exit in a script is will simply exit the script and return to the code that called the script, however if you use this event in a code block from within an object, it will exit the entire event even if there are various separate code blocks after the function has been called. Typically it is used to avoid an instance running a specific block of code in, for example a collision event. The code below gives a simple example of this:

{
if invisible exit;
while (place_meeting(x, y))
{
x -= lengthdir_x(1, direction - 180);
y -= lengthdir_y(1, direction - 180);
}
}

The above code checks a variable and if it resolves to true, then it exists the code block, otherwise it goes ahead and runs the rest of the code.

Note: It does not end the execution of the game. For that you need to use game_end().

Back: GML Overview
Next: The "With" Construction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Functions

This section explains what a function is in GameMaker: Studio

The general definition of a function is something like this: A function has an input and an output, and the output is related somehow to the input. In GameMaker: Studio you use functions as part of the program to make things happen in your game and there are a great number of GML (GameMaker Language) functions available to you, all of which are explained in the Reference section of the manual.

In GML a function has the form of a function name, followed by the input arguments between brackets and separated by commas (if the function has no input arguments then just brackets are used). Here is an outline of the structure of a function:

<function>(<arg0>, <arg1> ,... <arg15>);

Generally there are two types of functions - First of all, there is the huge collection of built-in functions which are used to control all aspects of your game, and, secondly, any scripts you define in your game can also be used as a function (but not always).

Some functions return values and can be used in expressions, while others simply execute commands and you should note that it is impossible to use a function as the left-hand side of an assignment. For example, you cannot write:

instance_nearest(x, y, obj).speed = 0;

as the return value for the expression is a real number and so must be enclosed in brackets to be used in this way (see Addressing Variables In Other Instances for more information), so the above code should actually be written as:

(instance_nearest(x,y,obj)).speed = 0;

Back: GML Overview
Next: Assignments

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Scripts

Scripts are an important part of GML and this section explains their use.

When you create a script, you want to access the arguments passed to it, either when using the script action, or when calling the script as a function from a program (or from another script). These arguments are stored in the built in variables argument0, argument1, ..., etc... up to argument15. So there can be at most 16 arguments passed through to a script when called from code using this method,and if you are using the script D'n'D action then only the first 5 arguments can be specified.

When using the argument0...15 variables for a script, you must ensure that the script uses all the supplied arguments. For example if you have a script that takes two arguments and you only supply one then you will get an error for that script. The same goes if you supply more arguments than you require. However you can supply a variable number of arguments to a script using the built in argument array, argument[0 ... max_num], where the "max_num" value is the last argument you are passing in. When passing in arguments as an array of values you can use argument_count to find out how many there are and adapt the script to use only those arguments supplied, and it's worth noting that you are not limited to 16 arguments when using this method of parsing the input arguments.

NOTE: You cannot mix the two types of argument variables when calling a script. You must use either argument0 ... argument15 or argument[0 ... max_num].

Scripts can also return a value, so that they can be used in expressions. For this end you use the return statement:

return <expression>

It should be noted that the execution of the script ends at the return statement, meaning that any code which comes after the return has been called will not be run. Here is a short example script called "scr_sqr" which calculates the square of whatever value is passed to it, and it includes error catching in case the argument that it is passed is not a real number:

{
if !is_real(argument0)
{
return 0;
}
else
{
return (argument0 * argument0);
}
}

To call a script from within a piece of code, just act the same way as when calling functions - that is, write the script name with the argument values in parentheses. So, the above script would be called like this:

if keyboard_check_pressed(vk_enter)
{
val = scr_sqr(amount);
}

It is sometimes necessary for you to know how many arguments that a script has been passed from the code that calls it, and so GameMaker: Studio also provides the following read-only variable for this:

    argument_count

For more information on scripts please see Advanced Use - Scripts.

Back: GML Overview
Next: Comments in Code

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The "With" Construction

This section explains the various uses for "with" in GameMaker: Studio.

As indicated in the section Addressing Variables in Other Instances, it is possible to read and change the value of variables in other instances. But in a number of cases you want to do a lot more than just change a single variable with those other instances. For example, imagine that you want to move all the ball objects in your game 8 pixels. You may think that this is achieved simply by the following piece of code:

obj_ball.y = obj_ball.y + 8;

But this is not correct, as the right side of the assignment gets the value of the y-coordinate of the first ball and adds 8 to it. Next this new value is set as y-coordinate of all balls, so the result is that all balls get the same y-coordinate, and even if you use the following:

obj_ball.y += 8;

it will have exactly the same effect because it is simply an abbreviation of the first statement. So how do we achieve this? For this purpose there exists the with statement in GML. Its global form is:

with (<expression>) <statement>

<Expression> indicates one or more instances, and for this you can use an instance id, the name of an object (which indicates all instances of this object are to run the code block) or one of the special keywords (all, self, other). <Statement> is now executed for each of the indicated instances, as if that instance is the current (self) instance. So, to move all instances of the ball object 8 pixels down, you can type:

with (obj_ball) y += 8;

If you want to execute multiple statements, put curly brackets around them, the same as you would around any other program. So for example, to move all balls to a random position, you can use:

with (obj_ball)
{
x = random(room_width);
y = random(room_height);
}

Note that, within the statement(s), the indicated instance has become the target (self) instance that runs the code block, which means that the statements the original instance (that contains the "with" and the code block) has become the other instance. So for example, to move all balls to the position of the current instance, you can type this:

with (obj_ball)
{
x = other.x;
y = other.y;
}

The with statement is an extremely powerful tool and is useful in many, many circumstances so it is important that you understand fully how it can be used. To help there are a few more examples of use below:

with (instance_create(x, y, obj_Ball))
{
speed = other.speed;
direction = other.direction;
}

The above code will create an instance of obj_Ball and assign it the speed and direction of the instance that runs the whole code block.

with (instance_nearest(x, y, obj_Ball))
{
instance_destroy();
}

The above code will destroy the instance of obj_Ball nearest to the instance running the code.

var inst;
inst = noone;
with (obj_ball)
{
if str > other.str inst = id;
}
if inst != noone target = inst;

The above code is slightly more complex than previous ones due to it using a local variable. This variable is local to the script and not to the instance and so can be used and accessed by all instances that are referenced within the code block. So, in the code we have set it to the special keyword noone and then use the "with" construction to have every instance of obj_Ball check their "str" variable against that of the instance running the code block. If the value of the variable is larger, then they store their unique id in the "inst" local variable, meaning that at the end of the code, only the instance with a value greater than the calling instance (or the keyword noone if none are larger) will be stored in the local variable inst. For more information on local variables see the section Variables And variable Scope.

Back: GML Overview
Next: Scripts

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Comments in Code

This section deals with the ways in which you can comment your codes and scripts.

When working in collaboration with other people, when dealing with a large project, or even just for your own reference and debugging, leaving comments in your codes and scripts is very important. In GameMaker: Studio you have various mechanisms to help you leave notes and comments about code sections and even whole blocks of code that can be seen in the event list of the object that you are currently editing, and in this way you can leave notes to yourself and to your colleagues, or to explain a particularly tricky piece of code, or even just leave a reminder about what something does.

The first thing you can do is leave a short comment using // before the text. For example:

//initialize variables
sr = 10;
hp = 100;

You may also leave multiline comments, to give credit, to omit a complete section of code for debugging, or even to explain the arguments of a script. For that you can use /* ... */ like this:

/*
usage:
diff = angle_difference(angle1,angle2);

angle1 first direction in degrees, real
angle2 second direction in degrees, real

returns: difference of the given angles in degrees, -180 to 180

GMLscripts.com
*/
{
return ((((argument0 - argument1) mod 360) + 540) mod 360) - 180;
}

Finally, when using the code blocks in an object, it can be quite confusing, especially if you have many of them and any given event may end up looking like this: However if the very first line of your code has a comment that is started with /// then that comment will appear as the name of that code block. So, for example, if you have this:

///Check position

Then the code block will now have that as its description, as shown in the following image:

Back: GML Overview
Next: Evaluation Order

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Evaluation Order

This section deals with the evaluation order of functions and expressions.

When programming your game using GML you should be aware that function call arguments are not guaranteed an evaluation order. What this means is that the order in which you place functions in your code will change from platform to platform, so you should code them in an explicit manner. This is due to optimisation differences between the different target platforms, for example on the Windows target functions may be evaluated from right to left, but on the HTML5 target, they may be evaluated from left to right. So to avoid any issues you are best not to call multiple functions in the arguments of a function call as you may well be building in a reliance on the order of evaluation.

To see an example of what this means, consider the following code which is calling several functions and using them as arguments to a script:

buffer_seek(buff, buffer_seek_start, 0);
scr_buffer_get_info(buffer_read(buff, buffer_s8), buffer_read(buff, buffer_s16),buffer_read(buff, buffer_s16));

Now, the problem here is that on some platforms, the last buffer_read will be called first, and so all the arguments of the script will be wrong as the data is being read from the buffer in "reverse" order as you would perceive it. This has the knock-on effect here of affecting all further values for the buffer_read function so all the arguments being passed to this script will be wrong!

To get around this you should explicitly call the functions in the required order and store the returned values in variables, like this:

var val[0] = buffer_read(buff, buffer_s8);
var val[1] = buffer_read(buff, buffer_s16);
var val[2] = buffer_read(buff, buffer_s16);
scr_buffer_get_info(val[0], val[1], val[2]);

While it may seem a more verbose method, it keeps everything clear and avoids any possible problems with evaluation order.

You should also take care when using expressions too, as the order in which they are evaluated in will change depending on which target you are compiling to. So, when using expressions in your code, ensure you use brackets () to properly control the order of operations. This is very important to ensure the correct behaviour of your games across all the target platforms games and is essential for JavaScript platforms. For example, consider the following code:

a = b == c || d;

The different target compilers will perform the operations in different orders since they are not explicitly shown, giving rise to "odd" results that you may not expect when you play your game. To avoid this, use the () to separate out the parts, like this:

a = (b == c || d); //better
a = ((b == c) || d); //best

Back: GML Overview
Next: A Program

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Accessors

This section shows how to use accessors to get and set data within Data Structures and Buffers.

The GameMaker Language (GML) also permits you to access certain Data Structures through the use of logical expressions called accessors. This is done in a similar way as you would for working with arrays only we use an identifier symbol before the first argument to tell GameMaker: Studio that you are working on a (previously created) data structure.

Data Structures

You can add, replace and get values and keys for the following data structure types: ds_maps, ds_lists, and ds_grids. Each one has been given its own symbol and method for accessing, changing or setting values, as shown below.

ds_list [| ]

The syntax for lists is:

list_index[| index]

So when you have used ds_list_create() to create your list, you would use the list index (that you have stored in a variable) to reference it, with the "index" value being the position in the list to set or add. For example, the following code creates a list and then adds 10 entries, setting each entry to random number from 0 to 9:

ds = ds_list_create();
var index = 0;
repeat(10)
{
ds[| index++] = irandom(9);
}

Once you have created your list structure and filled it with data, to get values from the list you would have something like:

value = ds[| 5];

The above will get the value from position 5 (the sixth index, since lists start at 0) and store it in a variable. Note that if you are using an expression to add a reference to an index that already has a value, the previous value will be replaced rather than have a further index added to the list. To add further entries you would need to know the ds_list size and add them to the end. It is also worth noting that you can set a list index that is greater than the size of the list being referenced, and this will set that value, expanding the list at the same time, as well as initialise all the positions in the list up to the given index as 0.

ds_map [? ]

The syntax for maps is:

map_index[? key]

After creating your map with ds_map_create(), you would use the map index that you have stored in a variable to reference it, with the "key" value being the map key to set or get. For example, the following code creates a map and then adds a few entries to it using this syntax:

ds = ds_map_create();
ds[? "Name"] = "Hamish";
ds[? "Company"] = "MacSeweeny Games";
ds[? "Game"] = "Catch The Haggis";

Once you have created your map structure and filled it with data, to get values from a specific map key you would have something like:

value = ds[? "Name"];

The above will get the value from the key "Name" and store it in a variable. Note that if the map already contains the same key value as you are trying to add, it will not create a duplicate key with the new value, but rather the previous value will be replaced.

ds_grid [# ]

The syntax for grids is:

grid_index[# xpos, ypos]

After creating your grid with the ds_grid_create() function, you would use the grid index that you have stored in a variable to reference it, with the "xpos" and "ypos" being the position within the grid to get or set a value. For example, the following code creates a grid, clears it to 0, then and then adds a few entries to it:

ds = ds_grid_create();
ds_grid_clear(ds, 0);
var gw = ds_grid_width(ds) - 1;
var gh = ds_grid_height(ds) - 1;
repeat(10)
{
var xx = irandom(gw);
var yy = irandom(gh);
if ds[# xx, yy] == 0 ds[# xx, yy] = 1;
}

Once you have created your grid structure and filled it with data, to get values from a specific grid position you would have something like:

value = ds[# mouse_x div 16, mouse_y div 16];

The above will get the value from the given ds_grid based on the mouse position (divided by the "cell" width in the room to get the correct location).

Arrays

Arrays also have their own accessors which works in a similar way as those listed above for data structures. however array accessors have an interesting property and that is to permit you to modify an array from a script without having to copy it. When you pass an array into a script, it is passed by reference, meaning that the array itself isn't being copied into the script but rather it is simply being referenced to get the data. Normally if you then need to change the array, it would be copied to the script and then you would need to pass back the copied array for the original array to be updated. This can have costly processing overheads, and you can use the accessor instead, as that will change the original array directly without the need for it to be copied. You can see how this works in the examples below.

The syntax for arrays is:

array[@ xpos]
array[@ xpos, ypos]

After you have created your array in an instance, you can then pass it to a script by reference and use the accessor @ to change it directly. For example you would create the array and call the script like this:

array[99] = 0;
scr_Array_Populate(array);

The script itself would have something like this:

var a = argument0;
var i = 0;
repeat(25)
{
i = irandom(99);
while (a[i] != 0)
{
i = irandom(99);
}
a[@ i] = 100;
}

All this script is doing is selecting 25 random positions in the array and setting the value of the chosen array position to 100.

Back: Expressions
Next: The "If" Statement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


argument_count

Returns the number of arguments passed to a script.

Syntax:

argument_count;

Returns: Real

Description

This read-only variable returns the number of "arguments" that are passed through to a script. Normally used in conjunction with an argument array (argument[0...15]) to permit varying input arguments for a given script.

Example:

var i, arg;
for (i = 0; i < 5; i += 1;)
{
if argument_count > i
{
arg[i] = argument[i]
}
else
{
arg[i] = -1;
}
}

The above code uses the argument_count variable to initialize variables, and is an example of how to permit a script to accept a variable number of arguments.

Back: Scripts

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


array_copy

Copy an array (or part of it) into another array.

Syntax:

array_copy(dest, dest_index, src, src_index, length);

Argument | Description
dest | The ID of the array to copy to.
dest_index | The index within the array to copy to.
src | The ID of the array to copy from.
src_index | The index with the array to start copying from.
length | The length (number of array indices) to copy.

Returns: N/A

Description

With this function you can copy all or part of one array into another array at any position. You need to supply both the source and the destination arrays (both need to have been created previously), as well as a position within the source array to copy from and a position within the destination array to copy to. Finally you need to specify the length of the array (or the length of the part that you want) to copy. If the data being copied exceeds the length of the destination array, the array will be extended to accept the data.

Example:

if !array_equals(inventory_array, item_array)
{
var len = array_length_1d(inventory_array);
array_copy(item_array, 0, inventory_array, 0, len);
}

The above code will check two arrays to see if they hold equivalent values, and if they do not then the code will copy the entire contents of the array "inventory_array" to the array "item_array".

Back: Arrays
Next: array_equals

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


array_create

Create an array of a given size (and populate it with a default value).

Syntax:

array_create(size, [value]);

Argument | Description
size | The size of the array to create.

Returns: Array (Handle)

Description

With this function you can create an array of a given size. You tell the function the length of the array to create, and it will return the "handle" for the array which you can then assign to a variable. Arrays created in this way will have each entry initialised to 0.

Example:

instance_array = array_create(100);

The above code will create a new array of 100 entries and assign it to the variable "instance_array".

Back: Arrays
Next: array_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


array_equals

Check to see if two arrays are equal (equivalent or the same).

Syntax:

array_equals(var1, var2);

Argument | Description
var1 | The index of the first array.
var2 | The index of the second array.

Returns: Boolean

Description

With this function you can check to see if two arrays are equal (equivalent or the same). You give the two arrays to check, and the function will return true if they are equal (either equivalent or the same) or false if they are not. Note that this is not the same as checking if two arrays are the same using ==, which will not check to see if the two arrays hold equivalent values, but only to see if the arrays are referencing the same initial array. For example:

var a = [1,2,3,4];
var b = [1,2,3,4];
if (a == b)
{
show_debug_message( "This will never fire, as a and be do not reference the SAME array" );
}
if (array_equals(a, b))
{
show_debug_message( "This will fire now" );
}

Example:

if !array_equals(inventory_array, item_array)
{
var len = array_length_1d(inventory_array);
array_copy(item_array, 0, inventory_array, 0, len);
}

The above code will check two arrays to see if they hold equivalent values, and if they do not then the code will copy the entire contents of the array "inventory_array" to the array "item_array".

Back: Arrays
Next: array_length_1d

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


array_height_2d

Returns the height of a 2D array.

Syntax:

array_height_2d(array);

Argument | Description
array | The array to check.

Returns: Real

Description

With this function you can get the height (number of entries) of a the first dimension of a 2D array. You supply the array to check and the output from the function tells you how many initial entries it contains. You can get the number of entries for the second dimension of the array using the function array_length_2d.

Example:

for (var i = array_height_2d(a); i > -1; i--;)
{
for (var j = array_length_2d(a, i); j > -1; i--;)
{
a[i, j] = -1;
}
}

The above code will loop through a 2D array and set each entry to -1.

Back: Arrays
Next: is_array

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


array_length_1d

Returns the length of the first dimension of an array.

Syntax:

array_length_1d(array);

Argument | Description
array | The array to check.

Returns: Real

Description

With this function you can get the length (number of entries) of a 1D array. For 2D arrays you should be using the array_height_2d and array_length_2d functions.

WARNING!: If the array has over 32,000 entries this function will return an erroneous value and should not be used.

Example:

for (var i = array_length_1d(a) - 1; i > -1; i--;)
{
a[i] = -1;
}

The above code will loop through an array and set each entry to -1.

Back: Arrays
Next: array_length_2d

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


array_length_2d

Returns the length of a given dimension of a 2D array.

Syntax:

array_length_2d(array, n);

Argument | Description
array | The array to check.
n | The entry of the array to get the length of.

Returns: Real

Description

With this function you can get the length (number of entries) of a the second dimension of an array. You supply the entry number for the first dimension and the function will return the number of second dimension entries that the array has (to find the length of the first dimension use the function array_height_2D). The function will return 0 if the variable given is not an array or 1 if the variable is a 1D array (as there is still 1 row).

Example:

for (var i = array_height_2d(a) - 1; i > -1; i--;)
{
for (var j = array_length_2d(a, i) - 1; j > -1; j--;)
{
a[i, j] = -1;
}
}

The above code will loop through a 2D array and set each entry to -1.

Back: Arrays
Next: array_height_2d

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Data Types

This section covers the various different data types recognised by GameMaker: Studio.

In previous sections we have covered variables and their scoping rules but little has been said about the different data types that a variable can store. Therefore this chapter explains the different types and what they can be used for.

Before continuing, let's just briefly explain what we mean by "data types". When you create a variable it can be used to hold information, and when you call a GML function, it can also return information. However this information can come in various "flavours", like it can (for example) be a real number or it can be a string. These different types of values being used are called data types and when using GML they can be any of the following:

  • string - A string is a series of characters placed within either ' or " marks. For example "The Quick Brown Fox! 123" is a string.
  • real - A real number is simply a floating point or an integer value.
  • array - An array is a variable that stores values using a sequence of indices.
  • boolean - A boolean value is one that can only ever be true or false.
  • pointer - A pointer is a data type that "points" to an area of memory.
  • enum - An enum is a collection of constants held under a custom variable type.
  • undefined - This is a special value that is returned when the value you are checking cannot be found.

Strings

A string is simply any text that has been placed in quotation marks (either '...' or "..."). You can perform certain operations on strings, like add two strings together to create a longer string (concatenation) and you can also change the string properties and even extract real numbers from it. For more information on the string functions see: Reference - Strings.

Real Numbers

real numbers are any value that is not a string, nor any of the other possible data types. So, 124, 45639.566546456, 0, -45.5 etc... are all examples of real numbers. All real numbers are stored as 32bit floating point values (even integer values), so you may experience slight rounding errors when dealing with these. For more information on this and other number related functions, please see: Reference - Real Numbers.

Note that created variables in GameMaker are all stored as double-precision floating point numbers, but you can use other formats when dealing with extensions. These can be passed into GameMaker: Studio from an extension and then checked using the appropriate is_ function, listed at the bottom of this page.

Arrays

An array is a special data type that can be used to hold multiple values. You assign the array to a variable, and then "fill in" different indices of the array with values. This array can then be passed through to scripts and functions on a pass-by-reference basis, however should you modify the passed array, it will then become a copy of the original array and so will need to be returned back to the original variable for the array to be updated. For more information on arrays, please see: GML Overview - Arrays.

Booleans

A boolean is simply a value that can either be true or false. Note that currently GameMaker: Studio does not support "true" boolean values, and actually accepts any real number below 0.5 as a false value, and any real number equal to (or greater than) 0.5 as being true. This does not mean however that you should be checking 1 and 0 (or any other real number) for true and false, as you are also provided with the constants true and false which should always be used in your code to prevent any issues should real boolean data types be added in a future update.

Pointers

A pointer is a data type that "points" to a memory location. You cannot do operations on a pointer and it is used for some very specific functions, like getting a texture or buffer address from memory for another function. For examples of functions that return a pointer you can see buffer_get_address or sprite_get_texture.

There is also a function to check if a value is a pointer (see "Checking Data Types", below) and a function to convert a value into a pointer:

  1. ptr

You may also use (and get returned) the following built in constants when using pointers:

Constant | Description
pointer_null | This constant indicates that the pointer is not pointing to anything meaningful (the same as NULL in C++ or null in C#)
pointer_invalid | This constant simply means that the value is not a valid pointer

Enums

An enum is an "enumerator", and it essentially permits you to create your own limited data type with a list of constant values. Enums are global scope variables (this is implicit, and they require no "global" suffix or globalvar declaration) and they have the following structure:

enum <variable>{<constant> [= <value>]}

In the following example, we create an enum for the colours of the rainbow and assign it various constants and default values:

enum rainbowcolors {
red,
orange,
yellow,
green,
blue,
indigo,
violet
}

The enum entries can only be real numbers or expressions with previous enums, and by default are numbered from 0 upwards, so our example given above would default to red = 0, orange = 1, yellow = 2, etc... You can also assign values to the enum variables at the time of creation, using real numbers or expressions:

enum rainbowcolors {
red = 5,
orange = 5 * 2,
yellow = 15,
green = 20,
blue = 25,
indigo = 30,
violet = 35 * enum_test.entry
}

Notice in the above example we use another enum to create an expression for "violet". This only works if the enum being referenced was created before the enum that is using it in an expression, but it will not work for variables or functions, since the enum value must be able to be evaluated as a constant on compile.

To later access the value within a given enum type, you can use the point "." method, like this:

var value = rainbowcolours.green;

Note that you cannot modify the values for any enum constant after it has been created.

Undefined

An undefined value (also known as a "null" value") is one where an expression doesn't have a correct value, although it is syntactically correct, and so must return something. For example, say you have a ds_map and use the function ds_map_find_value(). Now, what happens when the map does not have the value being looked for? Well, since the function is correctly formatted, and the issue is that the no such value exists, then it would return the constant undefined, and you can check for this constant as you would check for true or any other value.

Checking Data Types

GameMaker: Studio permits you to check the data type of a given variable using the following functions:

  1. is_string
  2. is_real
  3. is_bool
  4. is_array
  5. is_ptr
  6. is_int32
  7. is_int64
  8. is_vec3
  9. is_vec4
  10. is_matrix
  11. is_undefined
  12. typeof

Back: GML Overview
Next: Arrays

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_array

Checks a variable to see if it is an array or not.

Syntax:

is_array(variable);

Argument | Description
variable | The variable to check.

Returns: Boolean

Description

This function can be used to check and see if a variable holds an array (it will return true) or not (in which case it will return false).

Example:

if is_array(a)
{
a = 0;
}

The above code checks a variable to see if it is an array, and if the function returns true, the array is deleted.

Back: Arrays
Next: array_length_1D

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_bool

Returns whether the given argument is a boolean value.

Syntax:

is_bool(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable is a boolean (true ior false) or not. In some cases you want to check and see if a variable in GameMaker Studio 2 holds a boolean value, and that's when you would use this function.

Example:

if is_bool(val)
{
global.Sound = val;
}
else
   {
global.Sound = true;
}

The above code checks the variable "val" to see if it is a real number and if it is it then uses it to set a global variable.

Back: Data Types
Next: is_array

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_int32

Returns whether the given argument is an int32.

Syntax:

is_int32(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable is a 32bit integer or not. In some cases you want to check and see what data type a variable holds in GameMaker: Studio and that's when you would use this function. It returns true or false depending on whether the value is an int 32 or not. For further information on data types see here.

Example:

if !is_int32(val)
{
show_debug_message("Not a 32 bit integer!");
}

The above code checks the variable "val" to see if it contains an int32 and if it is not then it shows a message in the debug console.

Back: Data Types
Next: is_int64

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_int64

Returns whether the given argument is an int64.

Syntax:

is_int64(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable is a 64bit integer or not. In some cases you want to check and see what data type a variable holds in GameMaker: Studio and that's when you would use this function. It returns true or false depending on whether the value is an int64 or not. For further information on data types see here.

Example:

if !is_int64(val)
{
show_debug_message("Not a 64bit integer!");
}

The above code checks the variable "val" to see if it contains an int64 and if it is not then it shows a message in the debug console.

Back: Data Types
Next: is_vec3

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_matrix

Returns whether the given argument is a matrix.

Syntax:

is_matrix(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable refers to a matrix or not. In some cases you want to check and see what data type a variable holds in GameMaker: Studio and that's when you would use this function. It returns true or false depending on whether the value is a matrix or not. For further information on data types see here, and to find out more about the matrix functions see: 3D Transforms.

Example:

if !is_matrix(val)
{
show_debug_message("Not a valid matrix!");
}

The above code checks the variable "val" to see if it contains a matrix and if it is not then it shows a message in the debug console.

Back: Data Types
Next: is_undefined

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_ptr

Returns whether the given argument is a pointer.

Syntax:

is_ptr(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable is a pointer or not. In some cases you want to check and see what data type a variable holds in GameMaker: Studio and that's when you would use this function. It returns true or false depending on whether the value is a pointer or not. For further information on data types see here.

Example:

if !is_ptr(val)
{
show_debug_message("Not a valid texture!");
}

The above code checks the variable "val" to see if it contains a pointer and if it is not then it shows a message in the debug console.

Back: Data Types
Next: is_undefined

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_real

Returns whether the given argument is a real (as opposed to a string).

Syntax:

is_real(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable is a real number or not. In some cases you want to check and see if a variable in GameMaker: Studio holds a real number, and that's when you would use this function. It does not return the real number but rather true or false, so a value of, for example, "fish" for n will return false, but a value of 200 for n will return true.

Example:

if is_real(val)
{
score += val;
}

The above code checks the variable "val" to see if it is a real number and if it is it then adds it to the score.

Back: Data Types
Next: is_bool

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_string

Returns whether the given argument is a string (as opposed to a real).

Syntax:

is_string(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable is a string number or not. In some cases you want to check and see if a variable in GameMaker: Studio holds a string and not a real and that's when you would use this function. It does not return the string but rather true or false, so a value of, for example, "fish" for n will return true, but a value of 200 for n will return false.

Example:

if is_string(val)
{
name = "Player: " + val;
}

The above code checks the variable "val" to see if it contains a string and if it does it adds it into another string which is then assigned to the variable "name".

Back: Strings
Next: string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_undefined

Returns whether the given argument is undefined or not.

Syntax:

is_undefined(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable is defined or not. In some cases you want to check and see what data type a variable holds in GameMaker: Studio and that's when you would use this function. It returns true or false depending on whether the value is defined or not. For further information on data types see here.

Example:

var val = ds_map_find_value(map, 13);
if is_undefined(val)
{
show_debug_message("Map entry does not exist!");
}

The above code checks the variable "val" to see if it is undefined or not and shows a debug message if it is.

Back: Data Types
Next: is_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_vec3

Returns whether the given argument is a vec3.

Syntax:

is_vec3(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable is a 3 value vector or not. In some cases you want to check and see what data type a variable holds in GameMaker Studio 2 and that's when you would use this function. It returns true or false depending on whether the value is an int64 or not. For further information on data types see here.

Example:

if !is_vec3(val)
{
show_debug_message("Not a 3 value vector!");
}

The above code checks the variable "val" to see if it contains a vec3 and if it is not then it shows a message in the debug console.

Back: Data Types
Next: is_vec4

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


is_vec4

Returns whether the given argument is a vec4.

Syntax:

is_vec4(n);

Argument | Description
n | The argument to check.

Returns: Boolean

Description

This function returns whether a given variable is a 4 value vector or not. In some cases you want to check and see what data type a variable holds in GameMaker Studio 2 and that's when you would use this function. It returns true or false depending on whether the value is an int64 or not. For further information on data types see here.

Example:

if !is_vec4(val)
{
show_debug_message("Not a 4 value vector!");
}

The above code checks the variable "val" to see if it contains a vec4 and if it is not then it shows a message in the debug console.

Back: Data Types
Next: is_matrix

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Keywords

This section deals with the different keywords that can be used in GameMaker: Studio functions.

To make certain things easier in GameMaker: Studio, you can use one of several keywords in your scripts and actions. These keywords are used primarily to identify instances and each one is explained in the text below. Note that all keywords are represented by a negative integer value, so care must be taken when assigning values to variables, as you may get unexpected results later as GameMaker: Studio interprets the value you have used as something else. You should also note that using the values instead of the keywords in your code is not at all recommended and could cause issues later on.

self

Keyword | Description | value
self | The instance which is executing the current block of code. | -1

self can be used to identify the calling instance of the current block of code. It always returns the value of -1 which GameMaker: Studio interprets as the unique ID for the instance. In general you should never need to use this keyword, as you can do the same task more efficiently and appropriately using other keywords or functions, and is maintained for legacy support reasons.

other

F

Keyword | Description | value
other | The other instance involved in a collision event, or the other instance from a with function. | -2

The special keyword other has two different ways that it can be used to reference a specific instance: when used in a with function (explained here) or when used in a collision event, which is what this section is going to explain.

A collision event can only happen between two instances. You can have multiple collisions between multiple instances, but they are all resolved by GameMaker: Studio on a 1-on-1 basis, with the instance that has the collision event and the "other" instance that is involved. Imagine you have a player object, multiple enemy objects and multiple bullet objects that the enemy can fire at you. You can assign each enemy a single bullet instance but with a different damage variable randomly assigned to it when created, for example:

var nnn;
nnn = instance_create(x, y, obj_Bullet);
nnn.damage = 5 + irandom(5);
nnn.speed = 8;
nnn.direction = point_direction(x, y, obj_Player.x, obj_Player.y);

See how we set its variables using the point method outlined in the section Addressing Variables? This will give the bullet objects a different damage value. But what about the player object? How will it detect the damage that it has to take? By using other in the collision event:

hp -= other.damage;
if hp <= 0 instance_destroy();

The above code will deduct the amount stored in the other instance in the collisions "damage" variable from the player "hp" variable, then it will check to see if the "hp" is lower than or equal to 0. If it is then it will destroy the player object. Please note that other used in this way only works in the collision event and that the other instance must have the variable being checked or else an error will be thrown. However you can assign values to variables, or even create new ones, using other in the collision event too, like this:

other.mana += 10; //add ten to the other instance "mana" variable
other.hit = true; //set the other instance variable "hit" to true, creating it if the variable doesn't already exist

all

Keyword | Description | value
all | All instances currently active in the room. | -3

This keyword is used to tell GameMaker: Studio that a function is to be applied, or to check, all active instances within a room (deactivated instances will not be checked or accessed). You cannot use all to access or set variables in other instances using the point method (see here), but you can use it when calling with(), for example:

with (all)
{
speed = 0;
}

The above code will set the speed of all instances in the room to 0. You can also use all within functions to target or check all instances in the room for example:

inst = instance_position(mouse_x, mouse_y, all); //Check a point for any active instance in the room

if collision_line(x, y, mouse_x, mouse_y, all, false, true) {} //Check all instances for a collision along a line

mp_grid_add_instances(grid, all, false); //Add all instances in the room into a motion planning grid

all is a very useful keyword and can be used in numerous situations within your code and actions, often cutting down on the amount of code you need to write to achieve a desired effect.

noone

Keyword | Description | value
noone | No instance at all. | -4

It may seem odd, but many times while programming your games will you find the need to check if there are no instances found at a location, or in a collision etc... In those cases you would use this keyword to check for nothing, something like this:

if instance_nearest(x, y, obj_enemy) != noone
{
//do something as there is an enemy instance near
}

In this example, the function instance_nearest() will return either noone or the unique ID of the nearest found instance. Basically, any time that you need to check for an instance, you can expect to get either noone or a unique instance ID returned.

Back: GML Overview
Next: Data Types

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ptr

Attempts to converts a given value into a pointer.

Syntax:

ptr(n);

Argument | Description
n | The value to convert.

Returns: Pointer

Description

This function will attempt to convert a given value into a pointer data type, where the value must be either a real, a string, an int64, an int32, or a ptr. Anything else will cause the game to crash with an error message.

Example:

if !is_ptr(val)
{
ptr(application_surface);
}

The above code checks the variable "val" to see if it contains a pointer and if it does not then one is assigned to it.

Back: Data Types
Next: pointer_null

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ptr

Attempts to converts a given value into a pointer.

Syntax:

ptr(n);

Argument | Description
n | The value to convert.

Returns: Pointer

Description

This function will attempt to convert a given value into a pointer data type, where the value must be either a real, a string, an int64, an int32, or a ptr. Anything else will cause the game to crash with an error message.

Example:

if !is_ptr(val)
{
ptr(application_surface);
}

The above code checks the variable "val" to see if it contains a pointer and if it does not then one is assigned to it.

Back: Data Types

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ptr

Attempts to converts a given value into a pointer.

Syntax:

ptr(n);

Argument | Description
n | The value to convert.

Returns: Pointer

Description

This function will attempt to convert a given value into a pointer data type, where the value must be either a real, a string, an int64, an int32, or a ptr. Anything else will cause the game to crash with an error message.

Example:

if !is_ptr(val)
{
val = ptr(application_surface);
}

The above code checks the variable "val" to see if it contains a pointer and if it does not then one is assigned to it.

Back: Data Types

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


typeof

Returns the type of variable being checked as a string.

Syntax:

typeof(variable);

Argument | Description
variable | The variable to get the type of.

Returns: String

Description

This function returns the data type of any given variable as a string. The possible return values are listed in the table below:

String | Description
number | The variable holds a real (floating point) number
string | The variable holds a string
array | The variable references an array
bool | The variable holds a boolean (true / false)
int32 | The variable holds a 32bit integer
int64 | The variable holds a 64 bit integer
ptr | The variable holds a pointer
undefined | The variable is undefined
null | The variable holds a null value (this should not be seen normally)
vec3 | The variable holds a 3 value vector
vec4 | The variable holds a 4 value vector
unknown | Value is unknown. This should never be seen and signifies that something has gone wrong at the most basic level like a memory overwrite

Example:

data_str = typeof(global.ExtensionInput);

The above code gets the data type held by the given global variable and returns the string to an instance variable.

Back: Data Types
Next: is_string

© Copyright YoYo Games Ltd. 2016 All Rights Reserved


Variables And Variable Scope

Here you can learn about the different types of variables in GameMaker: Studio.

Like any programming language GML uses variables as the basic unit for most programming operations. Variables are used to store information in the devices memory for later (or instant) use, and they are given a name so that you can refer to them in functions and programs. A variable in GML can store either a real number (like 100, 2.456575, -56 etc...) or a string (like "Hello world!").

A variable is something that we use to store a value for use in one or more operations or functions. Think of "pi", for example... it is a real world variable that holds the value 3.14159265(etc...). Why? Well, it's much easier to say to someone "pi" than "three point one four one five nine two six five"! So, naming things make life a lot simpler and it also means that should the value of that variable ever change, we don't have to change the number everywhere as the variable name is still the same. In GML a variable has a name that must start with a letter and can contain only letters, numbers, and the underscore symbol '_' with a maximum length of 64 symbols. So, valid variables are things like fish, foo_bar, num1, and invalid variables would be 6fish, foo bar, or *num. Now, In many programing languages you need to "declare" a variable before you can use it. This basically means that you tell the computer the name you wish to use so that it can assign a place in memory to store whatever value you decide to hold in that variable. With GML, that is not always necessary as it depends on the scope of the variable. There are four main variable categories when you program with GameMaker: Studio and each has its own scope (which is can be considered as its area of operation, or reach). These variables and their scope are outlined below:

  • instance: these are the most common variables and are defined within an instance. These are unique to that instance and can be used in any event and any function within that instance.

  • local: these variables must be declared using the "var" function. A local variable is only valid for the event or script resource in which it is created. So GameMaker: Studio will create the variable, use it for the duration of the event and then "forget" it again, meaning that if you try to use it later you will get an "unknown variable" error.

  • global: a global variable is one that belongs to the game world itself and not to any one instance. It has to be declared as global first, but after that any instance can check or change the variable and the value will always reflect the last operation done on it, no matter what instance or code box has performed the operation.

  • built in variables: these are special variables that are "built into" the objects and the rooms in the game world and they can be instance only or global in scope (but never local) .

More details can be found for these variable types on the following pages:

  1. Instance Variables
  2. Local Variables
  3. Global Variables

There are a few functions designed to help you when dealing with instance variables and global variables, although these are generally more associated with debugging than anything else:

  • variable_instance_exists
  • variable_instance_get_names
  • variable_instance_get
  • variable_instance_set
  • variable_global_exists
  • variable_global_get
  • variable_global_set

Back: GML Overview
Next: Addressing Variables in Other Instances


async_load

Global variable for holding a DS map when used in the Asynchronous Events.

Syntax:

async_load;

Returns: Real

Description

This variable is global in scope and is used to hold a DS map when used in the Asynchronous Events, and -1 at all other times. The actual contents of the DS map will depend on the type of asynchronous event that it is populated in, and the function that was used to trigger the event, so refer to the individual pages for those events.

Example:

if ds_map_find_value(async_load, "id") == back
{
if ds_map_find_value(async_load, "status") >= 0
{
background_index[0] = back
}
}

The above code is taken from the Image Loaded Asynchrnous Event and will first check the ID of the async_load DS map that has been populated, then check the status of the callback. If the value is greater than or equal to 0 (signalling success) the result from the callback will then be used to set the background index to the newly loaded image.

Back: Global Variables
Next: score

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Global Variables

This section explains what global variables are and how to use them.

A basic description of a global variable is one that, once declared, belongs to no instance in particular and yet can be accessed by all. Just like local variables, global variables must be declared, but unlike a local variable, a global variable remains in memory until the end of the game. So, you can create a global variable to keep track of (for example) the number of bullets that the player has and then just update this variable at different points in the game. A global variable does not belong to any specific instance and can be accessed, changed and used by all instances at any time, but any change made to the variable are "global", in that all instances using the variable will be affected by the change. Let's have a look at an example:

global.food = 5;

We declare the "food" variable by first writing "global" and then a "." to tell GameMaker that this variable is now global scope. We will need to use this method from now on any time we are required to access or to change this variable in any way. So, we have created a new variable called "food" and we have declared it as global. Now, any instance can use and change this variable in any way and all other instances will "see" this. For example we could have a different food object that the player collides with and in the collision event we have:

global.food +=1;

We also have another object that draws this value like this:

draw_text(32, 32, "food = " + string(global.food));

With global variables we can change values and see those changes reflected in all instances of the objects that reference this variable. As with local variables you have to take care not to name your global variables the same as any instance variables as that will cause you problems and make bugs creep into your games due to variable overlap, which can be a difficult issue to debug sometimes. In general you should have a single script or object that declares all your global variables at the very start of the game (for example, in the Room Start Event), so that they are initialised and ready for any instance to use, and this also gives you a handy place to go back and reference should you need to check a variable name.

GameMaker: Studio has a collection of "built in" global variables too, so you should be aware of them as you may name one of your instance variables the same or wish to have your own global variable with the same name and wonder why you are getting errors! They are easy to spot, however, as they are shown in a different colour in the code editor and also come up in the auto-complete bar at the bottom. the majority of built in global variables are very specific and will only be used on rare occasions, but there are three in particular which are very useful and you can find out more about them from the pages listed below:

  1. score
  2. health
  3. lives
  4. async_load

globalvar

The following method can also be used to declare global variables, but it is only included for backwards compatibility, and it is not recommended that you use this method for new projects as future versions of GameMaker: Studio may not support it.

The second method for creating global variables is to declare them as such using the globalvar declaration, much as you would a local variable using the var declaration. For example:

globalvar food;
food = 5;

Once declared in this way that variable is now considered global and requires no "global." prefix - which also means that it's a lot harder to identify global variables in your code and it's also much easier to get variable overlap as you use the same variable name in different objects - and the variable is accessed as follows:

food += 2;

or:

draw_text(32, 32, "food = " + string(food));

Back: Variables And Variable Scope
Next: Instance Variables

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


health

Global variable for holding the player health.

Syntax:

health;

Returns: Real

Description

This variable is global in scope and is used to hold a numeric value which is usually used for the player health. Bear in mind this is not necessarily always the case - just because it's called "health" doesn't mean it has to be used for the health... it can hold any real or integer value you wish for your game.

Example:

if place_meeting(x, y, obj_Enemy)
{
health -= 10;
if health <= 0 instance_destroy();
}

The above code checks the current instance to see if there is a collision with the instance of the object indexed in "obj_Enemy", and if there is, it removes 10 points from the global health variable and then checks this value to see if it is less than or equal to 0. If it is the instance destroys itself.

Back: Global Variables
Next: lives

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Instance Variables

An instance variable is one that's scope is limited to the instance that creates it.

An instance variable is created within an instance of an object and is considered unique to that instance - ie: many instances of the same object can have the same variable, but each variable can hold a different value as they are unique to each instance. But how is an instance variable created? Well, you create new variables simply by assigning a value to them as shown in this small example:

potions = 12;
life = 100;
name = "Jock MacSweeney";
strength = 5.5;
armour = -2;

As you can see you just have to give the name and then a value (either numeric or a string) to set that variable and have it ready for use within an instance of the object you are coding for. These variables can then be used and modified in a number of ways from within the instance, for example this code could be in a collision event and used to take an amount off of the variable "life":

life -= 5 + armour;

If "life" is at 100 it will now have a value of 97 (100 - (5 + -2) = 97). Now, that's a simple example, and you could replace "armour" for the actual value of -2, but what happens if you use that value in multiple places and then decide to change it? You would have to go through ALL your code and change every -2 to whatever the new value is, which is time consuming and very error prone! But if you use a variable, all you have to do is reassign it a new value and the code will automatically use that new value from then onwards, making things far more flexible and far easier to fix should there be a problem. It should also be noted that even if a value is not going to change it is far easier to remember what a variable called "life" means rather than just looking at a number!

GameMaker: Studio has a collection of "built in" instance variables too, so you should be aware of them as you may name one of your own instance variables the same or wish to have your own global variable with the same name and wonder why you are getting errors! They are easy to spot, however, as they are shown in a different colour in the code editor and also come up in the auto-complete bar at the bottom.

Back: Variables And Variable Scope
Next: Local Variables

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


lives

Global variable for holding the player lives.

Syntax:

lives;

Returns: Real

Description

This variable is global in scope and is used to hold a numeric value which is usually used for the player lives. Bear in mind this is not necessarily always the case - just because it's called "lives" doesn't mean it has to be used for the lives... it can hold any real or integer value you wish for your game.

Example:

if place_meeting(x, y, obj_Enemy_Bullet)
{
health -= 10;
if health <= 0 lives -=1;
}

The above code checks the current instance to see if there is a collision with the instance of the object indexed in "obj_Enemy_Bullet", and if there is, it removes 10 points from the global health variable and then checks this value to see if it is less than or equal to 0. If it is then the instance removes 1 from the global lives variable.

Back: Global Variables
Next: async_load

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Local Variables

A local variable is one that we declare first, then use, and then discard.

A local variable is one that we create for a specific event only and then discard when the event has finished (the only exception to this is in the script resources, where a var declared variable is local to the script and then discarded). Why would we need them? Well, variables take up space in memory and it may be that we are only going to use them for one operation or function in which case we only need to have it in memory for that short time that it's used. This keeps your code base clean and tidy as well as keeping memory space optimised for the things that really need it. To declare a local variable we use the function var like this:

var i, num, str;
i = 0;
num = 24.5;
str = "Hi there!";

All of the variables created above will be "forgotten" (ie: removed from memory) at the end of the event (or script) in which they were created. You must be careful that the name you give var declared variables does not coincide with another instance variable within the object running the code, and also make sure that you have no intention of using the value stored in that variable outside of the event declare it in. These variables are used a lot in programs, especially in loops for counting iterations, or when using a value several times in one operation that is not going to be repeated again. Here are another couple of examples:

var i = 0;
repeat (10)
{
inventory[i] = 0;
i+=1;
}

The above code creates a local variable called "i" and sets it to 0, all in the same line. Note that in previous versions of GameMaker you had to declare your local variables first and then assign them values, but in this version you can declare and assign them a value at the same time. The above code then uses this variable to initialize an array. As the variable "i" is not going to be used for any further functions in the instance other than this, it can be local in scope. Here is one more example:

var xx,yy;
xx = x - 32 +irandom(64);
yy = y - 32 +irandom(64);
instance_create(xx, yy, obj_blood);

Here we have used the local variables to store some random coordinates that we then use to create an instance. In this example you can see that it is not strictly necessary that we use these variables but for the sake of readability and ease of use, we do. It is MUCH clearer and obvious what we are doing there than if we used this code:

instance_create(x - 32 + irandom(64), y - 32 + irandom(64), obj_guts);

One other thing about var declared variables should be noted... As they are unique to the event that runs them, they can be used in any other instances through code too! This means that we can use these variables to set and change things in other instances using the "with()" construct (there is a section on this in the GML Overview section of the manual). The actual code itself would look something like this:

var num = instance_number(obj_Enemy);
with (obj_Enemy)
{
if num>10 instance_destroy();
}

The above code works because the var declared variable is local to the event (or script) it is contained in, not the instance, nor the game world, and so can be used in any function in any object as long as it is in the same code block.

Back: Variables And Variable Scope
Next: Global Variables

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


score

Global variable for holding the game score.

Syntax:

score;

Returns: Real

Description

This variable is global in scope and is used to hold a numeric value which is usually used for the game score. Bear in mind this is not necessarily always the case - just because it's called "score" doesn't mean it has to be used for the score and it can be used to hold any integer value you choose.

Example:

if place_meeting(x, y, obj_Bullet)
{
score += 10;
instance_destroy();
}

The above code checks the current instance to see if there is a collision with the instance of the object indexed in "obj_Bullet", and if there is, it adds 10 to the global score and then destroys itself.

Back: Global Variables
Next: health

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


variable_global_exists

Check to see if a given global variable exists

Syntax:

variable_global_exists(name);

Argument | Description
name | The name of the global variable to check for (as a string)

Returns: Boolean

Description

With this function you can check whether a global scope variable exists or not. You supply the global variable name to check for as a string (see example code below) and the function will return true if a global variable with the given name exists or false otherwise.

Example:

if !variable_global_exists("enemy_num")) global.enemy_num = instance_number(obj_Enemey_Parent);

The above code will check to see if the global variable called "enemy_num" exists and if it does not it is created and set a value.

Back: Variables And Variable Scope
Next: variable_global_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


variable_global_exists

Check to see if a given global variable exists

Syntax:

variable_global_exists(name);

Argument | Description
name | The name of the global variable to check for (as a string)

Returns: Value (any data type) or undefined (if the named variable does not exist)

Description

With this function you can check whether a global scope variable exists or not. You supply the global variable name to check for as a string (see example code below) and the function will return true if a global variable with the given name exists or false otherwise.

Example:

if variable_global_exists("enemy_num")
{
show_debug_message("enemy_num = " + string(variable_global_get("enemy_num"));)
}

The above code will check to see if a global variable exists and if it does then it is output to the console.

Back: Variables And Variable Scope
Next: variable_global_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


variable_global_set

Set a given global variable to a value

Syntax:

variable_global_set(name, val);

Argument | Description
name | The name of the global variable to set (as a string)
val | The value to set the global variable to

Returns: Value (any data type) or undefined (if the named variable does not exist)

Description

With this function you can set the value of a given global variable. You supply the name of the global variable to set the value of as a string (see example code below), and then the value to set (can be any valid data type). If the global variable does not exist already in the game it will be created and then assigned the value.

Example:

if !variable_global_exists(id, "enemy_num")
{
variable_global_set("enemy_num", 0);
}

The above code will check to see if a global variable exists and if it does not then it is created and set to 0.

Back: Variables And Variable Scope
Next: variable_instance_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


variable_instance_exists

Check to see if a given instance variable exists

Syntax:

variable_instance_exists(instance_id, name);

Argument | Description
instance_id | The unique ID value of the instance to check
name | The name of the variable to check for (as a string)

Returns: Boolean

Description

With this function you can check whether an instance scope variable exists or not. You supply the unique instance ID value (which can be found from the room editor, or is returned when you call the function instance_create) as well as the variable name to check for as a string (see example code below). The function will return true if a variable with the given name exists for the instance and false otherwise.

Example:

if !variable_instance_exists(id, "shields")) shields = 0;

The above code will check to see if the variable called "shields" exists in the instance running the code and if it does not then it is created and initialised to 0.

Back: Variables And Variable Scope
Next: variable_instance_get_names

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


variable_instance_get

Retrieve the value of a given instance variable string

Syntax:

variable_instance_get(instance_id, name);

Argument | Description
instance_id | The unique ID value of the instance to use
name | The name of the variable to get (as a string)

Returns: Value (any data type) or undefined (if the named variable does not exist)

Description

With this function you can get the value from a given named variable. You supply the unique instance ID value (which can be found from the room editor, or is returned when you call the function instance_create) as well as the name of the variable to get the value of as a string (see example code below). The function will return the value held by the variable.

IMPORTANT! If the variable you are getting does not exist then the function will return the keyword undefined and you may get errors that will stop the game from functioning, so if in doubt use the function variable_instance_exists first.

Example:

if variable_instance_exists(id, "shields")
{
var ss = variable_instance_get(id, "shields");
}
else
}
var ss = -1;
}

The above code will check to see if a variable exists and if it does then the value it holds is retrieved and stored in a local variable. If it does not exist, the local variable is set to -1.

Back: Variables And Variable Scope
Next: variable_instance_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


variable_instance_get_names

Return an array of all instance scope variables.

Syntax:

variable_instance_get_names(instance_id);

Argument | Description
instance_id | The unique ID value of the instance to check

Returns: Array (each entry is a string)

Description

With this function you can retrieve an array populated with the instance variable names for an instance. Each entry in the array will be a string of the variable name that corresponds to an instance scope variable that has been created in the instance.

Example:

var str = "";
var array = variable_instance_get_names(id);
show_debug_message("Variables for " + object_get_name(object_index) + string(id));
for (var i = 0; i < array_length_1D(array); i++;)
{
str = array[i] + ":" + string(variable_instance_get(array[i]));
show_debug_message(str);
}

The above code will retrieve an array of all instance scope variables for the instance running the code block and then display these along with their values in the debug output.

Back: Variables And Variable Scope
Next: variable_instance_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


variable_instance_set

Set the value of a given instance variable

Syntax:

variable_instance_set(instance_id, name, val);

Argument | Description
instance_id | The unique ID value of the instance to use
name | The name of the variable to set (as a string)
val | The value to set the variable to

Returns: N/A

Description

With this function you can set the value of a given named variable. You supply the unique instance ID value (which can be found from the room editor, or is returned when you call the function instance_create) as well as the name of the variable to get the value of as a string (see example code below). If the variable does not exist already in the instance it will be created and then assigned the value.

Example:

if !variable_instance_exists(id, "shields")
{
variable_instance_set(id, "shields", 0);
}

The above code will check to see if an instance variable exists in the calling instance and if it does not then it is created and set to 0.

Back: Variables And Variable Scope
Next: variable_global_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Functions

This section lists all the functions made obsolete in GameMaker: Studio from previous versions of GameMaker.

Due to the fact that GameMaker: Studio is focused on fast cross platform development, there are a number of functions that were available in previous versions of GameMaker that are now no longer supported. Most of these have been removed to permit games to run on devices without them blocking, but some have been removed because they are obsolete with current technology, or because they are specific functions for Windows that are no longer necessary.

Explaining exactly why each of these features was removed, as well as suggesting any possible workaround for you, is outside of the scope of this manual, but you can find a list of all the functions and functionality that has changed between Legacy versions and GameMaker: Studio here: YoYo Games Knowledge Base - Porting GM7 And GM8 Games To GameMaker: Studio.

Each of the following pages details the functions that have been removed and gives a brief explanation as to why they have been removed:

  1. Triggers
  2. Registry Functions
  3. CD Functions
  4. Display Functions
  5. Splash Functions
  6. Particle Functions
  7. Sound Functions
  8. mPlay Functions
  9. Message Functions
  10. Dynamic Functions
  11. Transition Functions
  12. File Functions
  13. Miscellaneous Functions

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete CD Functions

These functions are for dealing with the Windows CD reader.

Function List:

Function | Description
cd_init | Must be called before using the other functions. Should also be called when a CD is changed (or simply from time to time).
cd_present | Returns whether a CD is present in the default CD drive.
cd_number | Returns the number of tracks on the CD.
cd_playing | Returns whether the CD is playing.
cd_paused | Returns whether the CD is paused or stopped.
cd_track | Returns the number of the current track (1=the first).
cd_length | Returns the length of the total CD in milliseconds.
cd_track_length | Returns the length of track n of the CD in milliseconds.
cd_position | Returns the current position on the CD in milliseconds.
cd_track_position | Returns the current position in the track being played in milliseconds.
cd_play | Tells the CD to play tracks first until last. If you want to play the full CD give 1 and 1000 as arguments.
cd_stop | Stops playing
cd_pause | Pauses the playing.
cd_resume | Resumes the playing.
cd_set_position | Sets the position on the CD in milliseconds.
cd_set_track_position | Sets the position in the current track in milliseconds.
cd_open_door | Opens the door of the CD player
cd_close_door | Closes the door of the CD player

The following function has also been removed:

Function | Description
MCI_command | This functions sends the command string to the Windows multimedia system using the Media Control Interface (MCI). It returns the return string. You can use this to control all sorts of multimedia devices. See the Windows documentation for information in how to use this command. For example MCI_command('play cdaudio from 1') plays a CD (after you have correctly initialized it using other commands). This function is only for advanced use!

Why These Are Obsolete

These are Windows only functions and no longer applicable to any other device.

Back: Obsolete Functions
Next: Display Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Display Functions

These functions are for dealing with aspects of how the game is displayed.

Function List:

Function | Description
screen_refresh | Refreshes the screen using the current room image (not performing drawing events).
screen_wait_vsync | Waits for the next vertical synchronization of the monitor.
set_automatic_draw | Indicates whether to automatically redraw the room (true, default) or not (false).
set_synchronization | Indicates whether to synchronize the drawing with the refresh frequency of the monitor.
display_set_size | Sets the width and height of the display in pixels. Returns whether this was successful. (Realize that only certain combinations are allowed.)
display_set_colourdepth | Sets the colour depth. In general only 16 and 32 are allowed values. Returns whether successful.
display_set_frequency | Sets the refresh frequency for the display. Only few frequencies are allowed. Typically you could set this to 60 with a same room speed to get smooth 60 frames per second motion. Returns whether successful.
display_set_all | Sets all at once. Use -1 for values you do not want to change. Returns whether successful.
display_test_all | Tests whether the indicated settings are allowed. It does not change the settings. Use -1 for values you do not want to change. Returns whether the settings are allowed.
window_set_region_size | Set the width and height of the drawing region in the window. adaptwindow indicates whether the window size must be adapted if the region does not fit in. The window size will always be adapted if you use fixed scaling.
window_set_region_scale | If the window is larger than the actual room normally the room is displayed in a region centered in the window. It is though possible to indicate that it must be scaled to fill the whole or part of the window. A value of 1 is no scaling. If you use a value of 0 the region will be scaled to fill the whole window. If you set it to a negative value it will be scaled to the maximal size inside the window while maintaining the aspect ratio (this is often what you want). adaptwindow indicates whether the window size must be adapted if the scaled room does not fit in. Adapting the window is only effective when the scale factor is positive.
window_get_region_scale | Returns the scale factor for the drawing region.
window_get_region_width | Returns the current width of the drawing region.
window_get_region_height | Returns the current height of the drawing region.
window_set_visible | Sets whether the game window is visible. Clearly you normally want the window to remain visible during the whole game. The program will not receive keyboard events when the window is invisible.
window_get_visible | Returns whether the game window is visible.
window_set_showborder | Sets whether the border around the window is shown. (In full screen mode it is never shown.)
window_get_showborder | Returns whether the border around the window is shown in windowed mode.
window_set_showicons | Sets whether the border icons (iconize, maximize, close) are shown. (In full screen mode these are never shown.)
window_get_showicons | Returns whether the border icons are shown in windowed mode.
window_set_stayontop | Sets whether the window must always stay on top of other Windows.
window_get_stayontop | Returns whether the window always stays on top of other Windows.
window_set_sizeable | Sets whether the window is sizeable by the player. (The player can only size it when the border is shown and the window is not in full screen mode.)
window_get_sizeable | Returns whether the window is sizeable by the player.
window_default | Gives the window the default size and position (centered) on the screen.
window_view_mouse_set | Sets the position of the mouse with respect to the view with index id.
window_views_mouse_set | Sets the position of the mouse with respect to the first view that is visible.
room_set_caption | Sets the room caption for the given room index.

Why These Are Obsolete

These functions are now considered obsolete due to the changes in the way that GameMaker: Studio draws things to the screen, as well as the fact that some of them are legacy functions from quite a while back which are no longer valid for modern computers and devices, or that they don't work on any device except a Windows machine, and even then they are usually not necessary.

Back: Obsolete Functions
Next: Splash Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Dynamic Functions

These functions deal with the generation of resources at run time.

Object Function List:

Function | Description
object_add | Adds a new object. It returns the index of the object. You can now use this index in the routines above to set certain properties of the object and then you can use the index to create instances of the object.
object_delete | Deletes the object with the given index. Make sure no instances of the object exist in any of the rooms.
object_event_add | To give the object a behavior we must define events for the object. You can only add code actions to events. You need to specify the object, the event type, the event number (use the constants that have been specified before for the event_perform() function). Finally you provide the code string that must be executed. You can add multiple code actions to each event.
object_event_clear | You can use this function to clear all the actions for a particular event.
object_set_parent | Set the parentfor an object.

Variable Function List:

Function | Description
variable_global_exists | Returns whether a global variable with the given name (a string) exists.
variable_local_exists | Returns whether an instance variable with the given name (a string) exists for the current instance.
variable_global_get | Returns the value of the global variable with the given name (a string).
variable_global_array_get | Returns the value of index ind of the global array variable with the given name (a string).
variable_global_array2_get | Returns the value of index ind1,ind2 of the global 2-dimensional array variable with the given name (a string).
variable_local_get | Returns the value of an instance variable with the given name (a string).
variable_local_array_get | Returns the value of index ind of an instance array variable with the given name (a string).
variable_local_array2_get | Returns the value of index ind1,ind2 of an instance 2-dimensional array variable with the given name (a string).
variable_global_set | Sets the global variable with the given name (a string) to the given value
variable_global_array_set | Sets the index ind in the global array variable with the given name (a string) to the given value.
variable_global_array2_set | Sets the index ind1,ind2 in the global 2-dimensional array variable with the given name (a string) to the given value.
variable_local_set | Sets an instance variable with the given name (a string) to the given value.
variable_local_array_set | Sets the index ind in an instance array variable with the given name (a string) to the given value.
variable_local_array2_set | Sets the index ind1,ind2 in an instance 2-dimensional array variable with the given name (a string) to the given value.

Resource Function List:

Function | Description
sprite_add_sprite | Adds the sprite stored the file fname to the set of sprite resources. The file must be a .gmspr file that is saved in the sprite property form in GameMaker.
background_add_background | Adds the background stored the file fname to the set of background resources. The file must be a .gmbck file that is saved in the background property form in GameMaker.
sprite_add_sprite | Adds the sprite stored the file fname to the set of sprite resources. The file must be a .gmspr file that is saved in the sprite property form in GameMaker.
background_add_background | Adds the background stored the file fname to the set of background resources. The file must be a .gmbck file that is saved in the background property form in GameMaker.
sprite_create_from_screen | Creates a sprite by copying the given area from the screen.
sprite_add_from_screen | Adds an area of the screen as a next subimage to the sprite with index ind.
background_create_from_screen | Creates a background by copying the given area from the screen.

Miscellaneous Function List:

Function | Description
room_set_code | Sets the initialization code string for the room with the indicated index.
script_get_text | Returns the text string of the script with the given index.
execute_string | Execute the piece of code in the string str with the indicated arguments.
execute_file | Execute the piece of code in the file with the indicated arguments.
execute_program | Executes program "prog" with arguments "arg". "wait" indicates whether to wait for finishing.
execute_shell | Executes the program (or file) in the shell.
timeline_moment_add | Adds a code action to the time line at moment step. If the step does not exist it is created. So you can add multiple code actions for the same moment.

Why These Are Obsolete

These functions cannot be used any more due to changes in the underlying runner that GameMaker: Studio uses to generate the device specific packages making it impossible to generate objects, images or code "on the fly" as was done before.

Back: Obsolete Functions
Next: Transition Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete File Functions

These functions are general ones related to previous versions of GameMaker.

Variable Function List:

Function | Description
file_open_write | Opens a file for writing.
file_open_read | Opens a file for reading.
file_open_append | Opens a file ready to append information to.
file_write_string | Writes a string to a previously opened file.
file_write_real | Writes a real value to a previously opened file.
file_writeln | Writes a new line to an already opened file.
file_read_string | Reads a string from a previously opened file.
file_read_real | Reads a real value from a previously opened file.
file_readln | Skips to the next line of a previously opened file for reading.
file_eof | Checks to see if the end of the opened file has been reached.
file_eoln | Checks to see if the end of the current line in the opened file has been reached.
file_close | Closes the currently open file.

Why These Are Obsolete

These have been replaced by the file_text_* and the file_bin_* functions.

Back: Obsolete Functions
Next: Miscellaneous Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Message Functions

These functions deal with pop up messages and Windows captions.

Function List:

Function | Description
show_message_ext | Displays a dialog box with the string as a message and up to three buttons. But1, but2 and but3 contain the button text. An empty string means that the button is not shown. In the texts you can use the & symbol to indicate that the next character should be used as the keyboard shortcut for this button. The function returns the number of the button pressed (0 if the user presses the Esc key).
message_background | Sets the background image for the pop-up box for any of the functions above. back must be one of the backgrounds defined in the game. Unfortunately, alpha values are not taken into account. However, if the left-bottom pixel has an alpha value of 0, all pixels with that colour will be considered transparent.
message_alpha | Sets the alpha translucence for the pop-up box for any of the functions above. alpha must lie between 0 (completely translucent) and 1 (not translucent) (only for Windows 2000 or later).
message_button | Sets the sprite used for the buttons in the pop-up box. spr must be a sprite consisting of three images, the first indicates the button when it is not pressed and the mouse is far away, the second indicates the button when the mouse is above it but not pressed and the third is the button when it is pressed. Unfortunately, alpha values are not taken into account. However, if the left-bottom pixel has an alpha value of 0, all pixels with that colour will be considered transparent.
message_text_font | Sets the font for the text in the pop-up box.
message_button_font | Sets the font for the buttons in the pop-up box.
message_input_font | Sets the font for the input field in the pop-up box.
message_text_charset | This function allows you to specify which character set the dialogs will use.
message_mouse_colour | Sets the colour of the font for the buttons in the pop-up box when the mouse is above it.
message_input_colour | Sets the colour for the background of the input filed in the pop-up box.
message_caption | Sets the caption for the pop-up box. Indicates whether a border must be shown (1) or not (0) and str indicates the caption when the border is shown.
message_position | Sets the position of the pop-up box on the screen. Use -1, -1 to center the box.
message_size | Fixes the size of the pop-up box on the screen. If you choose -1 for the width the width of the image is used. If you choose -1 for the height the height is calculated based on the number of lines in the message.
show_menu | Shows a popup menu. str indicates the menu text. This consists of the different menu items with a vertical bar between them. For example, str = 'menu0|menu1|menu2'. When the first item is selected a 0 is returned, etc. When the player selects no item, the default value def is returned.
show_menu_pos | Shows a popup menu as in the previous function but at position x,y on the screen.
get_colour | Asks the player for a colour. defcol is the default colour. If the user presses Cancel the value -1 is returned.
get_directory | Asks for a directory. dname is the default name. If the user presses Cancel an empty string is returned.
get_directory_alt | An alternative way to ask for a directory. Capt is the caption to be show. root is the root of the directory tree to be shown. Use the empty string to show the whole tree. If the user presses Cancel an empty string is returned.
show_score | Whether to show the score in the window caption.
show_lives | Whether to show the number of lives in the window caption.
show_health | Whether to show the health in the window caption.
caption_score | The caption used for the score.
caption_lives | The caption used for the lives.
caption_health | The caption used for the health.
highscore_show | Shows the highscore table. numb is the new score. If this score is good enough to be added to the list, the player can input a name.
highscore_set_background | Sets the background image to use. back must be the index of one of the background resources.
highscore_set_border | Sets whether the highscore form must have a border or not.
highscore_set_font | Sets the font used for the text in the table.
highscore_set_colours | Sets the colours used for the background, the new entry in the table, and the other entries.
highscore_set_strings | Changes the different default strings used when showing the highscore table.
highscore_show_ext | Shows the highscore table with a number of options (can also be achieved by using a number of the previous functions).
highscore_add_current | Adds the current score to the highscore list. The player is asked to provide a name.

The following constants have also been removed:

  • text_type
  • button_type
  • input_type

Why These Are Obsolete

These are Windows only functions and no longer applicable to any other device, especially since most of them block the runner to show the message boxes.

Note: While the highscore display functions are now obsolete, the internal highscores do still exists and can be used... You will just have to display them yourself through your own code.

Back: Obsolete Functions
Next: Dynamic Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Miscellaneous Functions

These functions are general ones related to previous versions of GameMaker.

Variable Function List:

Function | Description
secure_mode | Returns whether the game is running in secure mode or not.
set_program_priority | Sets the priority for the program. You can indicate a value between -3 and +3. A value of -3 means that the program will only run if no other process on the computer requires processing time, or stated differently, when all other processes are idle. Values of -2 and -1 are below normal, so other processes will get priority. 0 is the normal value. +1 and +2 give a higher priority, resulting possibly in higher speed and smoother game flow. But other processes will get much less processing time. +3 indicates real-time mode. In real-time mode basically all time is allotted to the game. This can lead to serious problems with any other applications running on the computer. Also keyboard events and e.g. the pressing of the close box might no longer be recorded by Windows. So only use this if you want all the processor time. Also better check carefully before using it and save the game before running.
set_application_title | Sets the title of the application to the given string. The title is for example shown in the task bar.
export_include_file | Exports the included file with the name fname. This must be a string variable, so don't forget the quotes.
export_include_file_location | Exports the included file with the name fname to the given location. Location must contain the path and the filename.
discard_include_file | Discard the included file with the name fname, freeing the memory used. This must be a string variable, so don't forget the quotes.
gamemaker_pro | Indicates whether the game is created with the Pro version or not.
gamemaker_registered | Same as gamemaker_pro.
gamemaker_version | The version of GameMaker. This is an integer. For version 8.0 this can be anything between 800 and 809. For version 8.1 this will be something between 810 and 819, etc. so never check a particular version but better check for a range. This variable is not available in version before 800.
error_last | String indicating the last error message.
error_occurred | Indicates whether an error has occurred.
sleep | Sleeps numb milliseconds.
io_handle | Update the input state from mouse or keyboard.
keyboard_wait | Waits till the user presses a key on the keyboard.
mouse_wait | Waits till the user presses a mouse button.
disk_size | Returns the size of the indicated drive in bytes.
disk_free | Returns the amount of free space on the indicated drive in bytes.
date_current_date | Returns the date corresponding to the current moment.
date_current_time | Returns the time corresponding to the current moment.
date_create_date | Creates a date-time value corresponding to the indicated date.
date_create_time | Creates a date-time value corresponding to the indicated time.
date_valid_date | Returns whether the indicated date is valid.
date_valid_time | Returns whether the indicated time is valid.

Why These Are Obsolete

These functions cannot be used any more due to changes in the underlying runner that GameMaker: Studio uses and the fact that most of them are no longer relevant to any other device except Windows.

Back: Obsolete Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete mPlay Functions

These functions deal with multi player/internet information transfer.

Function List:

Function | Description
mplay_data_write | Write value val (string or real) into location ind (ind between 0 and 1000000).
mplay_data_read | Returns the value in location ind (ind between 0 and 1000000). Initially all values are 0.
mplay_data_mode | Sets whether or not to use guaranteed transmission for shared data. guar should either be true (the default) or false.
mplay_init_ipx | Initializes an IPX connection.
mplay_init_tcpip | Initializes a TCP/IP connection. addr is a string containing the web address or IP address, e.g. 'www.gameplay.com' or '123.123.123.12', possibly followed by a port number (e.g. ':12'). Only when joining a session (see below) do you need to provide an address. On a local area network no addresses are necessary.
mplay_init_modem | Initializes a modem connection. initstr is the initialization string for the modem (can be empty). phonenr is a string that contains the phone number to ring (e.g. '0201234567'). Only when joining a session (see below) do you need to provide a phone number.
mplay_init_serial | Initializes a serial connection. portno is the port number (1-4). baudrate is the baud rate to be used (100-256K). stopbits indicates the number of stopbits (0 = 1 bit, 1 = 1.5 bit, 2 = 2 bits). parity indicates the parity (0=none, 1=odd, 2=even, 3=mark). And flow indicates the type of flow control (0=none, 1=xon/xoff, 2=rts, 3=dtr, 4=rts and dtr). Returns whether successful. A typical call is mplay_init_serial(1,57600,0,0,4). Give 0 as a first argument to open a dialog for the user to change the settings.
mplay_connect_status | Returns the status of the current connection.
mplay_end | Ends the current connection.
mplay_ipaddress | Returns the IP address of your machine (e.g. '123.123.123.12') as a string.
mplay_message_send | Sends a message to the indicated player (either an identifier or a name; use 0 to send the message to all players). id is an integer message identifier and val is the value (either a real or a string). The message is sent in non-guaranteed mode. If val contains a string the maximal string length allowed is 30000 characters.
mplay_message_send_guaranteed | Sends a message to the indicated player (either an identifier or a name; use 0 to send the message to all players). id is an integer message identifier and val is the value (either a real or a string). This is a guaranteed send. If val contains a string the maximal string length allowed is 30000 characters.
mplay_message_receive | Receives the next message from the message queue that came from the indicated player (either an identifier or a name). Use 0 for messages from any player. The routine returns whether there was indeed a new message.
mplay_message_id | Returns the identifier of the last received message.
mplay_message_value | Returns the value of the last received message.
mplay_message_player | Returns the player who sent the last received message.
mplay_message_name | Returns the name of the player who sent the last received message.
mplay_message_count | Returns the number of messages left in the queue from the player (use 0 to count all message).
mplay_message_clear | Removes all messages left in the queue from the player (use 0 to remove all message).
mplay_player_find | Searches for all players in the current session and returns the number of players found.
mplay_player_name | Returns the name of player number numb (0 is the first player, which is always yourself). This routine can only be called after calling the previous routine.
mplay_player_id | Returns the unique id of player number numb (0 is the first player, which is always yourself). This routine can only be called after calling the first routine. This id is used in sending and receiving messages to and from individual players.
mplay_session_create | Creates a new session on the current connection.
mplay_session_find | Searches for all sessions that still accept players and returns the number of sessions found.
mplay_session_name | Returns the name of session number numb (0 is the first session). This routine can only be called after calling the previous routine.
mplay_session_join | Makes you join session number numb (0 is the first session). playername is your name as a player. Returns whether successful.
mplay_session_mode | Sets whether or not to move the session host to another computer when the host ends. move should either be true or false (the default).
mplay_session_status | Returns the status of the current session.
mplay_session_end | Ends the session for this player.

Why These Are Obsolete

These were Windows only functions and are no longer applicable to any other device, and even for Windows they have been superceded by much better methods of doing the same thing.

Back: Obsolete Functions
Next: Message Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Particle Functions

These functions deal with the manipulation of particles.

The following functions for particle attractors have been removed:

Function | Description
part_attractor_create | Creates a new attractor in the given particle system. It returns the index of the attractor. This index must be used in all calls below to set the properties of the attractor.
part_attractor_destroy | Destroys attractor ind in the particle system. Call this if you don't need it anymore to save space.
part_attractor_destroy_all | Destroys all attractors in the particle system that have been created.
part_attractor_exists | Returns whether the indicated attractor exists in the particle system.
part_attractor_clear | Clears the attractor ind to its default settings.
part_attractor_position | Sets the position of attractor ind to (x,y).
part_attractor_force | Sets the force parameters of attractor ind.

The following functions for particle changers have been removed:

Function | Description
part_changer_create | Creates a new changer in the given particle system. It returns the index of the changer. This index must be used in all calls below to set the properties of the changer.
part_changer_destroy | Destroys changer ind in the particle system. Call this if you don't need it anymore to save space.
part_changer_destroy_all | Destroys all changers in the particle system that have been created.
part_changer_exists | Returns whether the indicated changer exists in the particle system.
part_changer_clear | Clears the changer ind to its default settings.
part_changer_region | Sets the region for the changer.
part_changer_types | Sets which particle type the changer must change into what other type.
part_changer_kind | Sets the kind for the changer.

The following functions for particle deflectors have been removed:

Function | Description
part_deflector_create | Creates a new deflector in the given particle system. It returns the index of the deflector. This index must be used in all calls below to set the properties of the deflector.
part_deflector_destroy | Destroys deflector ind in the particle system. Call this if you don't need it anymore to save space.
part_deflector_destroy_all | Destroys all deflectors in the particle system that have been created.
part_deflector_exists | Returns whether the indicated deflector exists in the particle system.
part_deflector_clear | Clears the deflector ind to its default settings.
part_deflector_region | Sets the region for the deflector.
part_deflector_kind | Sets the kind for the deflector.
part_deflector_friction | Sets the friction for the deflector.

The following functions for particle destroyers have been removed:

Function | Description
part_destroyer_create | Creates a new destroyer in the given particle system. It returns the index of the destroyer. This index must be used in all calls below to set the properties of the destroyer.
part_destroyer_destroy | Destroys destroyer ind in the particle system. Call this if you don't need it anymore to save space.
part_destroyer_destroy_all | Destroys all destroyers in the particle system that have been created.
part_destroyer_exists | Returns whether the indicated destroyer exists in the particle system.
part_destroyer_clear | Clears the destroyer ind to its default settings.
part_destroyer_region | Sets the region for the destroyer.

Why These Are Obsolete

Particles are normally very fast to process due to the fact that they are normally just graphical effects which, once fired off, are left to do their own thing based on the parameters set for them when you created the system. These routines, however, could be used to change particle properties after they have been created in a game, which means that each particle has to be tracked and dealt with in an individual manner. As this is horribly slow and defeats the purpose of particles (as they are meant to be used for fast graphical effects)

Back: Obsolete Functions
Next: Sound Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Registry Functions

These functions are for dealing with the Windows registry

Function List:

Function | Description
registry_write_string | Creates an entry in the registry with the given name and string value.
registry_write_real | Creates an entry in the registry with the given name and real value.
registry_write_string_ext | Creates an entry in the key in the registry with the given name and string value.
registry_write_real_ext | Creates an entry in the key in the registry with the given name and real value.
registry_read_string | Returns the string that the given name holds. The name must exist, otherwise an empty string is returned.
registry_read_real | Returns the real value that the given name holds. The name must exist, otherwise the number 0 is returned.
registry_read_string_ext | Returns the string that the given name in the indicated key holds. The name must exist, otherwise an empty string is returned.
registry_read_real_ext | Returns the real value that the given name in the indicated key holds. The name must exist, otherwise the number 0 is returned.
registry_exists | Returns whether the given name exists.
registry_exists_ext | Returns whether the given name exists in the given key.
registry_set_root | Sets the root for the other routines, where: 0 = HKEY_CURRENT_USER, 1 = HKEY_LOCAL_MACHINE, 2 = HKEY_CLASSES_ROOT and 3 = HKEY_USERS.

Why These Are Obsolete

Apart from these being Windows only functions and so incompatible with all other devices, these functions can also be considered a security problem as their misuse can cause serious issues with Windows based computers.

Back: Obsolete Functions
Next: CD Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Sound Functions

These functions deal with sound effects and 3D sounds.

Function List:

Function | Description
sound_effect_set | Sets a (combination of) sound effect(s) for the indicated sound. effect can be any of the constants listed below.
sound_effect_chorus | Sets the parameters for the chorus effect for the indicated sound.
sound_effect_echo | Sets the parameters for the echo effect for the indicated sound.
sound_effect_flanger | Sets the parameters for the flanger effect for the indicated sound.
sound_effect_gargle | Sets the parameters for the gargle effect for the indicated sound.
sound_effect_reverb | Sets the parameters for the reverb effect for the indicated sound.
sound_effect_compressor | Sets the parameters for the compressor effect for the indicated sound.
sound_effect_equalizer | Sets the parameters for the equalizer effect for the indicated sound.
sound_3d_set_sound_position | Sets the position of the indicated sound with respect to the listener to the indicated position in space.
sound_3d_set_sound_velocity | Sets the velocity of the indicated sound to the indicated vector in space.
sound_3d_set_sound_distance | Sets the minimum distance at which the sound does no longer increase in loudness and the maximum distance at which the sound can no longer be heard.
sound_3d_set_sound_cone | Normally sound has the same amplitude at a given distance in all directions. You can set the sound cone to change this and make sound directional.
sound_get_preload | Returns whether the sound with the given index has preload set.
sound_restore | Restores the indicated sound in audio memory for immediate playing.
sound_discard | Frees the audio memory used for the indicated sound.
sound_background_tempo | Changes the tempo of the background music (if it is a midi file).
sound_set_search_directory | Sets the directory in which direct music files are to be found. The dir string should not include the final backslash.
sound_pan | Changes the pan for the indicated sound (-1 = left, 0 = center, 1 = right).

The following constants have also been removed:

  • se_none
  • se_chorus
  • se_echo
  • se_flanger
  • se_gargle
  • se_reverb
  • se_compressor
  • se_equalizer

Why These Are Obsolete

These were Windows only functions and are no longer applicable to any other device.

Back: Obsolete Functions
Next: mPlay Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Splash Functions

These functions deal with splash screens and videos.

Function List:

Function | Description
splash_show_video | Shows a video splash screen. fname is the name of the video file. Whether a particular movie file is supported depends on the drivers on the machine. Typically you can use .avi, .mpg, and .wmv files but avoid special codecs. You best put this file in the folder of the game yourself or in a subfolder. loop indicates whether to loop the video.
splash_show_text | Shows a text splash screen. fname is the name of the text file. You can either display standard text files (.txt) or rich text files (.rtf). Only part of the rich text features are taken into account. E.g. images and other embedded objects are not shown. delay indicates the delay in milliseconds before returning to the game. use 0 or a negative value to wait until the player presses the escape key or clicks with the mouse in the window. (Note that no scrollbar will be shown nor is there another way to scroll the text. So the text must fit the window.)
splash_show_image | Shows an image splash screen. fname is the name of the image file. Many image types are supported (for example .bmp, .jpg, .tif, and .wmf) but no animated images. delay is the delay in milli seconds before returning to the game.
splash_show_web | Shows a web page splash screen. url is the url of the webpage (starting with http://) or it is the file name for a local html file. Note however that you must provide the full path for this to work. So you best e.g. use as url something like working_directory + "\index.html". delay is the delay in milli seconds before returning to the game
splash_set_main | Indicated whether the splash screen must be shown in the main game window (true, default) or in a separate window (false).
splash_set_scale | Sets the scale factor to be used when displaying a splash video or image. When using a value of 0 the scale factor is chosen such that the window is filled (default).
splash_set_cursor | Sets whether the cursor should be visible in the splash screen. Default it is visible. For movies the cursor cannot be switched off.
splash_set_colour | Sets the colour of the area surrounding the image or video.
splash_set_caption | Sets the caption for the splash window. This only has effect when is a separate splash window is used. Default the empty string is used.
splash_set_fullscreen | Indicates whether to use a full screen window or not. This only has effect when is a separate splash window is used. Default a normal window is used.
splash_set_border | Indicates whether the window should have a border. This only has effect when is a separate normal splash window is used. Default a border is used.
splash_set_size | Sets the size of the splash window. This only has effect when is a separate normal splash window is used. Default size is 640x480.
splash_set_position | Sets the position of the splash window. This only has effect when is a separate normal splash window is used. Default Windows determines the position.
splash_set_adapt | Indicated whether the size of the window must be adapted to the scaled size of the video or image. This only has effect when is a separate splash window is used. Default adapt is true.
splash_set_top | Indicates whether the window should stay on top of other Windows. This only has effect when is a separate splash window is used. Default the value is true.
splash_set_interrupt | Indicates whether the game play should be interrupted while showing the splash window. This only has effect when is a separate splash window is used. Default the value is true.
splash_set_stop_key | Indicates whether to stop the display of the splash screen when the player pressed the Escape key. Default the value is true.
splash_set_stop_mouse | Indicates whether to stop the display of the splash screen when the player pressed the mouse inside the splash screen. Default the value is true.
splash_set_close_button | Indicates whether to show a close button in the top right corner of the splash screen. This is useful when running games in full screen mode or without a border. Default the value is true.

The following functions have also been removed:

Function | Description
show_info | Displays the game information window.
load_info | Loads the game information from the file named fname. This should be a rich text file (.rtf). This makes it possible to show different help files at different moments. Note that contrary to the splash screens, this rtf file cannot contain images.

Why These Are Obsolete

These are Windows only functions and no longer applicable to any other device, especially since they block the runner to show the splash screens.

Back: Obsolete Functions
Next: Particle Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Obsolete Transition Functions

These functions deal with splash screens and videos.

Function List:

Function | Description
transition_kind | Indicates the next room transition. You can use the following built-in values
transition_steps | Indicates the number of steps in the transition. The more steps, the longer the transition takes. Default is 80.
transition_define | You can actually create your own transitions. To this end you must define a script (possibly in an extension package) to do the transition. With this function you can then add the transition to the system. kind is the index of the transition (either a new one or an existing transitions). name is the name of the script. Note that the name of the script is a string! So there must be quotes around it. Note that this is really advanced stuff. The script must take five arguments: a surface with the image of the previous room, a surface with the image of the next room, the width of the surfaces, the height of the surfaces, and the fraction of the transition (between 0 and 1). It must then draw the image using the two surfaces.
transition_exists | This function returns whether a transition of the indicated kind exists.

Why These Are Obsolete

These functions have been removed due to the fact that they more or less "take over" control of the device to work. They are also incompatible with the way GameMaker: Studio now handles graphics.

Back: Obsolete Functions
Next: File Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Trigger Events

Trigger events are special events that will only "trigger" when the requirements that you specify in code have been met.

Why This Is Obsolete

Triggers, as implemented by previous versions of GameMaker, were in-efficient, very little used by the majority of people, and only seemed to break up the game-logic and make tracking complex games far more difficult than necessary. For those that used them, the same functionality can easily be achieved by creating a script and calling it in either the begin step event, the step event or the end step event of an object.

As you may have an older file made with previous versions of GameMaker that uses triggers, you can find an outline of what the trigger event was and how it was used below for use as a reference:

The Trigger Event

To define trigger events you chose Define Triggers from the Resources menu at the top of the main GameMaker window, or you can select to add a trigger event from within the object and then select "Add/Modify Triggers". Either method will open the following form where you define your trigger with a short code function. The form shown below contains an example of how this may be written.

At the left you see a list of all triggers that have so far been defined by you (obviously empty if you haven't yet created any!). Below there are some buttons which have the following functions:

  • Add. Use this button to add a new trigger event to the list. The form will then change to display the new empty trigger ready to add the necessary code and name.

  • Delete. Deletes the currently selected trigger event selected on the list. Be careful to never delete a trigger event that is used in an object! This will lead to unexpected results and will most certainly cause your problems in your project.

  • Load. Loads a collection of triggers from a file. Such a file must have the extension .gmtrg. The triggers from the file are added to the list of triggers on the left of the form and can then be used or modified as normal.

  • Save. Saves the collection of triggers to a file. This file should have the extension .gmtrg. In this way you can create your own library of triggers which can then be loaded into any further projects for use, and so saving you time.

  • Clear. Completely clears the list of all triggers. Be careful to only use this when no object uses any trigger event! As with Delete using Clear when an object is using a trigger event can have unwanted side-effects that may cause serious problems when running your project.

Once you are finished you must press the OK button to save the changes and be able to use the trigger event within an object. If you do not want to save the changes, simply close the form by clicking on the cross at the top right corner and indicate that you do not want to save changes in the dialogue box that will pop up.

Defining A Trigger

Once you have created a trigger you must fill in its properties, normally starting with giving it a name. This name can be anything you wish, as long as you use permitted characters (see further down for information about naming the trigger as a constant), but it should always be something descriptive so that you know instantly what it does when you select it to use in an object. This name will appear in the menu with available triggers and in the event lists for objects. The next you must do is specify the condition that will "trigger" the trigger event! This is done by writing a piece of GML code into the window on the right which returns either a true or false value when run. In this way a trigger will only fire when the return value is true.

Examples Of Use

Assume you want to create an event that happens when the player presses both the Control key and the A key. For this you could write the following condition script:

{
return keyboard_check(ord('A')) && keyboard_check(vk_control);
}

As you can see this condition script will return false unless both the Control key and the A key are pressed together.

You can actually put some quite complex and complete scripts as the condition, as long as somewhere in there you have a return statement that evaluates as true or false. For example, to have an event happen only when the number of instances (in this case "obj_ball") is between 3 and 5, you can use the following condition script:

{
var n;
n = instance_number(obj_ball);
return (n >= 3) && (n <= 5);
}

You may find that sometimes the code you need to define the condition is too long for the code window within the trigger form, so you might want to edit it in the actual code editor instead. To that end press the button Use code editor to open that window and keep working as normal, clicking on the tick in the top left corner to save your changes to the trigger.

You can create many other type of trigger events. For example, events that check whether you are near to an enemy, events to check whether you collected enough money or have a high score, events to spawn an object at a certain place... The possibilities are endless which makes using triggers a very handy way to organise your game, and re-use scripts that are helpful in other projects.

After you have specified the condition script, you should specify when the condition is to be tested. There are three options for this, all related to the step event:

  • You can test the condition at the beginning of a step (just before the begin step event).
  • You can test the condition in the middle of a step(just before the normal step event).
  • Or you can test the condition at the end (just before the end step event).

Most of the time the default middle position is fine, but in certain cases you need the other moments, particularly if the outcome of the trigger affects the next part of the step, or relies on something that has been done previously.

Naming a Constant

Finally, you may even create a constant with which to call the specified trigger event from code. To do this you must give it a name which must not contain spaces, nor unauthorized characters, and be easy to remember. If you look at the image above, you can see that we have used "tr_Near_Wall" to define the constant for that trigger. This follows the naming rules, is descriptive and easy to understand and will allow the trigger to be called from any other event in code. It should be noted that a trigger used in code does not evaluate to true or false, but it may still be used to set variables and other things. A sample of the code use would be:

event_perform(ev_trigger, tr_Near_Wall);

Using a trigger

Once you have defined your triggers you can use them when defining objects. To do this you would click on the Add Event, and then select Trigger events.

A pop-up will give you a list of the triggers you have created or loaded and you can select from there the one you wish to use. It will then be added to the event list as normal.

Back: Obsolete Functions
Next: Registry Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Advertising and Analytics

These functions are provided for integrating advertising and analytics services.

WARNING! As of the 1.3 update to GameMaker: Studio, these functions are no longer applicable to the Android and iOS target platforms. Instead, please see the section on Extensions as these platforms are now supported through Extension Packages.

There are a number of different companies that offer mechanisms to add advertising to your games, and there are others that permit you to integrate some form of analytics (so that you can see how your game is expanding in the given market place). GameMaker: Studio has a number of functions included as standard to make adding these services a simple matter.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio.

In Game Advertising

Once you have set up your advertising provider in the Global Game Settings - Advertising Tab, you will need to write them into your game using the following simple functions to control how the adverts are used and displayed:

  1. ads_enable
  2. ads_disable
  3. ads_move
  4. ads_get_display_width
  5. ads_get_display_height

We also support basic interstitial ads from Admob with the following functions:

  1. ads_interstitial_available
  2. ads_interstitial_display

Apart from these basic ads, some ad providers (like Supersonic and AdColony) offer more interactive interstitial ads that can be used to generate virtual currency for the user. However for these ads to function correctly you will need to have set up your own database to record the currencies for each player, which also means you should create your own login system to get the player id, or have some mechanism in place to identify each installation of your game to the database.

When you activate one of these ads it can be an "offerwall" (essentially a page to promote several different advertising campaigns) or a video and when the player watches an ad or clicks on an offer, the ad company calls your callback on the server you have set up to award the currency to the player. Note that it could be 15 minutes after the player has watched the movie (or clicked an offer) or it could be instantaneous so you must have that backend database set up and active 24 hours a day.

NOTE: To retrieve the currency for your player, you will need to use the http_get and http_post_string functions.

The following functions exist for ads from these companies:

  1. ads_setup
  2. ads_engagement_available
  3. ads_engagement_launch
  4. ads_engagement_active

Testing Ads

Certain providers provide the possibility to test ads on your device before you actually finalize their use and so GameMaker: Studio includes the option to switch testing on in the Global Game Settings - Advertising Tab. This option will affect your app differently depending on the target platform and the provider selected.

Android

On Android devices when testing is active, all ads will be displayed with a blue background that permits you to see what position and area is being used for the ad as well as see how well the test ads fit the specified ad space. Not all ad providers permit ad testing so below is a brief summary of those that do and how to set them up:

  • AdMob - You must first run your game once with AdMob ads enabled (but not testing!), making sure that your key0 advertising key is correct and using the ads_enable function. If you then look at the ADB console output, near the bottom you should see the following line: The device id number should then be copied into the appropriate space on the Advertising tab of the global Game Settings, and you should now flag the "test Ads" check-box to switch ad testing on. When you run your game again, this will be confirmed to be working by the ADB console output showing the message “Admob using test adverts”.

  • Ad Colony - You can see their test videos and offerwalls by configuring the test options through your profile page on their site http://www.adcolony.com/

  • Millennial Media - You should set the key0 app id to be "28911" and flag the "Test Ads" check-box to start receiving test ads on your device. This will also raise the number of event logs that are registered to make debugging easier.

iOS

iOS ad testing is limited to only a few companies currently and these are listed below along with instructions on how to set them up:

  • AdMob - Unlike on Android devices, Admob for iOS simply needs to be activated on the Advertising tab and have the "Test Ads" check-box ticked and it will then work as it should, sending test ads and ignoring clicks.

  • iAds iAds will only use test ads if you are running a signed distribution build and this is regardless of the settings in GameMaker: Studio as it is done automatically by iAds.

  • Millennial Media – As with Android, the event log levels are increased to debug levels, but instead of having a universal testing app id, you must register your device id on the mmedia.com site to receive test ads.

HTML5

Currently the support for testing ads on HTML5 has to be configured through the control panel of your developer account with the chosen company, with the "Test Ads" option in the Global Game Settings doing nothing at the moment. It is simply provided to make integrating future advertising partners easier.

PlayHaven

PlayHaven is a content provider for iOS and Android that permits you to show interstitial ads with a wide variety of content available - cross promotion of games, paid ads, user data requests and a lot more besides. Accessing all this functionality can be achieved via a very few function calls from within GameMaker: Studio, but to get them to work correctly you will have to have created a PlayHaven account and set up content to be displayed.

Further information on PlayHaven setup and integration can be found on the YoYo Games Knowledge Base.

The following functions can be used in your games to access PlayHaven content:

  1. ads_event
  2. ads_event_preload
  3. ads_set_reward_callback
  4. playhaven_add_notification_badge
  5. playhaven_hide_notification_badge
  6. playhaven_position_notification_badge
  7. playhaven_update_notification_badge

Analytics

WARNING! As of the 1.4 update to GameMaker: Studio, these functions are no longer applicable to the Android and iOS target platforms. Instead, please see the section on Extensions as these platforms are now supported through Extension Packages.

Your game can be tracked by different Analytics providers (principally Flurry and Google Analytics) which can be set up in the special Global Game Settings - Analytics Tab. In general, the analytics are autonomous, with each provider tracking the product and making the information available through their own web pages, but there are two extra functions supplied by GameMaker: Studio to permit you to send a text event to the analytics provider which you can then use to track special features from within your game:

  1. analytics_event
  2. analytics_event_ext

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_disable

Switch off in game ads.

Syntax:

ads_disable(num)

Argument | Description
num | The advert "slot" to disable (0 - 4).

Returns: N/A

Description

This function switches off the in-game ads for the given "slot" (as defined in the Global Game Settings - Advertising Tab), so that they are no longer displayed.

Example:

if purchased
{
ads_disable(0);
}

The above code switches off in game ads for "slot" 0 if the variable "purchased" returns true.

Back: Advertising and Analytics
Next: ads_move

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_enable

This code enables ads in your game room.

Syntax:

ads_enable(x, y, num)

Argument | Description
x | The x position in the room.
y | The y position in the room.
num | The advert "slot" to display (0 - 4).

Returns: N/A

Description

With this function you can display selected ads at the given position within the GUI. The "num" that you supply is the number of the advertising key that you wish to use as defined in the Global Game Settings - Advertising Tab, and will generate and advert of the size specified for that key.

Example:

ads_enable(0, 0, 1);

The above code switches on ads to be displayed at the top of the GUI, on the left and it will request the add defined for key 1 in the Global game Settings tab.

Back: Advertising and Analytics
Next: ads_disable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_engagement_active

Find the video advertisement status.

Syntax:

ads_engagement_active()

Returns: Boolean

Description

Some ad providers, for example Supersonic and AdColony, have interstitial advertisements that can take the form of an "offer wall" (essentially a page to promote several different advertising campaigns) or a video where virtual currency is rewarded to the player, so it's important to know when one of these adverts is being shown. This function will return true if such an ad is currently active or false if it is not.

Example:

if !ads_engagement_active()
{
if ads_engagement_available() && show
{
ads_engagement_launch();
show = false;
}
else
{
room_goto(rm_MainMenu);
}
}

The above code checks to see if there is currently and interstitial ad active and if not, then it will check to see if one is available and that the variable "show" returns true. If both conditions are met, an interstitial ad will be launched and the variable set to false, so that when the add is finished the check will take the player to the next room.

Back: Advertising and Analytics
Next: ads_event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_engagement_available

Find if an interstitial video/offerwall is available.

Syntax:

ads_engagement_available()

Returns: Boolean

Description

Some ad providers, for example Supersonic and AdColony, have interstitial advertisements that can take the form of an "offer wall" (essentially a page to promote several different advertising campaigns) or a video where virtual currency is rewarded to the player, so it's important to know when one of these adverts is available to be shown. This function will return true if such an ad is currently available or false if it is not.

Example:

if !ads_engagement_active()
{
if ads_engagement_available() && show
{
ads_engagement_launch();
show = false;
}
else
{
room_goto(rm_MainMenu);
}
}

The above code checks to see if there is currently and interstitial ad active and if not, then it will check to see if one is available and that the variable "show" returns true. If both conditions are met, an interstitial ad will be launched and the variable set to false, so that when the add is finished the check will take the player to the next room.

Back: Advertising and Analytics
Next: ads_engagement_launch

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_engagement_launch

Launch an interstitial video/offerwall.

Syntax:

ads_engagement_launch()

Returns: N/A

Description

Some ad providers, for example Supersonic and AdColony, have interstitial advertisements that can take the form of an "offer wall" (essentially a page to promote several different advertising campaigns) or a video where virtual currency is rewarded to the player. If such an advert is available, this function can be used to launch it at a specific moment within your game.

Example:

if !ads_engagement_active()
{
if ads_engagement_available() && show
{
ads_engagement_launch();
show = false;
}
else
{
room_goto(rm_MainMenu);
}
}

The above code checks to see if there is currently and interstitial ad active and if not, then it will check to see if one is available and that the variable "show" returns true. If both conditions are met, an interstitial ad will be launched and the variable set to false, so that when the add is finished the check will take the player to the next room.

Back: Advertising and Analytics
Next: ads_engagement_active

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_event

Trigger the PlayHaven content associated with the given placement name.

Syntax:

ads_event(placement)

Argument | Description
placement | The PlayHaven placement name (a string)

Returns: N/A

Description

This function will send an ad request to PlayHaven. The argument that it takes is the placement name string that you wish to use. If that placement is associated with any content from the PlayHaven network (which you must have set up previously from the PlayHaven dashboard - see here), an interstitial ad overlay will be shown. Some of these ads generate a callback, which can be dealt with from a script as defined by the function ads_set_reward_callback. You must have ads enabled and PlayHaven set up correctly in the Global Game Settings - Advertising Tab otherwise no ads will be shown.

Example:

ads_set_reward_callback(scr_AdsCallback);
ads_event("game_start");

The above code will set the callback script and then request an ad from PlayHaven for the placement named "game_start".

Back: Advertising and Analytics
Next: ads_event_preload

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_event_preload

Preload a PlayHaven ad placement, ready to be shown.

Syntax:

ads_event_preload(placement)

Argument | Description
placement | The PlayHaven placement name (a string)

Returns: N/A

Description

This function will preload a PlayHaven ad into memory, ready for it to be shown when the ads_event calls the placement used (both functions require the same placement name string to work. If you know that after a certain time or at a certain point in your game you are going to be calling a PlayHaven content placement, then this function can be called beforehand so as to make the user experience as smooth as possible.

NOTE: This function will not show the ad! It only loads it into memory.

Example:

ads_event_preload("game_start");

The above code will preload an ad from PlayHaven for the placement named "game_start".

Back: Advertising and Analytics
Next: ads_set_reward_callback

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_get_display_height

This function gets the height of the currently displaying ad.

Syntax:

ads_get_display_height(num)

Argument | Description
num | The advert number to display (0 - 4).

Returns: Real

Description

With this function you can get the height of the ad box defined for the ads enabled by the ads_enable function.

Example:

ads_move(0, display_get_gui_height() - ads_get_display_height(0), 0);

The above code will set an advert to display at the bottom left-hand corner of the display.

Back: Advertising and Analytics
Next: ads_interstitial_available

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_get_display_width

This function gets the width of the currently displaying ad.

Syntax:

ads_get_display_width(num)

Argument | Description
num | The advert number to display (0 - 4).

Returns: Real

Description

With this function you can get the width of the ad box defined for the ads enabled by the ads_enable function.

Example:

ads_move(display_get_gui_width() - ads_get_display_width(0), 0, 0);

The above code will set an advert to display at the top right-hand of the display.

Back: Advertising and Analytics
Next: ads_get_display_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_interstitial_available

Check to see if an interstitial ad can be served.

Syntax:

ads_interstitial_available()

Returns: Boolean

Description

This function will check to see if there is an interstitial ad available from the chosen ad provider (currently limited to ad Mob) and return true if there is or false if there is not.

Example:

if ads_interstitial_available()
{
ads_interstitial_display();
}

The above code checks to see if the ad provider can serve an interstitial ad and if it can, it then calls the function to display it.

Back: Advertising and Analytics
Next: ads_interstitial_display

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_interstitial_display

Display an interstitial ad if one is available.

Syntax:

ads_interstitial_display()

Returns: N/A

Description

This function will show an interstitial ad if one is available (limited currently to Ad mob only). If one is available, it will be shown until the user closes it, with the game still running in the background, so be aware of this and only use the function at points where it won't interrupt the game-play of your game.

Example:

if ads_interstitial_available()
{
ads_interstitial_display();
}

The above code checks to see if the ad provider can serve an interstitial ad and if it can, it then calls the function to display it.

Back: Advertising and Analytics
Next: ads_setup

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_move

This code moves displaying ads in your game room.

Syntax:

ads_move(x, y, num)

Argument | Description
x | The new x position in the room.
y | The new y position in the room.
num | The advert number to display (0 - 4).

Returns: N/A

Description

With this function you can move displaying ads to the given position within the GUI. The "num" that you supply is the number of the advertising key that you wish to use as defined in the Global Game Settings - Advertising Tab, and will generate an advert of the size specified for that key.

Example:

ads_move(display_get_gui_width() - ads_get_display_width(0), 0, 0);

The above code will set an advert to display at the top right-hand of the display.

Back: Advertising and Analytics
Next: ads_get_display_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_set_reward_callback

Set the reward callback script for PlayHaven interstitial.

Syntax:

ads_set_reward_callback(placement)

Argument | Description
placement | The PlayHaven placement name (a string)

Returns: N/A

Description

When generating content for the user using PlayHaven, the content can return callback values to your game, depending on what content it is and what rewards 8if any) are associated with it. To deal with this, you should create a script resource into which GameMaker: Studio will automatically pass the return arguments:

  • argument0 - A real number that represents the quantity/value returned by PlayHaven. -1 means that the interstitial was closed by the user without any action being taken.
  • argument1 - A string that contains the reward name as defined by you in the PlayHaven dashboard.

In this way with one single script you can reward the player with in game currency, items, etc... depending on the quantity returned and the reward name used.

Example:

ads_set_reward_callback(scr_AdsCallback);
ads_event("game_start");

The above code will set the callback script and then request an ad from PlayHaven for the placement named "game_start".

Back: Advertising and Analytics
Next: playhaven_add_notification_badge

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ads_setup

Setup offerwall support for ads.

Syntax:

ads_setup(user_uuid, ad_app_key)

Argument | Description
user_uuid | The user key for the rewards currency.
add_app_key | The app key for your game

Returns: N/A

Description

This function will pass the user id of the player to those providers, for example Supersonic and AdColony, that generate virtual currency "offerwalls" (essentially a page to promote several different advertising campaigns) and videos, so that the currency can be rewarded to the correct player for viewing or clicking these ads. The service providers should supply you with the app key for each specific game that you create and it is recommended that you store this as a constant within your game for ease of use later. Please refer to the YoYo Games Knowledge Base section on In App Advertising for more information related to your specific ad provider.

NOTE: Even if you only have your app configured for video advertising, you will still need to call this function to prepare the integrated developer api, but you should use and empty string ("") for the arguments.

Example:

if os_get_config() = "FreeOfferwall"
{
ads_setup(u_id, APP_KEY);
}

The above code will check the current configuration used for the game build and if it is "FreeOfferwall", then it will setup the advertising functions with the user id stored in the variable "u_id" and the application key stored in the custom constant "APP_KEY".

Back: Advertising and Analytics
Next: ads_engagement_available

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


analytics_event

Send an analytics event to your analytics provider.

Syntax:

analytics_event(string)

Argument | Description
string | A string to send to the provider.

Returns: N/A

Description

This function will send the specified text to the analytics provider that you have set up through the Global Game Settings - Analytics Tab. This function can be used to create a custom analytic to track something outside of the scope of the provider being used.

Example:

if hs_new
{
analytics_event("New hiscore of " + string (score));
}

The above code will check a variable to see if it is true and if it is then a special analytics event will be triggered with the specified string.

Back: Advertising and Analytics
Next: analytics_event_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


analytics_event_ext

Send a special, extended analytics event to your analytics provider.

Syntax:

analytics_event_ext(string, string_param0, value0, string_parm1, value1, ...)

Argument | Description
string | A string to send to the provider.
string_param[0 -9] | The parameter to send (a string).
value[0 - 9] | The value of the parameter (a real number).

Returns: N/A

Description

This function will send the specified text to the analytics provider that you have set up through the Global Game Settings - Analytics Tab. This function can be used to create a custom analytic to track something outside of the scope of the provider being used, and will also accept custom parameter/value pairs, where the parameter is a string and the value a real number. For Google Analytics, you can only add in one extra pair while Flurry will accept up to 7, and MarkedUp does not accept parameters so only the initial string will be shown.

Example:

var num, time;
ini_open("Options.ini");
num = ini_read_real("Data", "Plays", 0);
num += 1;
time = current_time;
analytics_event_ext(GAME_NAME, "Plays", num, "Time", time);
ini_write_real("Data", "Plays", num);
ini_close();

The above code will get play information from an ini file as well as the current time and then send those details to the analytics provider.

Back: Advertising and Analytics
Next: analytics_event

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


playhaven_add_notification_badge

Add a PlayHaven notification to the game.

Syntax:

playhaven_add_notification_badge(x, y, w, h, ident)

Argument | Description
x | The new x position in the room.
y | The new y position in the room.
w | The width of the badge.
h | The height of the badge
ident | The PlayHaven content name that identifies the widget being used.

Returns: N/A

Description

When using the PlayHaven More Games Widget (see here for more details) you can add a notification badge to the game that will show the number of games added to the network since the last update. Normally you would have a button object (for example) which would request the More Games widget be displayed in your game when the user clicks on it, and you can use this function to entice the player into clicking by showing whenever there are new games available on the button object itself.

Example:

playhaven_add_notification_badge(x- 16, y - 16, 32, 32, "games_widget");

The above code will set a badge to be displayed on the current object that will show when new games have been added to the More Games content that you defined with the name "games_widget".

Back: Advertising and Analytics
Next: playhaven_hide_notification_badge

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


playhaven_hide_notification_badge

Hide a PlayHaven notification.

Syntax:

playhaven_hide_notification_badge(x, y, w, h, ident)

Returns: N/A

Description

With this function you can hide any PlayHaven notification badges that you have previously created with the function playhaven_add_notification_badge.

Example:

if global.game_state != st_mainmenu
{
playhaven_hide_notification_badge();
}
else
{
playhaven_add_notification_badge(x- 16, y - 16, 32, 32, "games_widget");
}

The above code will check the value of a global variable and either add or hide a PlayHaven notification badge.

Back: Advertising and Analytics
Next: playhaven_position_notification_badge


playhaven_position_notification_badge

Change the position of a PlayHaven notification.

Syntax:

playhaven_position_notification_badge(x, y, w, h)

Argument | Description
x | The new x position in the room.
y | The new y position in the room.
w | The width of the badge.
h | The height of the badge

Returns: N/A

Description

After having added a PlayHaven notification badge (using the function playhaven_update_notification_badge) you can then change its position within the room using this function.

Example:

playhaven_position_notification_badge(x- 16, y - 16, 32, 32);

The above code will move the PlayHaven notification badge to a new location relative to the instance.

Back: Advertising and Analytics
Next: playhaven_update_notification_badge


playhaven_update_notification_badge

Update any PlayHaven notifications.

Syntax:

playhaven_update_notification_badge(x, y, w, h)

Returns: N/A

Description

After having added a PlayHaven notification badge (using the function playhaven_update_notification_badge) you can request an update from the PlayHaven network using this function.

Example:

playhaven_update_notification_badge();
alarm[0] = room_speed * 30;

The above code will request an update of new games available from the PlayHaven network and then reset the alarm to check again 30 seconds later.

Back: Advertising and Analytics
Next: ads_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


pocketchange_display_reward

pocketchange_display_reward (Deprecated)

Display the Pocket Change reward screen.

Syntax:

pocketchange_display_reward();

Returns: N/A

Description

Calling this function will open the Pocket Change app on the Shop page. If the user does not have the app installed, it will instead open the Google Play store on the Pocket Change app page and invite the user to download the app.

Example:

if mouse_check_button_pressed(mb_left)
{
pocketchange_display_reward();
}

The above code will check for a mouse button press and if one is detected, it will open the Pocket Change app on the rewards screen.

Back: Advertising and Analytics
Next: pocketchange_display_shop

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


pocketchange_display_shop

pocketchange_display_shop (Deprecated)

Display the Pocket Change shop screen.

Syntax:

pocketchange_display_shop();

Returns: N/A

Description

Calling this function will open the Pocket Change app on the Shop page. If the user does not have the app installed, it will instead open the Google Play store on the Pocket Change app page and invite the user to download the app.

Example:

if mouse_check_button_pressed(mb_left)
{
pocketchange_display_shop();
}

The above code will check for a mouse button press and if one is detected, it will open the Pocket Change app on the rewards screen.

Back: Advertising and Analytics
Next: pocketchange_display_reward

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Asynchronous Function

Asynchronous Functions

GameMaker: Studio has a number of functions that permit asynchronous communication.

Before dealing with the asynchronous functions (referred to from now on as async functions) in GameMaker: Studio it may be that you are wondering what the word "asynchronous" actually means! Well, the actual dictionary definition of asynchronous is:

"pertaining to a transmission technique that does not require a common clock between the communicating devices; timing signals are derived from special characters in the data stream itself."

In the context of GameMaker: Studio, an async function is one that sends out to a web server, or asks for user input, or even streams data, while letting GameMaker: Studio continue to run without blocking. When the information callback is received a special Async Event is fired which, in turn, allows any instance with an Async Event assigned to it to execute further functions (although this does not have to be the case). So, basically, it's a way to communicate with some external resource (server, user or device) without the game or project blocking while waiting for a reply.

Why is this important? Well, since it allows GameMaker: Studio to continue functioning while sending or receiving data, and this means that you can do many things all without blocking the game loop like -

  • stream data from the device into your game without the player waiting for things to load
  • have callback events to do things only when the correct information is received
  • communicate and interchange data with a web server

This all makes everything function in a much more fluid and unobtrusive way. It should be noted that the Async Events will be triggered for all instances that have them, so you can use an async function in one instance, and have the Asynchronous Event that deals with the reply in another one, or even various other ones. You can go here for more information on how the Asynchronous event works - Advanced Use: Asynchronous Events.

HTTP

Below you can find a list of the Async http functions available in GameMaker: Studio:

  1. http_request
  2. http_get
  3. http_get_file
  4. http_post_string

Cross Domain Issues

Please note that the above http_ functions may not function as expected due to cross domain security issues. This means that requests to your server or attempts to load resources from across domains are blocked and may appear to return blank results or 404 errors. One of the ways you can get around this is to have some server side PHP which allows certain domains to access your server (this is also a way to protect your resources and block servers that are not included in the PHP allow list).

The following is an example of the code you can use for this:

$http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "http://127.0.0.1:51268")
{
header('Access-Control-Allow-Origin: *');
}

Dialogues

Previous versions of GameMaker had pop-up dialogues that blocked the runner while waiting for a response from the user. However most modern devices do not like this and will interpret the runner stopping as an error and close the app. To prevent this GameMaker: Studio has async equivalents of these functions that fulfill the same purpose as previous versions, but do not block the game runner at any time, meaning that when called the game will run as normal in the background while the user responds to the shown dialogue. Once the user has responded, a Dialogs Asynchronous Event will be called so that you can deal with the results.

Below is a list of all the available asynchronous dialogue functions:

  1. get_login_async
  2. show_message_async
  3. show_question_async
  4. get_string_async
  5. get_integer_async

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_integer_async

Request an integer input from the user.

Syntax:

get_integer_async(string, default);

Argument | Description
String | The message to show in the dialog.
default | The default value.

Returns: Real

Description

This function opens a window and displays message as well as a space for the user to input a value (which will contain the supplied default value to start with). This is an asynchronous function, and as such GameMaker: Studio does not block the device it is being run on while waiting for answer, but rather keeps on running events as normal. Once the user has typed out their string and pressed the "Okay" button, an asynchronous Dialog event is triggered which, for the duration of that event only, will have a ds_map stored in the variable async_load.

This map will contain the three keys, "id", "status", and "value". "id" is the value that was returned by the function when called, the "status" will be either true for the "Okay" button being pressed, or false if the message was cancelled (where applicable as not all target platforms permit messages to be cancelled). Finally "value" will return the integer that the user input (or 0 if none was supplied).

Extended Example:

The left mouse press event (for example) of the object that is showing the message would have the following code:

msg = get_integer_async("How old are you?", 0);

The above will show a message requesting that the user input a string and press "Okay". The function id is stored in the variable "msg" and will be used in the asynchronous Dialogs event as shown below:

var i_d = ds_map_find_value(async_load, "id");
if i_d == msg
{
if ds_map_find_value(async_load, "status")
{
global.Age = ds_map_find_value(async_load, "value");
}
}

The above code checks the "id" key of the returned ds_map against the value stored in the variable "msg". If they are the same, it then checks to see if "Okay" was pressed (rather than the window being closed/cancelled) and if it returns true it then sets a global variable from the integer returned.

Back: Asynchronous Functions
Next: http_request

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_login_async

An asynchronous function that returns the username and password.

Syntax:

get_login_async(name, password);

Argument | Description
username | The default user name
password | The default password

Returns: Real

Description

This function opens a window that asks the user to input a username and password. These arguments can be set as an empty string or you can store previously entered values to use if you wish. This is an asynchronous function, and as such GameMaker: Studio does not block the device it is being run on while waiting for answer, but rather keeps on running events as normal. Once the user has input the details and pressed the "Okay" button, an asynchronous User Interaction event is triggered which, for the duration of that event only, will have a ds_map stored in the variable async_load.

This map will contain the two keys, "username" and "password", with the corresponding user input stored in each. As it is a ds_map that has been created, this can then be used, for example, by the json_encode function ready to be sent to a server or written to a file on the chosen device.

It is worth noting that this function will return an index number for the ds_map created which can then be checked in the corresponding event so that you can "target" a specific ds_map should you be expecting more than one async map to be returned (perhaps from some other function). Outside of the asynchronous events, the async_load ds_map will return an "id" value of -1.

Extended Example:

The create event (for example) of the object that is controlling the login of our user would have the following code:

ini_open("Profile.ini");
u = ini_read_string("User","0","");
p = ini_read_string("User","1","");
ini_close();
login = get_login_async(u,p);

The above code opens an ini file (or creates one if it doesn't exist) and gets the name and password stored in that file. If they do not exist, then the default of an empty string ("") is returned. These values are then used in get_login_async() to ask the user for their username and password details, with the request index being stored in the variable "login". Note that while waiting for the user to give the necessary information the game and its events will continue to run as normal.

Now that the asynchronous code has been fired off, we need to check for the return value in the asynchronous event for Dialogs in the following way:

if ds_map_find_value(async_load, "id") == login
{
u = ds_map_find_value(async_load, "username");
p = ds_map_find_value(async_load, "password");
}

The above code checks the "id" key of the async_load ds_map and if it holds the same value as that stored in the "login" variable, the map details are then read into the corresponding variables which you can then store or use to check against database values etc...

Back: Asynchronous Functions
Next: show_message_async

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_string_async

Request a string input from the user.

Syntax:

get_string_async(string, default);

Argument | Description
String | The message to show in the dialog.
default | The default string.

Returns: Real

Description

This function opens a window and displays message as well as a space for the user to input a string (which will contain the supplied default string to start with). This is an asynchronous function, and as such GameMaker: Studio does not block the device it is being run on while waiting for answer, but rather keeps on running events as normal. Once the user has typed out their string and pressed the "Okay" button, an asynchronous Dialog event is triggered which, for the duration of that event only, will have a ds_map stored in the variable async_load.

This map will contain the three keys, "id", "status", and "result". "id" is the value that was returned by the function when called, the "status" will be either true for the "Okay" button being pressed, or false if the message was cancelled (where applicable as not all target platforms permit the message to be cancelled). Finally "result" will return the string that the user input (or an empty string "" if none was supplied).

Extended Example:

The left mouse press event (for example) of the object that is showing the message would have the following code:

msg = get_string_async("What's your name?","Anon");

The above will show a message requesting that the user input a string and press "Okay". The function id is stored in the variable "msg" and will be used in the asynchronous Dialogs event as shown below:

var i_d = ds_map_find_value(async_load, "id");
if i_d == msg
{
if ds_map_find_value(async_load, "status")
{
if ds_map_find_value(async_load, "result") != ""
{
global.Name = ds_map_find_value(async_load, "result");
}
}
}

The above code checks the "id" key of the returned ds_map against the value stored in the variable "msg". If they are the same, it then checks to see if "Okay" was pressed (rather than the window being closed/cancelled) and if it returns true it then checks the "result" of a string to make sure that no empty strings were returned before setting a global variable.

Back: Asynchronous Functions
Next: get_integer_async

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


http_get

This function retrieves information from the supplied URL.

Syntax:

http_get(url);

Argument | Description
url | The web address of the server that you wish to get information from

Returns: Real

Description

With this function, you connect to the specified URL in order to retrieve information. As this is an asynchronous function, GameMaker: Studio will not block while waiting for a reply, but will keep on running unless it gets callback information. This information will be in the form of a string and will trigger an Async Event in any instance that has one defined in their object properties. You should also note that HTTP request parameters (the bits sometimes "tacked on" to the end of a URL when you submit a form on a web page) are perfectly acceptable when using this function, for example:

http_get("http://www.YoYoGames.com/logon?username="+name);

will pass the string held in the variable "name" to the server as well a retrieve the data from that URL. So, essentially, any time a simple, short piece of data needs to be passed from the client to the server, this would be reasonable choice as the function to use.

This function will generate multiple "call backs" which are picked up by any HTTP Events. These will generate a ds_map (more commonly known as a "dictionary") that is exclusive to this event and is stored in the special variable async_load. This ds_map will contain different values depending on whether there is data being returned or not. For example, if you have requested a file, the event will trigger multiple times as each packet of data is received so that you can show a progress bar, for example. The general structure for the ds_map will be as follows:

  1. id: The ID which was returned from the command. If you fire off a series of http_ requests then you need to know which one you are getting the reply to, and so you would use this value to compare to the value you stored when you originally sent the request to find the right one.

  2. status: Returns a value of less than 0 for an error, 0 for complete and 1 for receiving packets (see below for more details).

  3. result: The data received (string only).

  4. url: The complete URL you requested.

  5. http_status: The raw http status code (if available). This returns the standard web status code for most browsers, eg: 304 for "Not Modified" or 204 for "No Content", etc...

If there are multiple packets being returned to your game, the callback "status" key will return 1, in which case the ds_map will have the following additional keys:

  1. "contentLength": This is the size of file that the web server has said you should expect to receive (may be -1 if the server does not return this data).

  2. "sizeDownloaded": The size of the data that has already been downloaded.

NOTE: You should be aware that due to XSS protection in browsers, requests to and attempts to load resources from across domains are blocked and may appear to return blank results. Please see the section on Cross Domain Issues for further details.

Extended Example:

The http_get function can be called from any event, and since it is asynchronous the callback can be almost instantaneous or could take several seconds. Calling the function is simple and would look something like this:

get = http_get("http://www.MacSweeneyGames.com/logon?username=" + name);

The above code will pass the string held in the variable "name" to the given server as well as retrieve the data from that URL, triggering an Async Event which will contain the async_load ds_map (the async_load map index will be stored in the variable "get" so you can check for the correct callback). The Async Event triggered would be the HTTP sub-event, and in that event you would have the following:

if ds_map_find_value(async_load, "id") == get
{
if ds_map_find_value(async_load, "status") == 0
{
r_str = ds_map_find_value(async_load, "result");
}
else
{
r_str = "null";
}
}

The above code will first check the id of the ds_map that has been created, then check the status of the callback. If the value is equal to 0 (signalling success) the result from the callback will then be stored in a variable for future use, otherwise the variable will be set to a default value (in this case "null").

Back: Asynchronous Functions
Next: http_get_file

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


http_get_file

This function retrieves a file from the supplied URL.

Syntax:

http_get_file(url, local_target);

Argument | Description
url | The web address of the server that you wish to get file from
local_target | The local storage area target directory to store the file in

Returns: Real

Description

With this function, you can connect to the specified URL in order to retrieve information in the form of a file. As this is an asynchronous function, GameMaker: Studio will not block while waiting for a reply, but will keep on running unless it gets callback information. This information will be in the form of a string and will trigger an Async Event in any instance that has one defined in their object properties.

This event will generate a "call back" which is picked up by any HTTP Events, in which case it will generate a ds_map (more commonly known as a "dictionary") that is exclusive to this event and is stored in the special variable async_load. This ds_map will contain different values depending on the data being returned, ie: the event will trigger multiple times as each packet of data is received so that you can show a progress bar, for example. The general structure for the ds_map will be as follows:

  1. id: The ID which was returned from the command. If you fire off a series of http_ requests then you need to know which one you are getting the reply to, and so you would use this value to compare to the value you stored when you originally sent the request to find the right one.

  2. status: Returns a value of less than 0 for an error, 0 for complete and 1 for receiving packets (see below for more details).

  3. result: The data received (string only).

  4. url: The complete URL you requested.

  5. http_status: The raw http status code (if available). This returns the standard web status code for most browsers, eg: 304 for "Not Modified" or 204 for "No Content", etc...

If there are multiple packets being returned to your game, the callback "status" key will return 1, in which case the ds_map will have the following additional keys:

  1. "contentLength": This is the size of file that the web server has said you should expect to receive (may be -1 if the server does not return this data).

  2. "sizeDownloaded": The size of the data that has already been downloaded.

NOTE: You should be aware that due to XSS protection in browsers, requests to and attempts to load resources from across domains are blocked and may appear to return blank results. Please see the section on Cross Domain Issues for further details.

Extended Example:

The http_get_file function can be called from any event, and since it is asynchronous the callback can be almost instantaneous or could take several seconds. Calling the function is simple and would look something like this:

file = http_get_file("http://www.macsweeneygames.com/downloads/upgrade.zip", "\Downloads\Upgrade.zip");

The above code will request a file from the given URL and set it to be downloaded to the local storage area, in the directory "Downloads" with the given file name (this does not have to be the same as the source file name). The async_load map index will be stored in the variable "file" so you can check for the correct callback in the Asynchronous Event, and if the save directory does not exist, it will be created. The Asynchronous Event triggered would be the HTTP sub-event, and in that event you would have something like the following:

if ds_map_find_value(async_load, "id") == file
{
var status = ds_map_find_value(async_load, "status");
if status == 0
{
var path = ds_map_find_value(async_load, "result");
var files = zip_unzip(path, "/NewContent/");
if files > 0
{
global.ExtraContent = true;
}
}
}

The above code will first check the id of the ds_map that has been created, then check the status of the callback. If the value is equal to 0 (signalling success) the result from the callback will then be used along with the zip_unzip() function to unzip the downloaded file to the given directory. If the unzip succeeds a global variable is set to true.

Back: Asynchronous Functions
Next: http_post_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


http_post_string

This function not only retrieves information from the supplied URL, but sends data as part of the retrieval request.

Syntax:

http_post_string(url, string);

Argument | Description
url | The web address of the server that you wish to get information from
string | The string you wish to send to the specified URL

Returns: Real

Description

In computing, a post request is used when the client needs to send data to the server as part of the retrieval request, such as when uploading a file or submitting a completed form, and the same is true of this function in GameMaker: Studio. In contrast to the http_get request method where only a URL is sent to the server, http_post_string() also includes a string that is sent to the server and may result in the creation of a new resource or the update of an existing resource or both. It should be noted that HTTP request parameters (the bits sometimes "tacked on" to the end of a URL when you submit a form on a web page) are perfectly acceptable when using this function too.

This event will generate a "call back" which is picked up by any HTTP Events, in which case it will generate a ds_map (more commonly known as a "dictionary") that is exclusive to this event and is stored in the special variable async_load. This ds_map will contain different values depending on whether there is data being returned or not. For example, if you have requested a file, the event will trigger multiple times as each packet of data is received so that you can show a progress bar, for example. The general structure for the ds_map will be as follows:

  1. id: The ID which was returned from the command. If you fire off a series of http_ requests then you need to know which one you are getting the reply to, and so you would use this value to compare to the value you stored when you originally sent the request to find the right one.

  2. status: Returns a value of less than 0 for an error, 0 for complete and 1 for receiving packets (see below for more details).

  3. result: The data received (string only).

  4. url: The complete URL you requested.

  5. http_status: The raw http status code (if available). This returns the standard web status code for most browsers, eg: 304 for "Not Modified" or 204 for "No Content", etc...

If there are multiple packets being returned to your game, the callback "status" key will return 1, in which case the ds_map will have the following additional keys:

  1. "contentLength": This is the size of file that the web server has said you should expect to receive (may be -1 if the server does not return this data).

  2. "sizeDownloaded": The size of the data that has already been downloaded.

NOTE: You should be aware that due to XSS protection in browsers, requests to and attempts to load resources from across domains are blocked and may appear to return blank results. Please see the section on Cross Domain Issues for further details.

Extended Example:

The http_post_string function can be called from any event, and since it is asynchronous the callback can be almost instantaneous or could take several seconds. Calling the function is simple and would look something like this:

var str = "name=" + global.player_name + "&score=" + string(global.player_score);
post = http_post_string("http://www.angusgames.com/game?game_id=" + string(global.game_id), str);

The above code sends a retrieval request to the specified URL with the given parameters as well as sending the additional data (player name and score in URL-encoded form) stored in the variable str. This will trigger all defined asynchronous Http Events if a callback is received, and you can check the "id" returned against that stored in the variable post to make sure that you run the correct code should you have used various http_post_string() functions. The following example code shows how this would be done:

var r_str = "null";
if ds_map_find_value(async_load, "id") == post
{
if ds_map_find_value(async_load, "status") == 0
{
r_str = ds_map_find_value(async_load, "result");
}
}

The above code will first check the id of the ds_map that has been created, then check the status of the callback. If the value is equal to 0 (signalling success) the result from the callback will then be stored in a variable for future use, otherwise the variable will simply hold a default value (in this case "null").

Back: Asynchronous Functions
Next: get_login_async

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


http_request

This function retrieves information from the supplied URL.

Syntax:

http_request(url, method, header_map, body);

Argument | Description
url | The web address of the server that you wish to get information from
method | The request method (normally "POST" or "GET", but all methods are supported)
header_map | A ds_map with the required header fields
body | The data to be transmitted following the headers (can be a binary buffer handle)

Returns: Real

Description

With this function, you can create an HTTP header request to define the operating parameters of an HTTP transaction, which can be used for many things like (for example) authentication via HTTP headers if you use RESTful APIs. The function requires the full IP address of the server to request from as well as the type of request to make (as a string, see the note below): "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "OPTIONS", or "CONNECT". You will also need to supply a ds_map of key/value pairs (as strings, where the key is the header field and the value is the required data for the header), and the final argument is an optional data string that you can add to the request, and if it's not needed then it can be either 0 or an empty string "". Note that you can also send a buffer (see the section on Buffers for more details), in which case the last argument would be the "handle" of the buffer to send.

This event will generate a "call back" which is picked up by any HTTP Events, in which case it will generate a ds_map (more commonly known as a "dictionary") that is exclusive to this event and is stored in the special variable async_load. This ds_map has the following two keys related to the request function:

  1. id: The ID which was returned from the command. If you fire off a series of http_ requests then you need to know which one you are getting the reply to, and so you would use this value to compare to the value you stored when you originally sent the request to find the right one.

  2. response_headers: If this has a value greater than or equal to 0, it holds a ds_map that contains the HTTP headers returned with the response to the HTTP request.

NOTE: HTTP headers normally follow the format "key:value", but since GMS creates these pairs for you from the ds_map, there is no need to include the colon ":" in your map key or value strings.

NOTE: You should be aware that due to XSS protection in browsers, requests to and attempts to load resources from across domains are blocked and may appear to return blank results. Please see the section on Cross Domain Issues for further details.

Example:

var map = ds_map_create();
ds_map_add(map, "Host", "225.0.0.97:3000");
ds_map_add(map, "Connection", "keep-alive");
ds_map_add(map, "Content-Length", "169");
ds_map_add(map, "Cache-Control", "max-age=0");
ds_map_add(map, "Authorization", "Basic eW95b19hZG1pbjpjNG5lZmllbGQ=");
ds_map_add(map, "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
ds_map_add(map, "User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
ds_map_add(map, "Content-Type", "application/x-www-form-urlencoded");
ds_map_add(map, "Accept-Encoding", "gzip,deflate,sdch");
ds_map_add(map, "Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6");
ds_map_add(map, "Cookie", "request_method=GET; _InAppPurchases_session=69bb6ef6eec2b");
var data="utf8=%E2%9C%93&authenticity_token=kPmS14DcYcuKgMFZUsN3XFfj3mhs%3D&product%5Bname%5D=CatchTheHaggis&product%5Bproduct_id%5D=http_test&commit=Create+Product";
request = http_request("http:225.0.0.97:3000/products", "POST", map, data);

The above code creates a ds_map with the relevant HTTP headers for the function, then creates a data string for use as this is a POST request. Finally the function is called, with it's ID value being stored in the variable "request" for checking in the HTTP asynchronous event.

Back: Asynchronous Functions
Next: http_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


show_message_async

Shows a message to the user.

Syntax:

show_message_async(string);

Argument | Description
String | The message to show to the user.

Returns: Real

Description

This function opens a window and displays the message you define in the function to the user. This is an asynchronous function, and as such GameMaker: Studio does not block the device it is being run on while waiting for answer, but rather keeps on running events as normal. Once the user has pressed the "Okay" button, an asynchronous Dialog event is triggered which, for the duration of that event only, will have a ds_map stored in the variable async_load.

This map will contain the two keys, "id" and "status", with "id" being the value that was returned by the function when called, and the "status" being either true for the "Okay" button being pressed, or false if the message was cancelled (where available as not all target platforms permit the cancelation of dialogues).

Extended Example:

The left mouse press event (for example) of the object that is showing the message would have the following code:

msg = show_message_async("You will now be taken to the store");

The above will show a message with the given string. The message id is stored in the variable "msg" and will be used in the asynchronous Dialogs event as shown below:

var i_d, stat;
i_d = ds_map_find_value(async_load, "id");
if i_d == msg
{
if ds_map_find_value(async_load, "status")
{
url_open("https://play.google.com/store");
}
}

The above code checks the "id" key of the returned ds_map against the value stored in the variable "msg". If they are the same, it then checks to see if the "Okay" button was pressed (rather than the window being closed/cancelled) and if it returns true it opens a url.

Back: Asynchronous Functions
Next: show_question_async

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


show_question_async

Shows a question to the user.

Syntax:

show_question_async(string);

Argument | Description
String | The question to ask to the user.

Returns: Real

Description

This function opens a window and displays the question you define in the function to the user. This is an asynchronous function, and as such GameMaker: Studio does not block the device it is being run on while waiting for answer, but rather keeps on running events as normal. The function has two buttons that show "Yes" and "No", and once the user has pressed one, an asynchronous Dialog event is triggered which, for the duration of that event only, will have a ds_map stored in the variable async_load.

This map will contain the two keys, "id", and "status". "id" is the value that was returned by the function when called, while the "status" will be either true or false for "Yes" and "No" respectively.

Extended Example:

The left mouse press event (for example) of the object that is showing the message would have the following code:

msg = show_question_async("Do you want to buy some armour for " + string(armour[0, 5]) + "coins?");

The above will show a question with the given string, requesting that the user press either "yes" or "No". The function id is stored in the variable "msg" and will be used in the asynchronous Dialogs event as shown below:

var i_d, stat;
i_d = ds_map_find_value(async_load, "id");
if i_d == msg
{
if ds_map_find_value(async_load, "status")
{
coins -= armour[0,5];
global.protection += armour[0,0];
}
}

The above code checks the "id" key of the returned ds_map against the value stored in the variable "msg". If they are the same, it then checks to see if one of the two buttons were pressed and if it returns true it will then deduct a value from a variable and add a value to a global variable too.

Back: Asynchronous Functions
Next: get_string_async

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Buffers

These functions can be used to read and write directly to the device buffer memory.

A binary buffer is a region of physical memory used to temporarily hold data while it is being moved from one place to another or manipulated in some way, for example you can use a buffer to hold packet data awaiting transmission over a network or for storing a packet that has been received over a network. GameMaker: Studio has a number of specific functions related to creating, modifying and loading/saving buffers, but before using them please note the following points:

  • When a buffer is created, it is automatically cleared and filled to 0.

  • The "size" argument of the buffer functions always refers to the size in bytes of the buffer.

  • The "Alignment" argument refers to how data is stored within a buffer. If your alignment is set to say, 4, and you write a single piece of data which is 1 byte in size then do a buffer_tell, you'll get an offset of 1. However, if you write another piece of data, also 1 byte in size, then do a buffer_tell, you'll get an offset of 5 as the alignment has "padded" the data to that size. Alignment only affects where things are written to, so if you do a buffer_tell after you write something, it'll return the current write position which immediately follows the data you've written. Note, however, that if you then write another piece of data, internally the buffer will move the write position along to the next multiple of the alignment size before actually writing the piece of data.

  • When dealing with "offset", this is the value in bytes to offset the data by within the given buffer. So if your buffer is 2 byte aligned and you want to skip the first 4 aligned places, you would have an offset of 2 * 4 bytes.

  • Some of the buffer functions also create a new buffer (like buffer_load for example). Remember that these buffers will also need to be removed from memory when not in use using the buffer_delete function.

  • The memory used for creating buffers is system memory so even when the game doesn't have focus, any data stored in a buffer should be safe, however if the app is closed or re-started then it will be lost.

The following pages explain how buffers work within the context of GameMaker: Studio and contain a couple of code examples for those users that are unsure of how to use them:

  1. Using Buffers
  2. Buffer Examples

The following functions exist for you to use with binary buffers in your games:

  1. buffer_create
  2. buffer_create_from_vertex_buffer
  3. buffer_create_from_vertex_buffer_ext
  4. buffer_delete
  5. buffer_read
  6. buffer_write
  7. buffer_fill
  8. buffer_seek
  9. buffer_tell
  10. buffer_peek
  11. buffer_poke
  12. buffer_save
  13. buffer_save_ext
  14. buffer_save_async
  15. buffer_load
  16. buffer_load_ext
  17. buffer_load_async
  18. buffer_async_group_begin
  19. buffer_async_group_option
  20. buffer_async_group_end
  21. buffer_copy
  22. buffer_copy_from_vertex_buffer
  23. buffer_get_type
  24. buffer_get_alignment
  25. buffer_get_address
  26. buffer_get_size
  27. buffer_get_surface
  28. buffer_set_surface
  29. buffer_resize
  30. buffer_sizeof
  31. buffer_md5
  32. buffer_sha1
  33. buffer_base64_encode
  34. buffer_base64_decode
  35. buffer_base64_decode_ext

There are also two extra functions related to buffers that can be used to save and load game states (note that they require a buffer to have been created previously):

  1. game_load_buffer
  2. game_save_buffer

Finally, you can also use special Vertex Buffers to create your own custom primitives or models, etc... You can find out more about these from the following section of the manual:

  1. Vertex Buffers

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Buffer Examples

This page has two examples of using buffers to help understand how to use them.

Making Checkpoints With A Buffer

A simple example of how a buffer can be used in any GameMaker: Studio game for any platform, is the function game_save_buffer. This function will take a "snapshot" of the current game state and save it to a pre-defined buffer, which can then be read from to load the game at that point again.

NOTE: This function is very limited and it is designed for the beginner to get a checkpoint system up and running quickly, but more advanced users may prefer to code their own system using the File functions, due to the fact that the game will not save any of the dynamic resources that you can create at run-time like data structures, surfaces, added backgrounds and sprites etc...

The first thing we need to do is create a new object to control the saving and loading, so you would make one and give it a Create Event. In this event, you could place the following code:

SaveBuffer = buffer_create(1024, buffer_grow, 1);
StateSaved = false;

The first line creates a grow buffer (since we don't know the final size of the saved data) of 1024 bytes and aligned to 1 byte. A variable is then created to check against and see if the game has been saved or not (this will be used for loading).

Next we would add a Keypress Event (for example) in which we will save the current game state to the created buffer:

StateSaved = true;
buffer_seek(SaveBuffer, buffer_seek_start, 0);
game_save_buffer(SaveBuffer);

The above will first set the control variable to true (so that this is saved when we save the game to the buffer) and then seek to the start of the buffer before writing the current save state into it. Why do we use buffer_seek? Well, as mentioned on the Using Buffers page, you read and write to a buffer from the last position that data was added to. This means that if you don't set the buffer tell back to the start then when you save you will be adding the data into the buffer at the current buffer read/write position, so we use the function buffer_seek to move the tell to the buffer start.

We have now saved the current game state to a buffer. The next step would be to code how to load it, probably in another Keypress Event:

if StateSaved
{
buffer_seek(SaveBuffer, buffer_seek_start, 0);
game_load_buffer(SaveBuffer);
}

The game will then be loaded at the end of the event in which you place the above code.

NOTE: This is only for use in the same room, and not for generating complete saved games for after your game has been closed or restarted!

The final thing to add to the controller object is a "clean up" code. Buffers are stored in memory and as such if you do not clean up when you are finished with them, you can get memory leaks that will eventually lag and crash your game. So you would probably add a Room End Event (from the Other event category) with:

buffer_delete(SaveBuffer);

This object can now be placed into a room and on a key press save and load the room state from a buffer.

Networking Buffers

When working with the GameMaker: Studio networking functions, you have to use buffers to create the datapacket that is being sent over the network connection. This example intends to show how this is done, but due to the scope of the networking possibilities, it is only designed to show how to use the buffers themselves, and not the full networking system (there is a Demo file included with GameMaker: Studio that shows this).

The first thing we will show is the creation and use of a buffer for the client side of the network connection. This buffer will be used to create small data packets that can then be sent to the server, so in the Create Event of an instance we would assign a buffer like this:

send_buff = buffer_create(256, buffer_grow, 1);

We make the buffer small (256bytes) as it is not intended for holding large amounts of data, we make it a grow buffer to ensure no errors should we need to add more data to be sent at any time, and the alignment is set to one for convenience.

Now, let's say that we want our client to send data to the server. For that we need to create a buffer "packet", and in this example we are going to send a Key Press Event, like when the player presses Left Arrow to move around the game. To do this we write the necessary data to the buffer first then send it off:

buffer_seek(buff, buffer_seek_start, 0);
buffer_write(buff, buffer_u8, 1);
buffer_write(buff, buffer_s16, vk_left);
buffer_write(buff, buffer_bool, true);
network_send_packet(client, buff, buffer_tell(buff));

Before writing to the buffer we have set the "tell" to the start of the buffer as networking always takes the data from the start of a buffer. We then write the check value (this will be used by the server to determine the type of event to be processed), then the key being used, and then the state of the key (in this case true for pressed). This buffer is then sent as a data packet by the network function. Note that we do not send the whole buffer! We only send the data written, using the buffer_tell function to return the current read/write position of the buffer (remember that writing to the buffer moves the "tell" to the end of what has been written).

What about receiving the data on the server? The received data packet that must be written into the buffer on the server and then used to update the game. For that we would use the Networking Asynchronous Event in the network controller object of the server, as this simplified code below shows:

var buff = ds_map_find_value(async_load, "buffer");
if cmd == buffer_read(buff, buffer_u8);
{
key = buffer_read(buff, buffer_s16 );
key_state = buffer_read(buff, buffer_bool);
}

The asynchronous event will contain a special temporary ds_map (it is removed at the end of the event automatically) which contains different information depending on the type of incoming data from the network. In this case, we are assuming that the map has been checked and found to be a buffer data packet sent from a client. We now check the first piece of data that is in the buffer to see what kind of event has been sent - in this case the value "1" represents a key event, however when coding these things you should define constants to hold these values to simplify things - and then store the key being pressed and its state (true = pressed, false = released). This information would then be used to update all the clients with the new status of the sending client player.

NOTE: The buffer that is created from the ds_map is automatically removed at the end of the Network Asynchronous Event so there is no need to use buffer_delete here.

Back: Buffers
Next: Using Buffers

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_async_group_begin

Begin the definition of a buffer group for asynchronous saving.

Syntax:

buffer_async_group_begin(groupname);

Argument | Description
groupname | The name of the group (as a string).

Returns: N/A

Description

This function is called when you want to begin the saving out of multiple buffers to multiple files. The "groupname" is a string and will be used as the directory name for where the files will be saved, and should be used as part of the file path when loading the files back into the IDE later (using any of the buffer_load functions). This function is only for use with the buffer_save_async() function and you must also finish the save definition by calling buffer_async_group_end() function otherwise the files will not be saved out.

Note that for the console platforms (like PS4 for example), the "groupname" will be used as the save slot description, and using this function can help you avoid having the UI show for every file that is being saved out.

Example:

buffer_async_group_begin("SaveGame");
save1 = buffer_save_async(buff1, "Player_Save1.sav", 0, 16384);
save2 = buffer_save_async(buff2, "Player_Save2.sav", 0, 16384);
save3 = buffer_save_async(buff3, "Player_Save3.sav", 0, 16384);
save4 = buffer_save_async(buff4, "Player_Save4.sav", 0, 16384);
buffer_async_group_end();

The above code starts a buffer group then sets it to save out 4 files asynchronously. The group definition is then ended (at which point saving will begin).

Back: Buffers
Next: buffer_async_group_option

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_async_group_end

Ends the definition of a buffer save group and initiates the saving.

Syntax:

buffer_async_group_end();

Returns: Real

Description

This function finishes the definition of a buffer save group. You must have previously called the function buffer_async_group_begin() to initiate the group, then call the function buffer_save_async() for each file that you wish to save out. Finally you call this function, which will start the saving of the files.

Example:

buffer_async_group_begin("SaveGame");
save1 = buffer_save_async(buff1, "Player_Save1.sav", 0, 16384);
save2 = buffer_save_async(buff2, "Player_Save2.sav", 0, 16384);
save3 = buffer_save_async(buff3, "Player_Save3.sav", 0, 16384);
save4 = buffer_save_async(buff4, "Player_Save4.sav", 0, 16384);
buffer_async_group_end();

The above code starts a buffer group then sets it to save out 4 files asynchronously. The group definition is then ended (at which point saving will begin).

Back: Buffers
Next: buffer_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_async_group_option

Set various options for saving a buffer group asynchronously.

Syntax:

buffer_async_group_option(option, value);

Argument | Description
option | The option to set.
value | The value to set (can be string or real, depending on the option).

Returns: N/A

Description

With this function you can set some platform specific options for the buffer group being saved. The options available are as follows:

  • "subtitle" or "slottitle" - The value for this option would be a string, which will be shown to the user when managing their save data in the OS. This is only important when saving data, not when loading again.

  • "showdialog" - The value for this option is a boolean true or false. If set to true, when you save or load GameMaker: Studio will show the System UI, otherwise it will do a quicksave/quickload with no UI shown. You normally only need this if you're supporting multiple save slots to allow the user to pick a slot, but if you just support one slot per user, set this to false.

  • "savepadindex" - For this option you would specify the pad index of the player who is saving or loading and the system will write data to and read data from this player's save folder.

  • "saveslotsize" - This option requires that you specify the actual size in bytes you want to save (so you can do a buffer_seek and buffer_tell to get that, for example). Note that it is not obligatory to supply this value as all saves are pre-assigned a minimum space, which is normally about 10MB or so.

IMPORTANT - This function is currently only valid for the PlayStation target module. on all the other targets it will do nothing.

Example:

buffer_async_group_begin("save_folder_name");
buffer_async_group_option("showdialog", false);
buffer_async_group_option("slottitle", "Catch The Haggis Save");
buffer_async_group_option("subtitle", "All your haggis are saved here!");
save = buffer_save_async(buff, "Player_Save.sav", 0, 16384);
buffer_async_group_end();

The above code starts a buffer group then sets the group options before it sets 4 files to save asynchronously. The group definition is then ended (at which point saving will begin).

Back: Buffers
Next: buffer_async_group_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_base64_decode

Decode a base64 encoded string into a buffer.

Syntax:

buffer_base64_decode(string);

Argument | Description
string | The base64 encoded string to decode

Returns: Real

Description

With this function you can decode a base64 encoded string (created using the buffer_base64_encode function) into a buffer. This function will create the buffer (as a 1 byte aligned "grow" buffer") and return the unique index for the buffer which should be used in all further function calls.

NOTE: It's important that you remove any dynamically created resources like this from memory when you no longer need them to prevent memory leaks, so when you are finished with the buffer that you have created you should free it up again using buffer_delete.

Example:

ini_open("Save.ini");
buff = buffer_base64_decode(ini_read_string("Save", "Slot1", ""));
ini_close();

The above code will open an ini file and then read a string from it into the decode function. This function will return a buffer index, which is stored in the variable "buff", containing the data previously encoded and saved. The ini file is then closed.

Back: Buffers
Next: buffer_base64_decode_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_base64_decode_ext

Decode a base64 encoded string into a buffer at the given offset.

Syntax:

buffer_base64_decode_ext(buffer, string, offset);

Argument | Description
buffer | The index of the buffer to decode the string into.
string | The base64 encoded string to decode.
offset | The data offset value.

Returns: N/A

Description

With this function you can decode a base64 encoded string (created using the buffer_base64_encode() function) into a buffer. Unlike the function buffer_base64_decode(), this will not create a buffer for you, but rather you should already have created the buffer (see buffer_create), the id of which you would then use with this function. The "offset" is the position within the buffer to decode the given string (in bytes).

Example:

buff = buffer_create(16384, buffer_grow, 2);
ini_open("Save.ini");
var str = ini_read_string("Save", "Slot1", "");
buffer_base64_decode_ext(buff, str, 0);
ini_close();

The above code will create a buffer and store the unique id for it in the variable "buff", then open an ini file and read a string from it into the local variable "str". This string is then decoded into the newly created buffer before closing the ini file again.

Back: Buffers
Next: buffer_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_base64_encode

Encode a section of a buffer using base64

Syntax:

buffer_base64_encode(buffer, offset, size);

Argument | Description
buffer | The index of the buffer to use.
offset | The data offset value.
size | The size of the buffer.

Returns: String

Description

This function will convert the data from the given buffer into a base64 format encoded string. This is a commonly used encoding scheme that is often used for any media that needs to be stored or transferred over the internet as text, and renders the output unreadable to the human eye. To use this you need to specify an already created buffer, the offset value (which is the point within the buffer at which you wish to start encoding) as well as the size, in bytes, of the buffer memory to encode.

Example:

var b_str = buffer_base64_encode(buff, 0, buffer_get_size(buff))

The above code will create encode the full data stored in the buffer indexed by the variable "buff", and store the returned string in the local variable "b_str".

Back: Buffers
Next: buffer_base64_decode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_copy

Copy all or part of one buffer to another.

Syntax:

buffer_copy(src_buffer, src_offset, size, dest_buffer, dest_offset);

Argument | Description
src_buffer | The index of the buffer to copy from.
src_offset | The data offset to start copying from (in bytes).
size | The size of the data to copy (in bytes).
dest_buffer | The index of the buffer to copy to.
dest_offset | The offset position to copy the data to (in bytes).

Returns: N/A

Description

This function can be used to copy a segment (or all) of the data stored in one buffer to another. When using two buffers and copying from one to the other, both buffers must have previously been created using the buffer_create function (for example), and you can specify a data offset (in bytes) for the start point of the data to be copied from the source buffer relative to the start of the buffer, as well as another data offset to define the position to copy the data to in the destination buffer.

NOTE: You cannot copy to the same buffer.

Example:

buffer_copy(buff1, 0, 2048, buff2, 2048);

The above code will copy the data stored in the buffer indexed in the variable "buff1", and then paste it into the buffer indexed in the variable "buff2", but offset by 2048 bytes.

Back: Buffers
Next: buffer_copy_from_vertex_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_copy_from_vertex_buffer

Copy all or part of a vertex buffer into a regular buffer.

Syntax:

buffer_copy_from_vertex_buffer(vertex_buffer, start_vertex, num_vertices, dest_buffer, dest_offset);

Argument | Description
vertex_buffer | The index of the vertex buffer to copy from.
start_vertex | The starting vertex.
num_vertices | The total number of vertices to use.
dest_buffer | The index of the buffer to copy to.
dest_offset | The offset position to copy the data to (in bytes).

Returns: N/A

Description

This function can be used to copy some (or all) of the vertex data stored in one vertex buffer into a previously created regular buffer. When copying from a vertex buffer into a regular buffer with this function, both buffers must have previously been created (using the vertex_create_buffer() and buffer_create functions, for example). You can specify the range of vertex data that you wish to copy into the buffer, where the start vertex can be anywhere between 0 and the number of vertices -1, and you can give the number of vertices from that point on to copy. You can use the function vertex_get_number() on the vertex buffer to get the total number of vertices stored. Finally you give the buffer index to copy the vertex data into, as well as a data offset to define the position to copy the vertex data to in the destination buffer.

Example:

var v_num = vertex_get_number(model_buff); buffer_copy_from_vertex_buffer(model_buffer, 0, v_num - 1, player_buffer, 0);

The above code will copy the vertex data stored in the vertex buffer indexed in the variable "model_buffer", and then paste it into the buffer indexed in the variable "player_buffer".

Back: Buffers
Next: buffer_get_type

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_create

Create a new buffer.

Syntax:

buffer_create(size, type, alignment)

Argument | Description
size | The size (in bytes) of the buffer.
type | The type of buffer to create (see the constants list below).
alignment | The byte alignment for the buffer

Returns: Real

Description

You use this function to allocate a portion of memory as a buffer in your game, with the function returning the unique buffer id that should be stored in a variable and used for all further function calls to the buffer. The buffer can then be used to store different types of data (specified when you write to the buffer using the buffer_write function, with the following constants being used to define the buffer type:

Constant | Description
buffer_fixed | A buffer of fixed size.
buffer_grow | A buffer that will "grow" dynamically as data is added
buffer_wrap | A buffer where the data will "wrap". When the data being added reaches the limit of the buffer size, the overwrite will be placed back at the start of the buffer, and further writing will continue from that point.
buffer_fast | Special "stripped" buffer that is extremely fast to read/write to. Can only be used with buffer_u8 data types, and must be 1 byte aligned.
buffer_vbuffer |

Apart from the buffer type, you will also have to set the byte alignment for the buffer. This value will vary depending on the data that you wish to store in the buffer, and in most cases a value of 1 is perfectly fine. However, be aware that for some operations a specific alignment is essential, and an incorrect alignment may cause errors (for further details on alignment see Buffers). The following is a general guide to show which values are most appropriate for each data type (when in doubt, use an alignment of 1):

  • Strings should be aligned to 1 byte.
  • Signed or unsigned 8bit integers can be aligned to any value, but note that for a fast buffer (see buffer_write) it must be aligned to 1.
  • Signed or unsigned 16bit integers should be aligned to 2 bytes.
  • Signed or unsigned 32bit integers should be aligned to 4 bytes
  • Floats of up to 16bits should be aligned to 2 bytes. (Not currently supported!)
  • Floats of up to 32bits should be aligned to 4 bytes.
  • Floats of up to 64bits should be aligned to 8 bytes.

NOTE: Byte alignment can be very important as the wrong choice may adversely affect performance.

NOTE: It's important that you remove any dynamically created resources like this from memory when you no longer need them to prevent memory leaks, so when you are finished with the buffer that you have created you should free it up again using buffer_delete.

Example:

player_buffer = buffer_create(16384, buffer_fixed, 2);

The above code allocates 16384 bytes of memory to a buffer and returns the index of that buffer, which is stored in the variable "player_buffer", for future use. The buffer is aligned to a two byte boundary.

Back: Buffers
Next: buffer_create_from_vertex_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_create_from_vertex_buffer

Create a new buffer using data from a vertex buffer.

Syntax:

buffer_create_from_vertex_buffer(vertex_buffer, type, alignment)

Argument | Description
vertex_buffer | The vertex buffer index to use.
type | The type of buffer to create (see the constants list below).
alignment | The byte alignment for the buffer

Returns: Real

Description

You use this function to allocate a portion of memory as a buffer in your game filled with the data from a previously created vertex buffer. The function returns a unique buffer id that should be stored in a variable and used for all further function calls to the buffer. The function takes the id for the vertex buffer to use (as returned by the function vertex_create_buffer(), for example) with the following constants being used to define the buffer type:

Constant | Description
buffer_fixed | A buffer of fixed size.
buffer_grow | A buffer that will "grow" dynamically as data is added
buffer_wrap | A buffer where the data will "wrap". When the data being added reaches the limit of the buffer size, the overwrite will be placed back at the start of the buffer, and further writing will continue from that point.
buffer_fast | Special "stripped" buffer that is extremely fast to read/write to. Can only be used with buffer_u8 data types, and must be 1 byte aligned.
buffer_vbuffer |

Apart from the buffer type, you will also have to set the byte alignment for the buffer. This value will vary depending on the data that you wish to store in the buffer, and in most cases a value of 1 is perfectly fine. However, be aware that for some operations a specific alignment is essential, and an incorrect alignment may cause errors (for further details on alignment see Buffers). The following is a general guide to show which values are most appropriate for each data type (when in doubt, use an alignment of 1):

  • Strings should be aligned to 1 byte.
  • Signed or unsigned 8bit integers can be aligned to any value, but note that for a fast buffer (see buffer_write) it must be aligned to 1.
  • Signed or unsigned 16bit integers should be aligned to 2 bytes.
  • Signed or unsigned 32bit integers should be aligned to 4 bytes
  • Floats of up to 16bits should be aligned to 2 bytes. (Not currently supported!)
  • Floats of up to 32bits should be aligned to 4 bytes.
  • Floats of up to 64bits should be aligned to 8 bytes.

NOTE: Vertex buffers are 1 byte aligned, but you can create the buffer with any alignment depending on how you want to treat the data, as the vertex data is simply a raw memory copy into the buffer.

NOTE: It's important that you remove any dynamically created resources like this from memory when you no longer need them to prevent memory leaks, so when you are finished with the buffer that you have created you should free it up again using buffer_delete. Also note that the vertex buffer used to create the new buffer is not removed from memory either and you should use the function vertex_delete_buffer() when it is no longer required.

Example:

player_buffer = buffer_create_from_vertex_buffer(model_buffer, buffer_grow, 1);

The above code allocates memory to a buffer then copies the data from the given vertex buffer into it, returning the index of the new buffer which is stored in the variable "player_buffer", for future use.

Back: Buffers
Next: buffer_create_from_vertex_buffer_ext


buffer_create_from_vertex_buffer_ext

Create a new buffer using data from a vertex buffer, specifying the number of vertices in the buffer to use.

Syntax:

buffer_create_from_vertex_buffer_ext(vertex_buffer, type, alignment, start_vertex, num_vertices)

Argument | Description
vertex_buffer | The vertex buffer index to use.
type | The type of buffer to create (see the constants list below).
alignment | The byte alignment for the buffer
start_vertex | The starting vertex.
num_vertices | The total number of vertices to copy.

Returns: Real

Description

You use this function to allocate a portion of memory as a buffer in your game filled with the data from a previously created vertex buffer. The function returns a unique buffer id that should be stored in a variable and used for all further function calls to the buffer. The function takes the id for the vertex buffer to use (as returned by the function vertex_create_buffer(), for example) with the following constants being used to define the buffer type:

Constant | Description
buffer_fixed | A buffer of fixed size.
buffer_grow | A buffer that will "grow" dynamically as data is added
buffer_wrap | A buffer where the data will "wrap". When the data being added reaches the limit of the buffer size, the overwrite will be placed back at the start of the buffer, and further writing will continue from that point.
buffer_fast | Special "stripped" buffer that is extremely fast to read/write to. Can only be used with buffer_u8 data types, and must be 1 byte aligned.
buffer_vbuffer |

Apart from the buffer type, you will also have to set the byte alignment for the buffer. This value will vary depending on the data that you wish to store in the buffer, and in most cases a value of 1 is perfectly fine. However, be aware that for some operations a specific alignment is essential, and an incorrect alignment may cause errors (for further details on alignment see Buffers). The following is a general guide to show which values are most appropriate for each data type (when in doubt, use an alignment of 1):

  • Strings should be aligned to 1 byte.
  • Signed or unsigned 8bit integers can be aligned to any value, but note that for a fast buffer (see buffer_write) it must be aligned to 1.
  • Signed or unsigned 16bit integers should be aligned to 2 bytes.
  • Signed or unsigned 32bit integers should be aligned to 4 bytes
  • Floats of up to 16bits should be aligned to 2 bytes. (Not currently supported!)
  • Floats of up to 32bits should be aligned to 4 bytes.
  • Floats of up to 64bits should be aligned to 8 bytes.

NOTE: Vertex buffers are 1 byte aligned, but you can create the buffer with any alignment depending on how you want to treat the data, as the vertex data is simply a raw memory copy into the buffer.

The final two arguments are used to specify the range of vertex data that you wish to copy into the newly created buffer. The start vertex can be anywhere between 0 and the number of vertices -1, and then you give the number of vertices from that point to copy. You can use the function vertex_get_number() on the vertex buffer to get the total number of vertices stored.

NOTE: It's important that you remove any dynamically created resources like this from memory when you no longer need them to prevent memory leaks, so when you are finished with the buffer that you have created you should free it up again using buffer_delete. Also note that the vertex buffer used to create the new buffer is not removed from memory either and you should use the function vertex_delete_buffer() when it is no longer required.

Example:

var v_num = vertex_get_number(model_buff); player_buffer = buffer_create_from_vertex_buffer(model_buffer, buffer_grow, 1, 0, v_num - 1);

The above code allocates memory to a buffer then copies the data of all vertices from the given vertex buffer into it, returning the index of the new buffer which is stored in the variable "player_buffer", for future use.

Back: Buffers
Next: buffer_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_delete

Delete a previously created buffer.

Syntax:

buffer_delete(buffer)

Argument | Description
buffer | The index of the buffer to delete.

Returns: N/A

Description

With this function you can delete a buffer previously have created using the function buffer_create from memory, releasing the resources used to create it and removing any data that it may currently contain.

NOTE: It's important to always remove any dynamically created resources from memory when you no longer need them to prevent memory leaks.

Example:

buffer_delete(player_buffer);

The above code will delete the previously created buffer with the id stored in the variable "player_buffer".

Back: Buffers
Next: buffer_read

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_exists

Checks to see if the input variable is a buffer ID or not.

Syntax:

buffer_exists(buffer)

Argument | Description
buffer | The index of the buffer to check.

Returns: Boolean

Description

This function can be used to check a variable to see if it holds a valid buffer ID value or not. If it does the function will return true otherwise it will return false.

Example:

if buffer_exists(buff)
{
buffer_delete(buff);
}

The above code checks to see if the variable "buff" holds a buffer ID and if it does, the buffer is deleted.

Back: Buffers
Next: buffer_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_fill

Writes data to a buffer.

Syntax:

buffer_fill(buffer, offset, type, value, size);

Argument | Description
buffer | The index of the buffer to fill.
offset | The data offset value (in bytes).
type | The type of data that is to be written to the buffer (see the list of constants here).
value | The data to write.
size | The size of the buffer (in bytes) that you wish to fill.

Returns: N/A

Description

This function can be used to fill a previously created buffer with a given data type and value. The data you fill the buffer with must be in agreement with the "type" argument of this function, meaning that you can't try to fill with a string and use the unsigned 16bit integer type, for example. The type constants are the same as those used by the buffer_read and buffer_write functions. The "size" is the size of the buffer (in bytes) that you wish to fill, while the offset is the offset value (also in bytes) from the start of the buffer to start the fill from.

Example:

map_buffer = buffer_create(16384, buffer_fixed, 0);
buffer_fill(map_buffer, 0, buffer_u16, 0, 16384);

The above code finds the start of the buffer with the id stored in the variable "buff" them writes a series of signed 16bit integer values to it.

Back: Buffers
Next: buffer_seek

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_get_address

Get the raw, aligned, buffer address.

Syntax:

buffer_get_address(buffer);

Argument | Description
buffer | The index of the buffer to use.

Returns: pointer

Description

With this function you can get the a pointer to the raw, aligned buffer address. This is primarily for use with extensions as you can pass this value through to them, allowing them to access the buffer data. Note that there are a few things you cannot do with the buffer when accessing from an extension:

  • You cannot free the memory.
  • You cannot resize the memory.
  • You cannot not write past the buffer address plus the buffer size (you can use the buffer_get_size function for this) or you will get an out of bounds error.

Example:

var b_address = buffer_get_address(buff_model);
var b_end_address = b_address + buffer_get_size(buff_model);

The above code will get the memory address of the buffer indexed in the variable "buff_model" and then get the memory address for the end of the buffer using the buffer_get_size() function, storing both values in local variables for further use.

Back: Buffers
Next: buffer_get_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_get_alignment

Get the byte alignment of the given buffer.

Syntax:

buffer_get_alignment(buffer);

Argument | Description
buffer | The index of the buffer to check.

Returns: Real

Description

With this function you can get the a byte alignment for the given buffer ID.

Example:

alignment = buffer_get_alignment(buff);

The above code will get the alignment of the buffer from the value indexed in the variable "buff" and store it in a variable.

Back: Buffers
Next: buffer_get_address

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_get_size

Get the size (in bytes) of the given buffer.

Syntax:

buffer_get_size(index);

Argument | Description
index | The index of the buffer to get the size of.

Returns: Real

Description

With this function you can get the size of the given buffer in bytes.

Example:

var temp_buff = buffer_create(buffer_get_size(buff), buffer_fixed, 0);

The above code will create a new buffer and store its index in the local variable "temp_buff", with size of this new buffer being the same as that of the buffer indexed in the variable "buff".

Back: Buffers
Next: buffer_get_surface

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_get_surface

Copy surface data to a buffer.

Syntax:

buffer_get_surface(buffer, surface, mode, offset, modulo);

Argument | Description
buffer | The index of the buffer to use.
surface | The index of the surface to use.
mode | The data to get from the surface (see the list of constants below).
offset | The data offset value.
modulo | The offset from the end of the line to the start of the next

Returns: N/A

Description

With this function you can write the information from a surface to a given buffer. The buffer must have been created previously and should be a 1byte aligned grow buffer of an approximate size (in bytes) of the surface you are going to write. You can choose the copy "mode" for the data being stored which is set by the constants listed below, as well as the offset and modulo values. Both offset and modulo are byte values, with the offset defining the start position within the buffer and modulo being the number of bytes left at the end of every line (for storing additional data). Note that the function writes each pixel of the surface to the buffer using a BGRA formatting on the Windows target, but on other targets it may be different depending on the OS or even the device.

Constant | Description
0 | Copies all data from the surface.

Example:

buffer_get_surface(buff, application_surface, 0, 0, 0);

The above code will copy the data stored in the application surface to the buffer indexed in the variable "buff" with no offset or modulo values.

Back: Buffers
Next: buffer_set_surface

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_get_type

Get the type of buffer.

Syntax:

buffer_get_type(buffer);

Argument | Description
buffer | The index of the buffer to check.

Returns: Constant

Description

With this function you retrieve the type of buffer that is beinf referenced by a buffer ID value. The return value will be one of the following constants:

Constant | Description
buffer_fixed | A buffer of fixed size.
buffer_grow | A buffer that will "grow" dynamically as data is added
buffer_wrap | A buffer where the data will "wrap". When the data being added reaches the limit of the buffer size, the overwrite will be placed back at the start of the buffer, and further writing will continue from that point.
buffer_fast | Special "stripped" buffer that is extremely fast to read/write to. Can only be used with buffer_u8 data types, and must be 1 byte aligned.
buffer_vbuffer |

Example:

type = buffer_get_type(buff);

The above code will get the type of buffer from the value indexed in the variable "buff" and store it in a variable.

Back: Buffers
Next: buffer_get_alignment

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_load

Load a previously saved buffer.

Syntax:

buffer_load(filename);

Argument | Description
filename | The name of the file to load from.

Returns: real

Description

This function will load the buffer data that was previously saved using the buffer_save functions into a new buffer. This new buffer is created by the function as a "grow" buffer (see here) with a byte alignment of 1, and the new buffer id is returned. This ID should be stored in a variable and used in all further function calls to this buffer.

NOTE: It's important that you remove any dynamically created resources like this from memory when you no longer need them to prevent memory leaks, so when you are finished with the buffer that you have created you should free it up again using buffer_delete.

Example:

player_buffer = buffer_load("Player_Save.sav");

The above code will load a previously saved buffer into memory, creating a new buffer. The index of this new buffer is stored in the variable "player_buffer".

Back: Buffers
Next: buffer_load_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_load_async

Load the contents of a file into a buffer asynchronously.

Syntax:

buffer_load_async(buffer, filename, offset, size);

Argument | Description
buffer | The index of the buffer to load.
filename | The name of the file to load.
offset | The offset within the buffer to load to (in bytes).
size | The size of the buffer area to load (in bytes).

Returns: Real

Description

With this function you can load a file that you have created previously using the buffer_save function (or any of the other functions for saving buffers) into a buffer. The "offset" defines the start position within the buffer for loading (in bytes), and the "size" is the size of the buffer area to be loaded from that offset onwards (also in bytes).

The function returns a unique ID value which can then be used to check the asynchronous event async_load ID value, as shown in the extended example below. The async_load map in the event will have the following two key/value pairs:

  1. "id": the ID of the async function as returned by the save function.
  2. "status": will return true if the data was saved/loaded correctly, and false otherwise.

Extended Example:

The buffer_load_async() function can be called from any event, and since it is asynchronous the callback can be almost instantaneous or could take several seconds. Calling the function is simple and would look something like this:

loadid = buffer_load_async(buff, "Player_Save.sav", 0, 16384);

The above code loads the contents of the file "Player_Save.sav" to the given buffer, storing the ID of the function call in the variable "loadid". When the load is complete, the asynchronous Save/Load event will be triggered and you can parse the async_load map for the correct ID of the function, like this:

if ds_map_find_value(async_load, "id") == loadid
{
if ds_map_find_value(async_load, "status") == false
{
show_debug_message("Load failed!");
}
}

The above code will first check the id of the ds_map that has been created, then check the status of the callback, posting a debug message if there has been any issues.

Back: Buffers
Next: buffer_async_group_begin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_load_ext

Load the contents of a previously saved buffer into a buffer at the given position.

Syntax:

buffer_load_ext(buffer, filename, offset);

Argument | Description
buffer | The index of the buffer to load into.
filename | The name of the file to load from.
offset | The offset within the buffer to load to (in bytes).

Returns: N/A

Description

This function will load the buffer data that was previously saved using the buffer_save functions into an already created buffer. You give the id of the previously created buffer to load into, then the saved buffer file to load, and finally the offset from the start of the buffer (in bytes) that you wish to load the data to.

Example:

var pos = buffer_seek(player_buffer, buffer_seek_end, 0);
buffer_load(player_buffer, "Data_Save.sav", pos);

The above code will first get the position of the end of the buffer indexed in the variable "player_buffer" and then loads the data from the given into that position (note that this example will only work with "grow" or "wrap" buffer types).

Back: Buffers
Next: buffer_load_async

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_md5

Create an md5 hash for the given buffer.

Syntax:

buffer_md5(buffer, offset, size);

Argument | Description
buffer | The index of the buffer to use.
offset | The data offset value.
size | The size of the buffer.

Returns: String

Description

In cryptography, MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value and has been employed in a wide variety of security applications. It is also commonly used to check the integrity of data. This function will take the input data from a given buffer (or part of the buffer) and return the 32-character hexadecimal MD5 hash that is unique to that data. In this way you can generate a secure key which can be stored and used to check the integrity of the information being sent to (or received from) an external server (for example). When applying this to buffers using this function you must specify the buffer id of the buffer to use, then an offset value (in bytes) for where to begin, and then a size (again in bytes) for the region to be hashed.

Example:

check_string = buffer_md5(buff, 0, buffer_get_size(buff));

The above code will create an md5 hash for the full data stored in the buffer indexed by the variable "buff", and store the returned hash in the variable "check_string".

Back: Buffers
Next: buffer_sha1

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_peek

Read data from a buffer at the given position.

Syntax:

buffer_peek(buffer, offset, type);

Argument | Description
buffer | The index of the buffer to use.
offset | The offset position (in bytes) within the buffer to read the given data from.
type | The type of data that is to be read from the buffer (see the list of constants here).

Returns: Real/String

Description

With the buffer_read function, you can read data from the given buffer at the current "seek" position, with each piece of data being read advancing this position by the bytes being read or written. However, it may be necessary for you to read a given piece of data without wanting to change the current seek position, and that's when you would use this function. You simply supply the function with a buffer id, and then an offset position (from the buffer start) within that buffer to read from, as well as the data type that you are wanting to read.

NOTE: Using the incorrect data type for the data being read will result in erroneous values!

Example:

var red = buffer_peek(buff, 1, buffer_u8);
var green = buffer_peek(buff, 2, buffer_u8);
var blue = buffer_peek(buff, 3, buffer_u8);
image_blend = make_colour_rgb(red, green, blue);

The above code will get three values from three different positions within the buffer indexed in the variable "buff" and then use those values to set the image blend of the instance.

Back: Buffers
Next: buffer_poke

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_poke

Add data to a buffer at a specific position.

Syntax:

buffer_poke(buffer, offset, type, value);

Argument | Description
buffer | The index of the buffer to use.
offset | The offset position (in bytes) within the buffer to write the given data to.
type | The type of data that is to be written to the buffer (see the list of constants here).
value | The data to add to the buffer, in accordance with the type specified.

Returns: N/A

Description

With the buffer_write function, you can write data to the given buffer at the current "seek" position, with each piece of data advancing this position by the bytes being written or read. However, it may be necessary for you to change a given piece of data without wanting to change the current seek position, and that's when you would use this function. You simply supply the function with a buffer index, and then the offset position from the buffer start (in bytes) within that buffer to write to, as well as the data type and the value to be written.

Example:

buffer_poke(buff, 3, buffer_u8, colour_get_blue(image_blend));

The above code will add the blue component value of the colour used for the image blend into the buffer indexed in the variable "buff", at the third position in the buffer and as an unsigned 8bit value.

Back: Buffers
Next: buffer_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_read

Read from a buffer.

Syntax:

buffer_read(buffer, type)

Argument | Description
buffer | The index of the buffer to read from.
type | The type of data that is to be read from the buffer (see the list of constants below).

Returns: Real/String

Description

This function can be used to read data from a previously created buffer. The return value will depend on the type of data that you are reading, which in itself is defined by the following constants:

Constant | Description
buffer_u8 | An unsigned, 8bit integer. This is a positive value from 0 to 255.
buffer_s8 | A signed, 8bit integer. This can be a positive or negative value from -128 to 127 (0 is classed as positive).
buffer_u16 | An unsigned, 16bit integer. This is a positive value from 0 - 65,535.
buffer_s16 | A signed, 16bit integer. This can be a positive or negative value from -32,768 to 32,767 (0 is classed as positive).
buffer_u32 | An unsigned, 32bit integer. This is a positive value from 0 to 4,294,967,295.
buffer_s32 | A signed, 32bit integer. This can be a positive or negative value from -2,147,483,648 to 2,147,483,647 (0 is classed as positive).
buffer_u64 | An unsigned 64bit integer. This can be a positive or negative value from -(263) to 263 - 1.
buffer_f16 | A 16bit float. This can be a positive or negative value within the range of +/- 65504. (Not currently supported!)
buffer_f32 | A 32bit float. This can be a positive or negative value within the range of +/-16777216.
buffer_f64 | A 64bit float. This can be a positive or negative value from -(252) to 252 - 1.
buffer_bool | A boolean value. Can only be either 1 or 0 (true or false)
buffer_string | A string of any size.
buffer_text | A string of any size, without the final null terminating character.

NOTE: Using the incorrect data type for the data being read will result in erroneous values!

Example:

var cmd = buffer_read(buff, buffer_S16 );

The above code reads from the buffer with the id stored in the variable "buff" a signed 16bit value into the local variable "cmd".

Back: Buffers
Next: buffer_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_resize

Resize a given buffer.

Syntax:

buffer_resize(buffer, newsize);

Argument | Description
buffer | The index of the buffer to change the size of.
newsize | The new size of the buffer (in bytes).

Returns: N/A

Description

With this function you can resize a given buffer to be the size (in bytes) that you specify.

Example:

if buffer_get_size(buff) < 16384
{
buffer_resize(buff, 16384);
}

The above code will check the size of the buffer indexed in the variable "buff" and if it is less than the given value, the buffer is resized.

Back: Buffers
Next: buffer_sizeof

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_save

Save the contents of a buffer to a file.

Syntax:

buffer_save(buffer, filename);

Argument | Description
buffer | The index of the buffer to save.
filename | The name of the file to save as.

Returns: N/A

Description

With this function you can save the contents of a buffer to a file, ready to be read back into memory using the buffer_load function.

Example:

buffer_save(buff, "Player_Save.sav");

Saves the current contents of the buffer with the id stored in the variable "buff" to a file.

Back: Buffers
Next: buffer_save_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_save_async

Save part of the contents of a buffer to a file asynchronously.

Syntax:

buffer_save_async(buffer, filename, offset, size);

Argument | Description
buffer | The index of the buffer to save.
filename | The name of the file to save as.
offset | The offset within the buffer to save from (in bytes).
size | The size of the buffer area to save (in bytes).

Returns: Real

Description

With this function you can save part of the contents of a buffer to a file, ready to be read back into memory using the buffer_load function (or any of the other functions for loading buffers). The "offset" defines the start position within the buffer for saving (in bytes), and the "size" is the size of the buffer area to be saved from that offset onwards (also in bytes). This function works asynchronously, and so the game will continue running while being saved. This function will trigger an Asynchronous Load/Save Event where you can check to ensure that the save has occurred correctly.

Note that you can save out multiple buffers in one by calling this function multiple times between calls to buffer_async_group_begin() and buffer_async_group_end() (see those functions for further information on this).

The function returns a unique ID value which can then be used to check the asynchronous event async_load ID value, as shown in the extended example below. The async_load map in the event will have the following two key/value pairs:

  1. "id": the ID of the async function as returned by the save function.
  2. "status": will return true if the data was saved/loaded correctly, and false otherwise.

Extended Example:

The buffer_save_async() function can be called from any event, and since it is asynchronous the callback can be almost instantaneous or could take several seconds. Calling the function is simple and would look something like this:

saveid = buffer_save_async(buff, "Player_Save.sav", 0, 16384);

The above code saves the contents of the buffer "buff" to the given save file, storing the ID of the function call in the variable "saveid". When the save is complete, the asynchronous Save/Load event will be triggered and you can parse the async_load map for the correct ID of the function, like this:

if ds_map_find_value(async_load, "id") == saveid
{
if ds_map_find_value(async_load, "status") == false
{
show_debug_message("Save failed!");
}
}

The above code will first check the id of the ds_map that has been created, then check the status of the callback, posting a debug message if there has been any issues.

Back: Buffers
Next: buffer_load

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_save_ext

Save part of the contents of a buffer to a file.

Syntax:

buffer_save_ext(buffer, filename, offset, size);

Argument | Description
buffer | The index of the buffer to save.
filename | The name of the file to save as.
offset | The offset within the buffer to save from (in bytes).
size | The size of the buffer area to save (in bytes).

Returns: N/A

Description

With this function you can save part of the contents of a buffer to a file, ready to be read back into memory using the buffer_load function. The "offset" defines the start position within the buffer for saving (in bytes), and the "size" is the size of the buffer area to be saved from that offset onwards (also in bytes).

Example:

buffer_save_ext(buff, "Player_Save.sav", 0, 16384);

Saves part of the current contents of the buffer with the id stored in the variable "buff" to a file.

Back: Buffers
Next: buffer_save_async

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_seek

Move to a point within the buffer for reading/writing.

Syntax:

buffer_seek(buffer, base, offset);

Argument | Description
buffer | The index of the buffer to use.
base | The base position to seek.
offset | The data offset value.

Returns: N/A

Description

This function can be used to move through a buffer, finding the start, the end, or a position relative to that which was last used when reading or writing data. The "offset" value is the offset (in bytes) to add to the given seek position, for example, if the base is relative and the offset is 4, then the buffer position will move along 4 bytes from its current position. Please note the following:

  • You can use negative values for the offset to seek back through the buffer as well as positive values.

  • If the buffer is of the "wrap" type and you offset past the end of the buffer, the seek position will also wrap.

  • If the buffer is not of the "wrap" type, the seek will clamp to the beginning or end of the buffer, even when the offset would take the seek outside of the buffer limits.

The following constants are accepted as the "base" argument for seeking to:

Constant | Description
buffer_seek_start | The start of the buffer
buffer_seek_relative | A position relative to the current read/write position
buffer_seek_end | The end of the buffer

Example:

buffer_seek(buff, buffer_seek_start, 0);
buffer_write(buff, buffer_s16, 0);
buffer_write(buff, buffer_s16, x);
buffer_write(buff, buffer_s16, y);

The above code finds the start of the buffer with the id stored in the variable "buff" them writes a series of signed 16bit integer values to it.

Back: Buffers
Next: buffer_tell

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_set_surface

Copy buffer data to a surface.

Syntax:

buffer_set_surface(buffer, surface, mode, offset, modulo);

Argument | Description
buffer | The index of the buffer to use.
surface | The index of the surface to use.
mode | The data to get from the buffer (see the list of constants below).
offset | The data offset value.
modulo | The offset from the end of the line to the start of the next

Returns: N/A

Description

With this function you can write the information from a buffer to a given surface. Both the buffer and the surface must have been created previously. You can choose the copy "mode" for the data being stored which is set by the constants listed below, as well as the offset and modulo values. Both offset and modulo are byte values, with the offset defining the start position within the buffer and modulo being the number of bytes that were left at the end of every line (for storing additional data) when the buffer was written to.

Constant | Description
0 | Copies all data from the buffer.

NOTE: This function is currently only available for the Windows and Playstation 4 target platforms.

Example:

buffer_set_surface(buff, application_surface, 0, 0, 0);

The above code will copy all the data stored in the buffer indexed in the variable "buff" to the application surface with no offset or modulo values.

Back: Buffers
Next: buffer_resize

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_sha1

Create a sha1 hash for the given buffer.

Syntax:

buffer_sha1(buffer, offset, size);

Argument | Description
buffer | The index of the buffer to use.
offset | The data offset value.
size | The size of the buffer.

Returns: String

Description

In cryptography, SHA-1 is a cryptographic hash function designed by the United States National Security Agency and is employed in several widely used applications and protocols like the popular Git where it is used to check for file changes. This function will take input data from a buffer and returns a 160 bit message digest in ASCII format. In this way you can generate a secure key which can be stored and used to check the integrity of the information being sent to (or received from) an external server (for example). When applying this to buffers using this function you must specify the buffer id of the buffer to use, then an offset value (in bytes) for where to begin, and then a size (again in bytes) for the region to be hashed.

Example:

check_string = buffer_sha1(buff, 0, buffer_get_size(buff));

The above code will create a sha1 hash for the full data stored in the buffer indexed by the variable "buff", and store the returned hash in the variable "check_string".

Back: Buffers
Next: buffer_base64_encode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_sizeof

Returns the size (in bytes) of a given buffer.

Syntax:

buffer_sizeof(type);

Argument | Description
type | The type of data that is to be checked (see the list of constants here).

Returns: N/A

Description

This function will return the size (in bytes) of any of the given data constants (listed here).

Example:

var b = 12 * buffer_sizeof(buffer_u8);
buff = buffer_create(b, buffer_fixed, 1);

The above code first calculates the size of the buffer to create by multiplying the unsigned 8bit data type by 12 (since we will be using the buffer to hold 12 pieces of data), and then uses this value to set a fixed buffer to the correct size.

Back: Buffers
Next: buffer_md5

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_tell

Get the current "seek" position within the buffer.

Syntax:

buffer_tell(buffer);

Argument | Description
buffer | The index of the buffer to use.

Returns: Real

Description

When you read or write data to a buffer using the buffer_read or buffer_write the current "seek" position is advanced by the bytes written or read, and with this function you can get the current "seek" position for use in other buffer functions. For example, if your buffer alignment is set to 4 bytes and you write a single piece of data which is 1 byte in size then do a buffer_tell, you'll get an return value of 1. However, if you write another piece of data, also 1 byte in size, then do a buffer_tell, you'll get a return value of 5 as the alignment has "padded" the data to that position.

Example:

var pos = buffer_tell(buff);
buffer_seek(buff, buffer_seek_start, 0);
val[0] = buffer_read(buff, buffer_S16);
val[1] = buffer_read(buff, buffer_S16);
val[2] = buffer_read(buff, buffer_S16);
buffer_seek(buff, buffer_seek_start, pos);

The above code will store the current seek position within the buffer indexed in the variable "buff" to the local variable "pos". The buffer seek position will then be set to the start of the buffer, and three pieces of data are read into an array, before finally re-setting the buffer seek position to where it was previously.

Back: Buffers
Next: buffer_peek

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


buffer_write

Writes data to a buffer.

Syntax:

buffer_write(buffer, type, value)

Argument | Description
buffer | The index of the buffer to write to.
type | The type of data that is to be written to the buffer (see the list of constants below).
value | The data to write.

Returns: N/A

Description

This function can be used to write data to a previously created buffer. The data you write must be in agreement with the "type" argument of this function, meaning that you can't try to write a string as an unsigned 16bit integer, for example. The following constants can be used to define the data type:

Constant | Description
buffer_u8 | An unsigned, 8bit integer. This is a positive value from 0 to 255.
buffer_s8 | A signed, 8bit integer. This can be a positive or negative value from -128 to 127 (0 is classed as positive).
buffer_u16 | An unsigned, 16bit integer. This is a positive value from 0 - 65,535.
buffer_s16 | A signed, 16bit integer. This can be a positive or negative value from -32,768 to 32,767 (0 is classed as positive).
buffer_u32 | An unsigned, 32bit integer. This is a positive value from 0 to 4,294,967,295.
buffer_s32 | A signed, 32bit integer. This can be a positive or negative value from -2,147,483,648 to 2,147,483,647 (0 is classed as positive).
buffer_u64 | An unsigned 64bit integer. This can be a positive or negative value from -(263) to 263 - 1.
buffer_f16 | A 16bit float. This can be a positive or negative value within the same range as a 16 bit signed integer. (Not currently supported!)
buffer_f32 | A 32bit float. This can be a positive or negative value within the same range as a 32 bit signed integer.
buffer_f64 | A 64bit float. This can be a positive or negative value from -(263) to 263 - 1.
buffer_bool | A boolean value. Can only be either 1 or 0 (true or false)
buffer_string | A string of any size, finalized with a null terminating character.
buffer_text | A string of any size, without the final null terminating character.

Example:

buffer_seek(buff, buffer_seek_start, 0);
buffer_write(buff, buffer_s16, 0);
buffer_write(buff, buffer_s16, x);
buffer_write(buff, buffer_s16, y);

The above code finds the start of the buffer with the id stored in the variable "buff" them writes a series of signed 16bit integer values to it.

Back: Buffers
Next: buffer_fill

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Using Buffers

Here you can get an overview of how buffers work and how to use them in your games.

GameMaker: Studio has introduced a series of functions to the GameMaker Language (GML) to deal with buffers. Most people should be familiar with this term as it is used all the time when dealing with computers and programming, but knowing the word doesn't mean you actually know what it means. So this page aims to explain what a buffer is and how to use them within the context of GameMaker: Studio programming, although the general way they work is the same no matter the language or the technology, which is one of the reasons why they are so important.

What Is A Buffer?

A buffer (in programming) is basically a space within the system memory that is used to store small packets of data for just about anything (for example data transfer, collisions, colour data etc...). Since it is held in system memory it is very fast to access, and a buffer would generally be used for very short-term storage, like receiving network information before processing it, or for storing a checkpoint in your game (this is explained in the example given further down the page). Buffers are created by allocating a space in the system memory, calculated in bytes, which is then reserved for your game as long as your game is running or until you delete the buffer using the appropriate function. This means that even when your game is not in focus (for example, on a mobile device when you take a call the game will be put into the background) the buffer will still exist, however if the game is closed or re-started the buffer will be lost.

NOTE: Restarting the game will not clear or delete the buffer! But it will prevent any further access to the previously created buffer as the id handle will have been lost, causing a memory leak which will crash your game eventually. So, when re-starting a game, remember to delete the buffer first.

Buffer Types

GameMaker: Studio permits the creation of four different buffer types. The reason for this is that buffers are designed to be a highly optimised temporary storage medium, and as such you should create a buffer that is appropriate to the type of data that you wish it to store, otherwise you could get errors or cause a bottleneck in your code. Before explaining this further, let's look at the four available buffer types (defined as constants in GML):

Constant | description
buffer_fixed | A buffer of a fixed size in bytes. The size is set when the buffer is created and cannot be changed again.
buffer_grow | A buffer that will grow dynamically as data is added. You create it with an initial size (which should be an approximation of the size of the data expected to be stored), and then it will expand to accept further data that overflows this initial size.
buffer_wrap | A buffer where the data will wrap. When the data being added reaches the limit of the buffer size, the overwrite will be placed back at the start of the buffer, and further writing will continue from that point.
buffer_fast | This is a special "stripped down" buffer that is extremely fast to read/write to. However it can only be used with buffer_u8 data types, and must be 1 byte aligned. (Information on data types and byte alignment can be found further down this page).

Those are the buffer types available to you when using GameMaker: Studio, and which one you choose will greatly depend on the use you wish to put it to. For example, a grow buffer would be used for storing a "snapshot" of data to create a save game since you do not know the actual amount of data that is going to be placed in it, or a fast buffer would be used when you know that the values you are working with are all between 0 and 255 or -128 and 127, for example when processing RGB data from an image.

When creating a buffer, you should always try to create it to a size that is appropriate to the type, with the general rule being that it should be created to accommodate the maximum size of data that it is to store, and if in doubt, use a grow buffer to prevent overwrite errors.

The actual code to create a buffer would look something like this:

player_buffer = buffer_create(16384, buffer_fixed, 2);

That would create a fixed buffer of 16384 bytes and byte aligned to 2, with the function returning a unique id value that is stored in a variable for later referencing of this buffer. Now we have the basic concept of a buffer explained you should learn about data types and the previously mentioned byte alignment.

Data Types

When reading and writing data to a buffer, you do it in ''chunks'' of data defined by their '''data type'''. The '''data type''' sets the number of bytes allocated within the buffer for the value being written, and it is essential that you get this correct otherwise you will get some very strange results (or even errors) for your code.

Buffers are written to (and read from) sequentially, in that one piece of data is written after another, with each piece of data being of a set type. This means that you should ideally be aware of what data you are writing to the buffer at all times. These data types are defined in GML by the following constants:

Data Type Constant | Bytes | Description
buffer_u8 | 1 | An unsigned, 8bit integer. This is a positive value from 0 to 255.
buffer_s8 | 1 | A signed, 8bit integer. This can be a positive or negative value from -128 to 127 (0 is classed as positive).
buffer_u16 | 2 | An unsigned, 16bit integer. This is a positive value from 0 - 65,535.
buffer_s16 | 2 | A signed, 16bit integer. This can be a positive or negative value from -32,768 to 32,767 (0 is classed as positive).
buffer_u32 | 4 | An unsigned, 32bit integer. This is a positive value from 0 to 4,294,967,295.
buffer_s32 | 4 | A signed, 32bit integer. This can be a positive or negative value from -2,147,483,648 to 2,147,483,647 (0 is classed as positive).
buffer_f16 | 2 | A 16bit floating point number. This can be a positive or negative value within the range of +/- 65504. (Not currently supported!)
buffer_f32 | 4 | A 32bit floating point number. This can be a positive or negative value within the range of +/-16777216.
buffer_f64 | 8 | A 64bit floating point number. This can be a positive or negative value from -(252) to 252 - 1.
buffer_bool | 1 | A boolean value. Can only be either 1 or 0 (true or false)
buffer_string | N/A | This is a UTF-8 null terminated (0x00) string. Basically a GameMaker string is dumped in the buffer, and a 0 is put at the end.

So, say you have created a buffer and you want to write information to it, then you would use something like the following code:

buffer_write(buff, buffer_bool, global.Sound);
buffer_write(buff, buffer_bool, global.Music);
buffer_write(buff, buffer_s16, obj_Player.x);
buffer_write(buff, buffer_s16, obj_Player.y);
buffer_write(buff, buffer_string, global.Player_Name);

looking at the example above you can see that you can write different types of data to a buffer (you are only limited to a specific data type when using the fast buffer type), and this data will be added into the buffer consecutively (although its actual position in the buffer will depend on its byte alignment, explained below). This is the same for reading information from the buffer too, and in the case of the example given above, you would read from the buffer in the same order that you wrote the data, checking for the same data type, eg:

global.Sound = buffer_read(buff, buffer_bool);
global.Music = buffer_read(buff, buffer_bool);
obj_Player.x = buffer_read(buff, buffer_s16);
obj_Player.y = buffer_read(buff, buffer_s16);
global.Player_Name = buffer_read(buff, buffer_string);

As you can see, you read out information in the same order that you read it into the buffer. For further information on how to add and remove data from the buffer please see the Examples section below.

Byte Alignment

If you have been reading through this page you will have seen references to the byte alignment of a buffer. This basically refers to the position that new data will stored at within a given buffer. How does this work? Well, for a single byte aligned buffer, each piece of data is written to the buffer sequentially, with each new data piece being added directly after the previous. However a 2 byte aligned buffer will write each piece of data to intervals of 2 bytes, so that even if your initial write is 1 byte of data, the next write will be moved to align to two bytes. So, if your byte alignment is set to, say, 4 bytes and you write a single piece of data which is 1 byte in size then do a buffer tell (a tell gets the current position for reading/writing for the buffer), you'll get an offset of 1 (the offset in this case is the number of bytes from the start of the buffer to the current read/write position).

However, if you write another piece of data, also 1 byte in size, then do a buffer tell, you'll get an offset of 5 bytes (even though you have only written 2 bytes of data) as the alignment has padded the data to align it with the 4 byte buffer alignment.

Basically, what this means is that alignment will only affect where things are written to, so if you do a buffer tell after you write something, it'll return the current write position which immediately follows the data you've previously written. Note, however, that if you then write another piece of data, internally the buffer will move the write position along to the next multiple of the alignment size before actually writing the piece of data.

Examples

You can find two examples of using buffers on the following page:

  1. Buffer Examples

Back: Buffers
Next: Buffer Examples

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Cloud Services

These function can be used to sync data to different cloud services.

When making games, it is often necessary to store information about the game state in a file of some type, but storing this information on the device is not always the best option as, if the player deleted the game and then re-installs, this information may be lost. To prevent this you can use various different cloud services, which offer data storage over the internet for retrieval and modification at any time. You should note that this function is limited to one single data "blob" per game, so every time you send a new save to the cloud service, whether it is a string or a file, it will overwrite any previously stored data.

GameMaker: Studio supports this with a few simple functions that work in conjunction with the Asynchronous Cloud Event. These functions are explained on the following pages:

  1. cloud_synchronise
  2. cloud_string_save
  3. cloud_file_save

NOTE: Currently only Amazon WhisperSync is supported and you must activate it through the Android Tab of the Global Game Settings.

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


cloud_file_save

Save a file (as a string) to the chosen cloud service.

Syntax:

cloud_file_save(file, description);

Argument | Description
string | The file to be uploaded (as a string).
description | A brief description of the data being stored.

Returns: Real

Description

This function will commit a file to the chosen cloud service for storage. The function will return a unique id value that should then be used in the appropriate asynchronous event to identify the ds_map that is returned as a "call back" from the cloud service. The file should contain all the information that you need to save for your game as you can only store one single "data blob" to the cloud, and running this function again will overwrite any previously stored values (as will using the cloud_string_save function). The description should be a short string of information that describes the save, eg: "Level2, Stage2".

For further information on the returned asynchronous data, please see the function cloud_synchronise.

Example:

var t_str = "";
for (var i = 0; i < 10; i++;)
{
t_str += string(global.Highscore[i]) + "|"
}
var file = file_text_open_write("Highscores.txt");
file_text_write_string(file, t_str);
file_text_close(file);
save_check = cloud_file_save("Highscores.txt", "Current Highscores");

The above code creates a string from the values stored in the global array "Highscores" and then writes this string to a file for local storage. The file is then sent to the cloud service for storage.

Back: Cloud Services
Next: cloud_synchronise

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


cloud_string_save

Save a string to the chosen cloud service.

Syntax:

cloud_string_save(string, description);

Argument | Description
string | The data string to be uploaded.
description | A brief description of the data being stored.

Returns: Real

Description

This function will commit a string to the chosen cloud service for storage. The function will return a unique id value that should then be used in the appropriate asynchronous event to identify the ds_map that is returned as a "call back" from the cloud service. The string should contain all the information that you need to save for your game as you can only store one single "data blob" to the cloud, and running this function again will overwrite any previously stored values (as will using the cloud_file_save function). The description should be a short string of information that describes the save, eg: "Level2, Stage2".

For further information on the returned asynchronous data, please see the function cloud_synchronise.

Example:

var t_str = "";
for (var i = 0; i < 10; i++;)
{
t_str += string(global.Highscore[i]) + "|"
}
save_check = cloud_string_save(t_str, "Current Highscores");
var file = file_text_open_write("Highscores.txt");
file_text_write_string(file, t_str);
file_text_close(file);

The above code creates a string from the values stored in the global array "Highscores" and then writes this string to the cloud service for storage, as well as writing it to a file for local storage.

Back: Cloud Services
Next: cloud_file_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


cloud_synchronise

Synchronise the game with the cloud service.

Syntax:

cloud_synchronise();

Returns: Real

Description

This function would normally be called at the start of a new game and is used to retrieve the current status of the cloud service at game start up. The function returns a unique id value which would then be used in the Asynchronous Cloud Event to retrieve the relevant information from the ds_map that is created.

This function will send off to the cloud for data, which will then trigger the appropriate asynchronous event. In this event, you can check the returned async_load ds_map for the following values:

  1. "status": This holds the status code, where a negative value denotes an error, a description of which will be contained in the “errorString”. A value of 0 (or a positive value) indicates a success(see below for exact values), and the “resultString” will contain the returned data or a success message.

  2. "id": The id which was returned from the called function. If you fire off a series of cloud_ requests then you need to know which one you are getting the reply to, and so you would use this value to compare to the value you stored when you originally sent the request to find the right one.

  3. "description": The description of the last uploaded file.

  4. "resultString": This holds a string which is the data blob returned from the cloud.

  5. "errorString": returns an Error String for any error.

The exact meaning of the returned "status" map entry is explained in the following table:

Status Value | errorString / resultString | Description
-1 | errorString = "Not logged in to <SERVICE>" | You have not successfully logged in to the given Cloud Service
0 | resultString = recovered data | New game data downloaded from the cloud (following a cloud_synchronise call)
1 | resultString = "AlreadySynchronized" | No new data since you last called cloud_synchronise
2 | resultString = "ConflictDeferral" | A conflict was encountered, but the gamer chose to ignore it
3 | resultString = "GameUploadSuccess" | data from cloud_string_save or cloud_file_save was successfully uploaded to the cloud
-n | errorString = Description of error | Any other negative number means a synchronisation failure

Extended Example:

This function would be called in an event like the Game Start Event or in an object that is placed in the first room of your game, with the idea being that you check the current data blob from the cloud server to see if it is up to date or not.

cloud_check = cloud_synchronise();

You would then want to check the returned ds_map in the asynchronous Cloud Event to get the status and the returned string, if there is one, with something like the following code:

if ds_map_find_value(async_load, "id") == cloud_check
{
if ds_map_find_value(async_load, "status") < 0
{
show_message_async("Cloud Services not available. Please check connectivity.");
}
else
{
if ds_map_find_value(async_load, "status") == 0
{
var file = file_text_open_write("Save.txt");
file_text_write_string(file, ds_map_find_value(async_load, "resultString"));
file_text_close(file);
}
}
}

The above code checks to make sure that the correct asynchronous function call is being revised, then goes on to get the status of the returned cloud ds_map. if the status is a negative number, something has gone wrong and the user is informed, otherwise the code will continue and retrieve the synchronised data and write it to a text file for later use.

Back: Cloud Services
Next: cloud_string_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Data structures

This section deals with the different, specialist functions that you can use to store different types of data.

In games you often need to store information in a precise and ordered way. For example, you may need to store lists of items that a person carries or you may want to store a grid of places that still need to be visited. Now, you can use the arrays for this, but if you want to do more complicated operations, like sorting the data or searching for a particular item, you need to write large pieces of GML code which can be slow to execute, difficult to debug and a real pain to write!

To remedy this, GameMaker: Studio has a number of built-in data structures that can be accessed through specialist functions. There are six different types of data structure available, each one having its own benefits depending on the type of information that you are looking to store and how you wish to manipulate it later: stacks, queues, lists, maps, priority queues, and grids.

Essentially, all data structures work in the same way - You create a data structure and store its index value in a variable. You then use this index to reference the data structure in all further function calls that can perform operations on it. Finally, once you are done you destroy the data structure again to remove it from memory. You can use as many of the structures at the same time as you need, and all structures can store both strings and real values.

NOTE: As with all dynamic resources, data structures take up memory and so should always be destroyed when no longer needed to prevent memory leaks which will slow down and eventually crash your game.

Information on the different data structures can be found in the following sections:

  1. Stacks
  2. Queues
  3. Lists
  4. Maps
  5. Priority Queues
  6. Grids

Before using data structures in your game, you should also be aware that there are certain moments when, due to rounding errors, you may get a result that is not what you expected. This may be resolved by changing the DS precision using the following function:

  1. ds_set_precision

Finally, there is also a special function for checking to see whether a data structure of any given type exists:

  1. ds_exists

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_exists

Check to see if a data structure of a given type exists.

Syntax:

ds_exists(ind, type);

Argument | Description
ind | The variable index to check for the data structure
type | The type of data structure to check for (see the list of constants below)

Returns: Boolean

Description

With this function you can check to see if a data structure of the given type exists. You supply the "index" value (as held in a variable) and the ds "type", which can be any of the constants listed below, and the function will return true if the data structure exists and false otherwise.

Constant | Description
ds_type_map | A map data structure
ds_type_list | A list data structure
ds_type_stack | A stack data structure
ds_type_grid | A grid data structure
ds_type_queue | A queue data structure
ds_type_priority | A priority data structure

Example:

if !ds_exists(ai_grid, ds_type_grid)
{
ai_grid = ds_grid_create(room_width / 32, room_height / 32);
}

The above code checks the (previously initialised) variable "ai_grid" to see if it indexes a ds_grid type data structure, and if it does not then it creates one and stores its index in the variable.

Back: Data Structures
Next: ds_set_precision

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_set_precision

Sets the precision used for comparisons.

Syntax:

ds_set_precision(prec);

Argument | Description
prec | The precision value (default 0.0000001)

Returns: N/A

Description

When comparing values, for example when searching in a map or sorting a list, GameMaker: Studio must decide when two values are equal. For strings and integer values this is clear but for real numbers, due to floating point round-off errors, seemingly equal numbers can easily become unequal. For example, it's possible that (5 / 3) * 3 will not be equal to 5! To help avoid this, a precision value is used on all real number functions, and when the difference between two numbers is smaller than this precision they are considered equal. The default a precision of 0.0000001 is used for all data structure functions unless changed by this function.

NOTE: This precision is used in all data structures but not in other comparisons in GML!

Example:

ds_set_precision(0.0001);

The above code will change the default precision setting for all data structure functions.

Back: Data Structures
Next: ds_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


DS Grids

This section explains the various functions that can be used to create and manipulate ds_grids

A ds_grid is basically a type of two-dimensional array. You define the grid by setting its integer width and height, which then sets the total number of "cells" within the grid (the width and height multiplied) and these cells are then used to hold different data values (real numbers or strings).

This type of structure allows you to set and retrieve the value of cells in the grid by giving the x and y index of it (which starts with 0 for both the x and the y axis and goes up to the width - 1 and the height -1). But you can also set the value in specific grid regions, add single values, and retrieve the sum, maximum, minimum, and mean value over a given region, making this data structure the most versatile of all those available to you.

When accessing DS grid data structures, you should always try to use integer values for the cell position, and all non-integer indices will be floored by GameMaker: Studio if you do not. If that is not what you require, then you will need to do the rounding yourself previously before passing the index that you wish to check.

NOTE: As with all dynamic resources, data structures take up memory and so should always be destroyed when no longer needed to prevent memory leaks which will slow down and eventually crash your game.

The following functions exist that deal with DS grids.

  1. ds_grid_create
  2. ds_grid_destroy
  3. ds_grid_width
  4. ds_grid_height
  5. ds_grid_resize
  6. ds_grid_clear
  7. ds_grid_set
  8. ds_grid_set_disk
  9. ds_grid_set_grid_region
  10. ds_grid_set_region
  11. ds_grid_shuffle
  12. ds_grid_sort
  13. ds_grid_get
  14. ds_grid_get_max
  15. ds_grid_get_mean
  16. ds_grid_get_min
  17. ds_grid_get_sum
  18. ds_grid_get_disk_max
  19. ds_grid_get_disk_mean
  20. ds_grid_get_disk_min
  21. ds_grid_get_disk_sum
  22. ds_grid_add
  23. ds_grid_add_region
  24. ds_grid_add_disk
  25. ds_grid_add_grid_region
  26. ds_grid_multiply
  27. ds_grid_multiply_disk
  28. ds_grid_multiply_region
  29. ds_grid_multiply_grid_region
  30. ds_grid_value_exists
  31. ds_grid_value_disk_exists
  32. ds_grid_value_x
  33. ds_grid_value_y
  34. ds_grid_value_disk_x
  35. ds_grid_value_disk_y
  36. ds_grid_copy
  37. ds_grid_read
  38. ds_grid_write

Apart from these specific functions you can all use an expression (called an accessor) to add or modify the contents of your ds_grid. This accessor looks similar to a 2D array with the following syntax:

grid_index[# xpos, ypos]

You can find more information, plus examples, from from the GML Overview page on Accessors.

NOTE: if you need to check if a data structure exists, you can use the ds_exists() function.

Back: Data Structures
Next: DS Stacks

© Copyright YoYo Games Ltd. 2018 All Rights Reserved
.


ds_grid_add

Adds a value to a cell in a grid.

Syntax:

ds_grid_add(index, x, y, val);

Argument | Description
index | The index of the grid.
x | The x position of the cell in the grid.
y | The y position of the cell in the grid.
val | The value to add to the cell.

Returns: N/A

Description

This function can be used to add a given value (real or string) to the value of the given cell within the grid. The value to be added must be the same type as that held within the grid cell, ie: you cannot add a string to a real or vice-versa, and for strings this corresponds to concatenation.

Example:

ds_grid_add(grid, 5, 5, 6);

This would add 6 to the given cell within the ds_grid referenced by the variable "grid".

Back: DS Grids
Next: ds_grid_add_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_add_disk

Adds to all the cells in a circular region in a grid to an indicated value (can both be a number or a string).

Syntax:

ds_grid_add_disk(index, xm, ym, r, val);

Argument | Description
index | The index of the grid.
xm | The x position of the disk on the grid.
ym | The y position of the disk on the grid.
r | The radius of the disk on the grid.
val | The value to add to the cells within the disk.

Returns: N/A

Description

This function can be used to add a given value (real or string) to all the values of the cells found within the defined disk area of a grid. The value to be added must be of the same type as that held within the grid cells, ie: you cannot add a string to a real or vice-versa, and for strings this corresponds to concatenation.

Example:

ds_grid_add_disk(grid, 7, 6, 5, 2);

This would add 2 to all the values held in the cells within the defined disk area of the ds_grid referenced by the variable "grid".

Back: DS Grids
Next: ds_grid_add_grid_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_add_grid_region

Adds the contents of the cells in a source grid to the cells in a destination grid.

Syntax:

ds_grid_add_grid_region(index, source, x1, y1, x2, y2, xpos, ypos);

Argument | Description
index | The index of the destination grid.
source | The index of the source grid.
x1 | The left position of the region of cells to copy from the source grid.
y1 | The top position of the region of cells to copy from the source grid.
x2 | The right position of the region of cells to copy from the source grid.
y2 | The bottom position of the region of cells to copy from the source grid.
xpos | The x position on the destination grid to add the source region to.
ypos | The y position on the destination grid to add the source region to.

Returns: N/A

Description

This function can be used to add all the values of all the cells found within the source area of a grid to the values within the destination grid, as illustrated below: NOTE: You can also use this function on the same grid to add values from one region of the grid to those stored in another (see code example below).

Example:

ds_grid_add_grid_region(grid, grid, 0, 0, 1, 5, 2, 0);

The above code would copy the region of cells from (0,0) to (1,5) of the ds-grid indexed in the variable "grid" and add them to the cells from position (2,0) of the same ds_grid.

Back: DS Grids
Next: ds_grid_multiply

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_add_region

Adds the given value to all cells in a region.

Syntax:

ds_grid_add_region(index, x1, y1, x2, y2, val);

Argument | Description
index | The index of the grid.
x1 | The x position of the left of the region in the grid.
y1 | The y position of the top of the region in the grid.
x2 | The x position of the right of the region in the grid.
y2 | The y position of the bottom of the region in the grid.
val | The value to add to the region cells.

Returns: N/A

Description

This function can be used to add a given value (real or string) to all the values of the cells found within the defined area of a grid. The value to be added must be of the same type as that held within the grid cells, ie: you cannot add a string to a real or vice-versa, and for strings this corresponds to concatenation.

Example:

ds_grid_add_region(grid, 2, 4, 5, 5, ".");

This would add "." to all the strings held in the cells within the defined region of the ds_grid referenced by the variable "grid".

Back: DS Grids
Next: ds_grid_add_disk

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_clear

Clears the grid with the given id to an indicated value.

Syntax:

ds_grid_clear(index, val);

Argument | Description
index | This index of the grid to clear.
val | The new value for all grid cells.

Returns: N/A

Description

This function can be used to clear a given ds_grid to a specific value. All cells within the grid will then contain this value, which can be a real number or a string. The image below illustrates how this works:

Example:

ds_grid_resize(global.Grid, room_width / 32, room_height / 32);
ds_grid_clear(global.Grid, -1);

The above code will resize the ds_grid indexed in the global variable "Grid" and then clear it so that each cell holds the value -1.

Back: DS Grids
Next: ds_grid_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_copy

Copies one grid into another grid.

Syntax:

ds_grid_copy(destination, source);

Argument | Description
destination | This index of the grid to copy to.
source | This index of the grid to copy from.

Returns: N/A

Description

With this function you can copy the contents of one grid into another one. Both grids must have been created previously using the ds_grid_create function.

Example:

n_grid = ds_grid_create(ds_grid_width(a_grid), ds_grid_height(a_grid));
ds_grid_copy(n_grid, a_grid);
ds_grid_clear(a_grid, -1);

The above code creates a new ds_grid, based on the width and height of a previously created grid, then copies the information form the previous grid to the new one. Finally it clears the old grid so that all cells have a value of -1.

Back: DS Grids
Next: ds_grid_read

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_create

Creates a new grid.

Syntax:

ds_grid_create(w, h);

Argument | Description
w | The width of the grid to be created.
h | The height of the grid to be created.

Returns: Real.

Description

With this function you can create a new ds_grid data structure of the specified cell width and height. This function returns an id which must be used in all further functions that deal with this ds_grid.

Example:

mygrid = ds_grid_create(10, 10);

This creates a grid 10 cells high and 10 cells wide.

Back: DS Grids
Next: ds_grid_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_destroy

Destroys a grid, freeing the memory used.

Syntax:

ds_grid_destroy(index);

Argument | Description
index | This index of the grid to destroy.

Returns: N/A

Description

This function will remove the given grid data-structure from memory, freeing up the resources it was using and removing all values that it contained. This function should always be used when you are finished using the ds_grid to prevent memory leaks that can slow down and crash your game.

Example:

if lives = 0
{
ds_grid_destroy(Wall_Grid);
room_goto(rm_Menu);
}

The above code will check the value of the built in global variable "lives" and if it is 0, it destroys the ds_grid indexed in the variable "Wall_Grid" and then changes rooms.

Back: DS Grids
Next: ds_grid_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_get

Returns the value of a cell in a grid.

Syntax:

ds_grid_get(index, x, y);

Argument | Description
index | The index of the grid.
x | The x position of the cell you want to find the value of.
y | The y position of the cell you want to find the value of.

Returns: Real or String

Description

This function can be used to get the value (either a real number or a string) from any cell within the given ds_grid. If you pass invalid grid coordinates to the function, then the value returned will be 0.

Example:

var xx, yy;
xx = irandom(ds_grid_width(grid) - 1);
yy = irandom(ds_grid_height(grid) - 1);
val = ds_grid_get(xx, yy);

The above code selects a random cell from the ds_grid indexed in the variable "grid" and stores its value in the variable "val".

Back: DS Grids
Next: ds_grid_get_max

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_get_disk_max

Gets the maximum from all the values within a circular region.

Syntax:

ds_grid_get_disk_max(index, xm, ym, r);

Argument | Description
index | The index of the grid.
xm | The x position of the disk center in the grid.
ym | The y position of the disk center in the grid.
r | The radius of the disk in the grid.

Returns: Real or String

Description

This function can be used to find the maximum value for all the cells found within the defined disk area of a grid, as shown in the image below:

Example:

val = ds_grid_get_disk_max(grid, 5, 5, 2);

The above code will set the variable "val" to the maximum value contained within the given disk of the ds_grid indexed in the variable "grid".

Back: DS Grids
Next: ds_grid_get_disk_mean

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_get_disk_mean

Gets the mean value from all the values within a circular region.

Syntax:

ds_grid_get_disk_mean(index, xm, ym, r);

Argument | Description
index | The index of the grid.
xm | The x position of the disk on the grid.
ym | The y position of the disk on the grid.
r | The radius of the disk on the grid.

Returns: Real or String

Description

This function can be used to find the mean value for all the cells found within the defined disk area of a grid (all cell values are added together and then divided by the total number of cells that make up the disk), as shown in the image below:

Example:

val = ds_grid_get_disk_mean(grid, 5, 5, 2);

The above code will set the variable "val" to the mean value contained within the given disk of the ds_grid indexed in the variable "grid".

Back: DS Grids
Next: ds_grid_get_disk_min

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_get_disk_min

Gets the minimum from all the values within a circular region. Only works when the cells are numbers.

Syntax:

ds_grid_get_disk_min(index, xm, ym, r);

Argument | Description
index | The index of the grid.
xm | The x position of the disk on the grid.
ym | The y position of the disk on the grid.
r | The radius of the disk on the grid.

Returns: Real or String

Description

This function can be used to find the minimum value for all the cells found within the defined disk area of a grid, as shown in the image below:

Example:

val = ds_grid_get_disk_min(grid, 5, 5, 2);

The above code will set the variable "val" to the minimum value contained within the given disk of the ds_grid indexed in the variable "grid".

Back: DS Grids
Next: ds_grid_get_disk_sum

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_get_disk_sum

Gets the sum of all the values within a circular region. Only works when the cells are numbers.

Syntax:

ds_grid_get_disk_sum(index, xm, ym, r);

Argument | Description
index | The index of the grid.
xm | The x position of the disk on the grid.
ym | The y position of the disk on the grid.
r | The radius of the disk on the grid.

Returns: Real or String

Description

This function can be used to add all the values all the cells found within the defined disk area of a grid together, as shown in the image below:

Example:

val = ds_grid_get_disk_sum(grid, 5, 5, 2);

The above code will set the variable "val" to the sum of all values contained within the given disk of the ds_grid indexed in the variable "grid".

Back: DS Grids
Next: ds_grid_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_get_max

Returns the max value from all the cells within a region on a grid.

Syntax:

ds_grid_get_max(index, x1, y1, x2, y2);

Argument | Description
index | The index of the grid.
x1 | The left cell column of the region.
y1 | The top cell row of the region.
x2 | The right cell column of the region.
y2 | The bottom cell row of the region.

Returns: Real or String

Description

This function can be used to find the maximum value for all the cells found within the defined region of a grid, as shown in the image below:

Example:

val = ds_grid_get_max(grid, 0, 0, 5, 5);

The above code will set the variable "val" to the maximum value contained within the given region of the ds_grid indexed in the variable "grid".

Back: DS Grids
Next: ds_grid_get_mean

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_get_mean

Returns the mean value of all the cells within a region on a grid.

Syntax:

ds_grid_get_mean(index, x1, y1, x2, y2);

Argument | Description
index | The index of the grid.
x1 | The left cell column of the region.
y1 | The top cell row of the region.
x2 | The right cell column of the region.
y2 | The bottom cell row of the region.

Returns: Real or String

Description

This function can be used to find the mean value for all the cells found within the defined region of a grid (all cell values are added together and then divided by the total number of cells that make the region), as shown in the image below:

Example:

val = ds_grid_get_mean(grid, 0, 0, 5, 5);

The above code will set the variable "val" to the mean value contained within the given region of the ds_grid indexed in the variable "grid".

Back: DS Grids
Next: ds_grid_get_min

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_get_min

Returns the min value from all the cells within a region on a grid.

Syntax:

ds_grid_get_min(index, x1, y1, x2, y2);

Argument | Description
index | The index of the grid.
x1 | The left cell column of the region.
y1 | The top cell row of the region.
x2 | The right cell column of the region.
y2 | The bottom cell row of the region.

Returns: Real or String

Description

This function can be used to find the minimum value for all the cells found within the defined region of a grid, as shown in the image below:

Example:

val = ds_grid_get_min(grid, 0, 0, 5, 5);

The above code will set the variable "val" to the minimum value contained within the given region of the ds_grid indexed in the variable "grid".

Back: DS Grids
Next: ds_grid_get_sum

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_get_sum

Returns the sum of all the cells within a region on a grid.

Syntax:

ds_grid_get_sum(index, x1, y1, x2, y2);

Argument | Description
index | The index of the grid.
x1 | The left cell column of the region.
y1 | The top cell row of the region.
x2 | The right cell column of the region.
y2 | The bottom cell row of the region.

Returns: Real

Description

This function can be used to add all the values all the cells found within the defined region of a grid together, as shown in the image below:

Example:

val = ds_grid_get_sum(grid, 0, 0, 5, 5);

The above code will set the variable "val" to the sum of all values contained within the given region of the ds_grid indexed in the variable "grid".

Back: DS Grids
Next: ds_grid_get_disk_max

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_height

Finds the height of a grid.

Syntax:

ds_grid_height(index);

Argument | Description
index | This index of the grid to find the height of.

Returns: Real

Description

This function will return the height of the given grid. This value is the number of cells the grid has along the y-axis and is always an integer, as shown in the image below:

Example:

var i, j;
for (i = 0; i < ds_grid_width(grid); i += 1)
{
for (j = 0; j < ds_grid_height(grid); j += 1)
{
if ds_grid_get(grid, i, j) = 1
{
instance_create(i * 32, j * 32, obj_Wall);
}
}
}

The above code will loop through the ds_grid indexed in the variable "grid" and if the value found in any specific cell is equal to 1, it will then create an instance of "obj_Wall" at the appropriate position within the room.

Back: DS Grids
Next: ds_grid_resize

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_multiply

Multiplies the value of a given grid cell by a given amount.

Syntax:

ds_grid_multiply(index, x, y, val);

Argument | Description
index | The index of the grid.
x | The x position of the cell in the grid.
y | The y position of the cell in the grid.
val | The value to multiply with the cell.

Returns: N/A

Description

This function will multiply the value of a the given grid cell by the specified amount.

NOTE: This function will only work with real numbers, not strings.

Example:

ds_grid_multiply(mygrid, 5, 5, 2);

the above code will multiply the value stored in the given ds_grid cell by 2.

Back: DS Grids
Next: ds_grid_multiply_disk

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_multiply_disk

Multiply all the values contained within the disc region by a given amount.

Syntax:

ds_grid_multiply_disk(index, xm, ym, r, val);

Argument | Description
index | The index of the grid.
xm | The x position of the disk on the grid.
ym | The y position of the disk on the grid.
r | The radius of the disk on the grid.
val | The value to multiply the cells within the disk with.

Returns: N/A

Description

This function will take all the values in a given disc-shaped region of the ds_grid, and multiply each one by the given amount.

NOTE: This function will only work with real numbers, not strings.

Example:

ds_grid_multiply_disk(mygrid, 5, 5, 5, 2);

The above code will take all the values found within the circular grid area and multiply each one by 2.

Back: DS Grids
Next: ds_grid_multiply_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_multiply_grid_region

Multiplies the contents of the cells in a source grid with the cells in a destination grid.

Syntax:

ds_grid_multiply_grid_region(index, source, x1, y1, x2, y2, xpos, ypos);

Argument | Description
index | The index of the destination grid.
source | The index of the source grid.
x1 | The left position of the region of cells to copy from the source grid.
y1 | The top position of the region of cells to copy from the source grid.
x2 | The right position of the region of cells to copy from the source grid.
y2 | The bottom position of the region of cells to copy from the source grid.
xpos | The x position on the destination grid to multiply the source region with.
ypos | The y position on the destination grid to multiply the source region with.

Returns: N/A

Description

With this function you can define an area within a given ds_grid, then take those values and multiply them with those found in a separate region of either the same ds_grid, or another one (which has been previously created). The original region will remain unchanged, while the region that they have been multiplied with will now store the new values for each cell.

Example:

ds_grid_multiply_grid_region(mygrid, mygrid, 0, 0, 5, 5, 0, 0);

This would take the region of cells from (0,0) to (5,5) of the ds_grid "mygrid" and multiply them with the cells from position (0,0) of the same ds_grid.

Back: DS Grids
Next: ds_grid_value_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_multiply_region

Multiplies all the values found in the given region by a given amount.

Syntax:

ds_grid_multiply_region(index, x1, y1, x2, y2, val);

Argument | Description
index | The index of the grid.
x1 | The x position of the left of the region in the grid.
y1 | The y position of the top of the region in the grid.
x2 | The x position of the right of the region in the grid.
y2 | The y position of the bottom of the region in the grid.
val | The value to multiply with the region cells.

Returns: N/A

Description

With this function you can specify a region of the grid in which to multiply each cell value by a given amount.

NOTE: This function will only work with real numbers, not strings.

Example:

ds_grid_multiply_region( mygrid, 5, 5, 10, 10, 2 );

The above code will take all the values found within the defined rectangular grid area and multiply each one by 2.

Back: DS Grids
Next: ds_grid_multiply_grid_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_read

Reads the grid data structure from a string.

Syntax:

ds_grid_read(index, string [, legacy]);

Argument | Description
index | The index of the grid to read.
string | The string to read into the ds_grid.
legacy (optional) | Can be either true or false or omitted completely.

Returns: N/A

Description

This function can be used to convert a string which has been created previously by the function ds_grid_write() back into a ds_grid. The ds_grid must have been created previously (see the example below). Note that if the data structure was created with previous versions of GameMaker you should add the optional argument "legacy", setting it to true as the string format has changed with this version.

Example:

grid = ds_grid_create(room_width div 32, room_height div 32);
ini_open("Save.ini");
ds_grid_read(grid, ini_read_string("Save", "0", ""));
ini_close();

The above code creates a ds_grid based on the size of the room (each 32x32 square of pixels represents one grid cell) and then reads a previously saved set of grid data from an ini file into the new ds grid.

Back: DS Grids
Next: ds_grid_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_resize

Resizes the grid to a new width and height.

Syntax:

ds_grid_resize(index, w, h);

Argument | Description
index | This index of the grid to resize.
w | The new width of the grid.
h | The new height of the grid.

Returns: N/A

Description

With this function you can resize the given ds_grid to have a different width and/or height. If the grid size is larger than the current grid, the new cells will have a base value of 0, and if the size is smaller then the values held in the cells that are no longer within the new size will be lost. All other cells will be left untouched.

Example:

ds_grid_resize(global.Grid, room_width / 32, room_height / 32);
ds_grid_clear(global.Grid, -1);

The above code will resize the ds_grid indexed in the global variable "Grid" and then clear it so that each cell holds the value -1.

Back: DS Grids
Next: ds_grid_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_set

Sets a cell in a grid to a given value.

Syntax:

ds_grid_set(index, x, y, value);

Argument | Description
index | This index of the grid.
x | The x position of the cell to set.
y | The y position of the cell to set.
value | The value with which to set the cell.

Returns: N/A

Description

This function can be used to set a given cell within the given ds_grid to any value, which can be a real number or a string. The image below illustrates this:

Example:

grid = ds_grid_create(5, 5);
var i, j;
i = 0;
j = 0;
repeat (ds_grid_width(grid))
{
repeat (ds_grid_height(grid))
{
ds_grid_set(grid, i, j, irandom(9));
j += 1;
}
j = 0;
i += 1;
}

The above code creates a grid and stores its index in the variable "grid". It then populates this grid with random integers from 0 to 9.

Back: DS Grids
Next: ds_grid_set_disk

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_set_disk

Sets all the cells in a circular region in a grid to an indicated value.

Syntax:

ds_grid_set_disk(index, xm, ym, r, val);

Argument | Description
index | The index of the grid.
xm | The x position of the disk on the grid.
ym | The y position of the disk on the grid.
r | The radius of the disk on the grid.
val | The value to set with the cells within the disk.

Returns: N/A

Description

With this function you can set a circular region of a grid to a certain value. You need to supply a starting grid cell (as an x and y axis coordinate) as well as the radius of the disk to set and the value that you wish to set the disk too, as shown by the illustration below:

Example:

ds_grid_set_disk(grid, ds_grid_width(grid) div 2, ds_grid_height(grid) div 2, 5, -4);

The above code will set a circular region with a radius of 5 cells in the ds_grid indexed in the variable "grid" to a value of -4.

Back: DS Grids
Next: ds_grid_set_grid_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_set_grid_region

Copies the contents of the cells in a source grid to a destination grid.

Syntax:

ds_grid_set_grid_region(index, source, x1, y1, x2, y2, xpos, ypos);

Argument | Description
index | The index of the destination grid.
source | The index of the source grid.
x1 | The left position of the region of cells to copy from the source grid.
y1 | The top position of the region of cells to copy from the source grid.
x2 | The right position of the region of cells to copy from the source grid.
y2 | The bottom position of the region of cells to copy from the source grid.
xpos | The x position on the destination grid to copy the source region to.
ypos | The y position on the destination grid to copy the source region to.

Returns: N/A

Description

This function can be used to copy the contents of a rectangular area of grid cells from one (previously defined) ds_grid to another, or it can be used to copy a region from within the same grid. The following images illustrate both ways that this function can be used:

Example:

ds_grid_set_grid_region(t_grid, grid, 0, 0, 5, 5, 10, 10);

This would copy the region of cells from (0,0) to (5,5) of the grid indexed in the variable "t_grid" and copy them to position (10,10) in the grid indexed in the variable "grid".

Back: DS Grids
Next: ds_grid_set_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_set_region

Sets the all cells in the region in the grid with the given id, to the indicated value (can both be a number or a string).

Syntax:

ds_grid_set_region(index, x1, y1, x2, y2, val);

Argument | Description
index | The index of the grid.
x1 | The x position of the left of the region in the grid.
y1 | The y position of the top of the region in the grid.
x2 | The x position of the right of the region in the grid.
y2 | The y position of the bottom of the region in the grid.
val | The value to set the region cells to.

Returns: N/A

Description

This function can be used to set a rectangular region of a given grid to a specified value (which can be either a real or a string) as illustrated by the image shown below:

Example:

ds_grid_set_region(grid, 5, 5, 10, 10, 99);

This would set all cells within the region of the grid indexed in the variable "grid" from (5,5) to (10,10) to 99.

Back: DS Grids
Next: ds_grid_shuffle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_shuffle

Shuffles all the positions in a grid so that they end up in a random order.

Syntax:

ds_grid_shuffle(index);

Argument | Description
index | The index of the grid to shuffle.

Returns: N/A

Description

This function can be used to randomize the positions of all values in all cells within a grid.

NOTE: This function will shuffle the grid cells to the same positions every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game. This is only true when testing and debugging the game, as the final executable package will not show this behaviour and will be random every play.

Example:

ds_grid_shuffle(grid);

This would take all the values in the ds_grid indexed in the variable "grid" and shuffle them around to get a different order.

Back: DS Grids
Next: ds_grid_sort

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_sort

Sort a grid according to the values of a given column.

Syntax:

ds_grid_sort(index, column, ascending);

Argument | Description
index | The index of the grid to sort.
column | The column to use for sorting the rows
ascending | Whether to sort lowest to highest (true), or highest to lowest (false).

Returns: N/A

Description

This function can be used to sort a ds_grid based on the values from a given column (much as you would sort files by date, size etc... in the Windows Explorer). The following image shows an example:

Example:

ds_grid_sort(grid, 3, false);

This would take all the values in the ds_grid indexed in the variable "grid" and sort them according to the values found in the 3rd column of the grid (as shown in the above image).

Back: DS Grids
Next: ds_grid_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_value_disk_exists

Finds whether a value exists within a circular region off a grid.

Syntax:

ds_grid_value_disk_exists(index, xm, ym, r, val);

Argument | Description
index | The index of the grid.
xm | The x position of the disk on the grid.
ym | The y position of the disk on the grid.
r | The radius of the disk on the grid.
val | The value to find.

Returns: Boolean

Description

With this function you can check to see if a specific value (real or string) is present within a circular area of a given ds_grid. If it is present the function will return true otherwise it will return false.

Example:

if ds_grid_value_disk_exists(grid, 5, 5, 5, val)
{
xpos = ds_grid_value_disk_x(grid, 5, 5, 5, val);
ypos = ds_grid_value_disk_y(grid, 5, 5, 5, val);
}

The above code checks a ds_grid for a specific value within a disk region. if it is found, it then stores the x and y position of the value in two variables for later use.

Back: DS Grids
Next: ds_grid_value_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_value_disk_x

Finds the x position of a value found within a circular region of a grid.

Syntax:

ds_grid_value_disk_x(index, xm, ym, r, val);

Argument | Description
index | The index of the grid.
xm | The x position of the disk on the grid.
ym | The y position of the disk on the grid.
r | The radius of the disk on the grid.
val | The value to find.

Returns: Real

Description

With this function you can get the x coordinate (within the given grid disc-shaped region) of the value being searched for. Be aware that if the value being searched for does not exists, the function will return 0, so it is a good idea to check if the values exists first with ds_grid_value_disk_exists then run this function (along with the ds_grid_value_disk_y function) to get the exact position within disc being searched.

Example:

if ds_grid_value_disk_exists(grid, 5, 5, 5, val)
{
xpos = ds_grid_value_disk_x(grid, 5, 5, 5, val);
ypos = ds_grid_value_disk_y(grid, 5, 5, 5, val);
}

The above code checks a ds_grid for a specific value within a disk region. if it is found, it then stores the x and y position of the value in two variables for later use.

Back: DS Grids
Next: ds_grid_value_disk_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_value_disk_y

Finds the y position of a value found within a circular region of a grid.

Syntax:

ds_grid_value_disk_y(index, xm, ym, r, val);

Argument | Description
index | The index of the grid.
xm | The x position of the disk on the grid.
ym | The y position of the disk on the grid.
r | The radius of the disk on the grid.
val | The value to find.

Returns: Real

Description

With this function you can get the y coordinate (within the given grid disc-shaped region) of the value being searched for. Be aware that if the value being searched for does not exists, the function will return 0, so it is a good idea to check if the values exists first with ds_grid_value_disk_exists then run this function (along with the ds_grid_value_disk_x function) to get the exact position within disc being searched.

Example:

if ds_grid_value_disk_exists(grid, 5, 5, 5, val)
{
xpos = ds_grid_value_disk_x(grid, 5, 5, 5, val);
ypos = ds_grid_value_disk_y(grid, 5, 5, 5, val);
}

The above code checks a ds_grid for a specific value within a disk region. if it is found, it then stores the x and y position of the value in two variables for later use.

Back: DS Grids
Next: ds_grid_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_value_exists

Finds whether a certain value appears in a region of a grid.

Syntax:

ds_grid_value_exists(index, x1, y1, x2, y2, val);

Argument | Description
index | The index of the grid.
x1 | The x position of the left of the region in the grid.
y1 | The y position of the top of the region in the grid.
x2 | The x position of the right of the region in the grid.
y2 | The y position of the bottom of the region in the grid.
val | The value to find.

Returns: Boolean

Description

With this function you can check to see if a specific value (real or string) is present within a rectangular area of a given ds_grid. If it is present the function will return true otherwise it will return false.

Example:

if ds_grid_value_exists(grid, 0, 1, 5, 6, val)
{
xpos = ds_grid_value_x(grid, 0, 1, 5, 6, val);
ypos = ds_grid_value_y(grid, 0, 1, 5, 6, val);
}

The above code checks a ds_grid for a specific value within a rectangular region. if it is found, it then stores the x and y position of the value in two variables for later use.

Back: DS Grids
Next: ds_grid_value_disk_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_value_x

Returns the x position of a value within a region of a grid.

Syntax:

ds_grid_value_x(index, x1, y1, x2, y2, val);

Argument | Description
index | The index of the grid.
x1 | The x position of the left of the region in the grid.
y1 | The y position of the top of the region in the grid.
x2 | The x position of the right of the region in the grid.
y2 | The y position of the bottom of the region in the grid.
val | The value to find.

Returns: Real

Description

With this function you can get the x coordinate (within the given rectangular grid region) of the value being searched for. Be aware that if the value being searched for does not exists, the function will return 0, so it is a good idea to check if the values exists first with ds_grid_value_exists then run this function (along with the ds_grid_value_y function) to get the exact position within region being searched.

Example:

if ds_grid_value_exists(grid, 0, 1, 5, 6, val)
{
xpos = ds_grid_value_x(grid, 0, 1, 5, 6, val);
ypos = ds_grid_value_y(grid, 0, 1, 5, 6, val);
}

The above code checks a ds_grid for a specific value within a rectangular region. if it is found, it then stores the x and y position of the value in two variables for later use.

Back: DS Grids
Next: ds_grid_value_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_value_y

Returns the y position of a value within a region of a grid.

Syntax:

ds_grid_value_y(index, x1, y1, x2, y2, val);

Argument | Description
index | The index of the grid.
x1 | The x position of the left of the region in the grid.
y1 | The y position of the top of the region in the grid.
x2 | The x position of the right of the region in the grid.
y2 | The y position of the bottom of the region in the grid.
val | The value to find.

Returns: Real

Description

With this function you can get the y coordinate (within the given rectangular grid region) of the value being searched for. Be aware that if the value being searched for does not exists, the function will return 0, so it is a good idea to check if the values exists first with ds_grid_value_exists then run this function (along with the ds_grid_value_x function) to get the exact position within region being searched.

Example:

if ds_grid_value_exists(grid, 0, 1, 5, 6, val)
{
xpos = ds_grid_value_x(grid, 0, 1, 5, 6, val);
ypos = ds_grid_value_y(grid, 0, 1, 5, 6, val);
}

The above code checks a ds_grid for a specific value within a rectangular region. if it is found, it then stores the x and y position of the value in two variables for later use.

Back: DS Grids
Next: ds_grid_value_disk_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_width

Returns the width of a grid.

Syntax:

ds_grid_width(index);

Argument | Description
index | This index of the grid to find the width of.

Returns: Real

Description

This function will return the width of the given grid. This value is the number of cells the grid has along the x-axis and is always an integer, as shown in the image below:

Example:

var i, j;
for (i = 0; i < ds_grid_width(grid); i += 1)
{
for (j = 0; j < ds_grid_height(grid); j += 1)
{
if ds_grid_get(grid, i, j) = 1
{
instance_create(i * 32, j * 32, obj_Wall);
}
}
}

The above code will loop through the ds_grid indexed in the variable "grid" and if the value found in any specific cell is equal to 1, it will then create an instance of "obj_Wall" at the appropriate position within the room.

Back: DS Grids
Next: ds_grid_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_grid_write

Turns a data structure into a string and returns this string.

Syntax:

ds_grid_write(index);

Argument | Description
index | The index of the grid to write.

Returns: String

Description

This function can be used to convert the given ds_grid into a string, which can then be stored in an external file (for example). You can read the returned string from this function back into a ds_grid using the function ds_grid_read().

NOTE: The returned string is not a human readable string, but rather a dump of the contents of the data-structure

Example:

ini_open("Save.ini");
ini_write_string("Save", "0", ds_grid_write(mygrid));
ini_close();

The above code will open an ini file (creating it if it doesn't already exist) and then write the given ds_grid as a string to that file.

Back: DS Grids
Next: ds_grid_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


DS Lists

A ds_list stores a collection of values in a particular order.

A ds_list is a data-structure that stores information sequentially as it is added (much like a 1D array). Ds lists are very flexible data structures that permit you to add values at the end or insert them somewhere in the middle of the list, as well as giving you the ability to shuffle the order (to randomize the values) or sort them in an ascending or descending order.

When accessing DS list data structures, you should always try to use integer values for the list position, and all non-integer indices will be floored by GameMaker: Studio if you do not. If that is not what you require, then you will need to do the rounding yourself previously before passing the index that you wish to check.

NOTE: As with all dynamic resources, data structures take up memory and so should always be destroyed when no longer needed to prevent memory leaks which will slow down and eventually crash your game.

The following functions exist that deal with DS lists.

  1. ds_list_create
  2. ds_list_destroy
  3. ds_list_clear
  4. ds_list_empty
  5. ds_list_size
  6. ds_list_add
  7. ds_list_set
  8. ds_list_delete
  9. ds_list_find_index
  10. ds_list_find_value
  11. ds_list_insert
  12. ds_list_replace
  13. ds_list_shuffle
  14. ds_list_sort
  15. ds_list_copy
  16. ds_list_read
  17. ds_list_write

Ds_lists can be used hold ds_maps and other ds_lists too, but only for use in conjunction with the json_encode function. This requires that you "flag" or "mark" the entry within the list so that it can be encoded correctly using the following special functions:

  1. ds_list_mark_as_list
  2. ds_list_mark_as_map

Apart from these specific functions you can all use an expression (called an accessor) to add or modify the contents of your ds_list. This accessor looks similar to a 1D array with the following syntax:

list_index[| index]

You can find more information, plus examples, from from the GML Overview page on Accessors.

NOTE: if you need to check if a data structure exists, you can use the ds_exists() function.

Back: Data Structures
Next: DS Maps

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_add

Adds the given value (or values) to the end of the list.

Syntax:

ds_list_add(id, val1 [, val2, ... val15]);

Argument | Description
id | The id of the list to add to.
val | The value to add to the list.
[val2, ... val15] | Optional values to be added to the list.

Returns: N/A

Description

This function can be used to add a new value (real or string) to the list, which will be added on at the end. The function can take a further 14 optional arguments (making a total of 15 possible additions), permitting you to add multiple values consecutively to the list in a single call.

Example:

ds_list_add(sc_list, score);

The above code will add the value stored in the "score" variable into the list indexed in the variable "sc_list".

Back: DS Lists
Next: ds_list_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_clear

Clears all of the data from a given list.

Syntax:

ds_list_clear(id);

Argument | Description
id | The id of the data structure to clear.

Returns: N/A

Description

With this function you can clear all data from the given list data-structure. This does NOT destroy the data-structure (for that you should use ds_list_destroy) it only wipes all data from it and returns an empty list.

Example:

if count = 15 && !ds_list_empty(command_list)
{
ds_list_clear(command_list);
alarm[0] = room_speed;
ai_count = 0;
}

The above code checks a variable to see if it has reached a specific value and if it has it clears the ds_list indexed in the variable "command_list", sets an alarm, and resets the variable to 0.

Back: DS Lists
Next: ds_list_empty

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_copy

Copies one list into another.

Syntax:

ds_list_copy( id, source );

Argument | Description
id | The id of the list being copied to.
source | The id of the list to be copied from.

Returns: N/A

Description

With this function you can copy the contents of one list into another. Both lists must have been created previously and if the list being copied to already has information within it, this list will be cleared first. The end result is two independent lists which contain the same information.

Example:

if !ds_list_empty(main_list)
{
old_list = ds_list_create();
ds_list_copy(old_list, main_list);
ds_list_clear(main_list);
}

The above code will check a ds_list to see if it is empty. If it is not empty it is copied into another ds_list (which has been created previously) and then the original list is cleared.

Back: DS Lists
Next: ds_list_read

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_create

Creates a new list, returning its id.

Syntax:

ds_list_create();

Returns: Real

Description

This function will create a new list data-structure and return the index value. This value should be stored in a variable and used in all further function calls relating to the list.

Example:

list = ds_list_create();

This will create a new list and assign its index id to the instance variable "list".

Back: DS Lists
Next: ds_list_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_delete

Deletes the value at a given position in the list.

Syntax:

ds_list_delete(id, pos);

Argument | Description
id | The id of the list to change.
pos | Where in the list to delete the value.

Returns: N/A

Description

With this function you can remove the value stored at a specific position within the list.

Example:

if ds_list_size(sc_list)>10
{
while (ds_list_size(sc_list) > 10)
{
ds_list_delete(sc_list, 0);
}
}

The above code checks the size of a ds_list and if it is larger than ten, it loops through the list removing the top value (position 0) until the list has only 10 entries.

Back: DS Lists
Next: ds_list_find_index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_destroy

Destroys a given list and removes it from memory.

Syntax:

ds_list_destroy(id);

Argument | Description
id | The id of the data structure to remove.

Returns: N/A

Description

This function will remove the given list data-structure from memory, freeing up the resources it was using and removing all values that it contained. This function should always be used when you are finished using the ds_list to prevent memory leaks that can slow down and crash your game.

Example:

if lives = 0
{
ds_list_destroy(AI_list);
room_goto(rm_Menu);
}

The above code will check the value of the built in global variable "lives" and if it is 0, it destroys the ds_list indexed in the variable "AI_list" and then changes rooms.

Back: DS Lists
Next: ds_list_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_empty

Returns whether the given list is empty or not.

Syntax:

ds_list_empty(id);

Argument | Description
id | The id of the data structure to check.

Returns: Boolean

Description

With this function you can check the given ds_list to see if it is empty (returns true) or not (returns false).

Example:

if count == 15 && !ds_list_empty(command_list)
{
ds_list_clear(command_list);
alarm[0] = room_speed;
count = 0;
}

The above code checks a variable to see if it has reached a specific value and if it has it clears the ds_list indexed in the variable "command_list", sets an alarm, and resets the variable to 0.

Back: DS Lists
Next: ds_list_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_find_index

Finds the position of a given value in the list.

Syntax:

ds_list_find_index(id, val);

Argument | Description
id | The id of the list to use.
val | The value to find.

Returns: Real

Description

With this function you can check the given list for a value and the position within the list for that value will be returned. Note that if there are more than one entries in the list with the same value, the position of any one of them may be returned, and that if the value does not exist, then -1 will be returned. Note that the value can be an array, which you can check with the function is_array.

Example:

pos = ds_list_find_index(list, "Player1");

The above code checks the list indexed in the variable "list" for the value "Player1" and stores the returned position in the variable "pos".

Back: DS Lists
Next: ds_list_find_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_find_value

Finds the value held at a given position in the list.

Syntax:

ds_list_find_value(id, pos);

Argument | Description
id | The id of the list to use.
pos | The position to look at, where 0 corresponds to the very beginning of the list and the final position is ds_list_size(id)-1.

Returns: Real, String or Undefined

Description

With this function you can check the given list position and the value held within the list for that position will be returned.

NOTE: If you give a position that is outside of the given list size (ie: position 11 in a 10 value list) then the function will return <undefined>. You should always check this using the is_undefined() function.

Example:

val = ds_list_find_value(list, ds_list_size(list) - 1);

The above code checks the list indexed in the variable "list" at the last position in the list and stores the returned value in the variable "val".

Back: DS Lists
Next: ds_list_insert

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_insert

Inserts the given value to any position in the list.

Syntax:

ds_list_insert(id, pos, val);

Argument | Description
id | The id of the list to add to.
pos | The position to add the value, where 0 corresponds to the very beginning of the list and the final position is ds_list_size(id)-1.
val | The value to add to the list.

Returns: N/A

Description

This function will add the given value into the list at the given position. if the list contains more values after the given position, their position will be shifted up one to make room making the list larger by one.

Example:

ds_list_insert(list, 9, score);

The above code will add the value stored in the variable "score" into the 10th position of the list indexed by the variable "list" (lists are counted from 0, so a ten value list is numbered from 0 - 9).

Back: DS Lists
Next: ds_list_replace

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_mark_as_list

"Marks" a given ds_list position as being another ds_list.

Syntax:

ds_list_mark_as_list(id, pos);

Argument | Description
id | The id of the list to mark.
pos | The position within the list to mark.

Returns: N/A

Description

This function will "mark" (or "flag") a given position within a previously created ds_list as holding another ds_list. This functionality is designed only for use when encoding JSON strings (which you can create using json_encode) and the complimentary ds map functions.

NOTE: Once a ds_list has had a value within it flagged as another list or map, destroying the list will also destroy the marked lists and maps too. This means that you do not have to manually go through the list contents and destroy the marked data structures individually before destroying the "parent" list.

Example:

var j_list = ds_list_create();
var sub_list = ds_list_create();
ds_list_add(sub_list, health);
ds_list_add(sub_list, lives);
ds_list_add(sub_list, score);
ds_list_add(j_list, sub_list);
ds_list_mark_as_list(j_list, 0);

The above code creates two ds_lists, then populates one with various values from global variables. This list is then added into the second list, and the position "marked" as such so that it can be correctly encoded later.

Back: DS Lists
Next: ds_list_mark_as_map

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_mark_as_map

"Marks" a given ds_list position as being a ds_map.

Syntax:

ds_list_mark_as_map(id, pos);

Argument | Description
id | The id of the list to mark.
pos | The position within the list to mark.

Returns: N/A

Description

This function will "mark" (or "flag") a given position within a previously created ds_list as holding a previously created ds_map. This functionality is designed only for use when encoding JSON strings (which you can create using json_encode) and the complimentary ds map functions.

NOTE: Once a ds_list has had a value within it flagged as another list or map, destroying the list will also destroy the marked lists and maps too. This means that you do not have to manually go through the list contents and destroy the marked data structures individually before destroying the "parent" list.

Example:

var sub_map = ds_map_create();
ds_map_add(sub_map, "player", player_array);
ds_map_add(sub_map, "enemy", enemy_array);
ds_list_add(j_list, sub_map);
ds_list_mark_as_map(j_list, 0);

The above code creates a ds_map and then populates it with two keys, each containing an array of values. This map is then added into the given ds_list, and the position "marked" as such so that it can be correctly encoded later.

Back: DS Lists
Next: ds_list_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_read

Reads the list data structure from a string.

Syntax:

ds_list_read(id, str [, legacy]);

Argument | Description
id | The id of the data structure to read into.
str | The string to read from.
legacy (optional) | Can be either true or false or omitted completely.

Returns: N/A

Description

With this function you can recreate a saved ds_list (one that has previously been written as a string using ds_list_write). You must first create a new ds_list to read the string into, and if the ds_list already exists and has information stored in it, then this will be cleared before reading. This function is of vital importance when creating save/load mechanisms for your game.Note that if the data structure was created with previous versions of GameMaker you should add the optional argument "legacy", setting it to true as the string format has changed with this version.

Example:

list = ds_list_create();
ini_open("save.ini");
var str = ini_read_string("Lists", "0", "");
if str != ""
{
ds_list_read(list, str);
}
ini_close();

The above code creates a list and stores the index in the variable "list". It then opens an ini file and reads a string from that, checking to make sure that the string is not returned as empty first. This string is then read into the newly created ds_list.

Back: DS Lists
Next: ds_list_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_replace

Replaces the value to any position in the list with a given other value.

Syntax:

ds_list_replace(id, pos, val);

Argument | Description
id | The id of the list to change.
pos | The position to replace the value, where 0 corresponds to the very beginning of the list and the final position is ds_list_size(id)-1.
val | The new value to replace the given value with.

Returns: N/A

Description

This function will replace the value at the given position for another one.

Example:

ds_list_replace(n_list, 3, name);

The above code will replace the value stored at position 3 in the list for that stored in the variable "name".

Back: DS Lists
Next: ds_list_shuffle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_set

Sets a given list position to a value.

Syntax:

ds_list_set(id, pos, val);

Argument | Description
id | The id of the list to add to.
pos | The position within the list to set.
[val2, ... max_val] | The value to add to the list.

Returns: N/A

Description

This function can be used to set a previously added list entry. You give the list ID (as returned when you created the list) and the position within the list to set as well as the value to set it to. Note that if the entry being set is outside the bounds of the list (ie, you set list entry 20 but the current list only contains 10 entries) then the list will be filled to the given position and each entry will be set to 0.

Example:

for (var i = 0; i < ds_list_size(list); i++;)
{
ds_list_set(list, i, -1);
}

The above code will add the value stored in the "score" variable into the list indexed in the variable "sc_list".

Back: DS Lists
Next: ds_list_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_shuffle

Shuffles the values in the given list to a random order.

Syntax:

ds_list_shuffle(id);

Argument | Description
id | The id of the list to shuffle.

Returns: N/A

Description

With this function you can shuffle a list, which will re-order all the component values into random positions from those in which they were originally added to the list.

NOTE: This function will shuffle the list items to the same positions every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game. This is only true when testing and debugging the game, as the final executable package will not show this behaviour and will be random every play.

Example:

if restart
{
ds_list_shuffle(card_list);
}

The above code will shuffle the list indexed in the variable "card_list" if the variable "restart" is flagged as true.

Back: DS Lists
Next: ds_list_sort

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_size

Returns the number of values stored in the given list.

Syntax:

ds_list_size(id);

Argument | Description
id | The id of the data structure to check.

Returns: Real

Description

This function will return the "size" of the list, ie: the number of items that have been added into it.

Example:

if !ds_list_empty(control_list)
{
num = ds_list_size(control_list);
}

The above code checks a ds_list to see if it is empty or not, and if it is not, it gets the number of items that it contains and stores the value in a variable.

Back: DS Lists
Next: ds_list_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_sort

Sorts the values in the list according to their size, either ascending or descending.

Syntax:

ds_list_sort(id, ascend);

Argument | Description
id | The id of the list to sort.
ascend | Whether the values should be ascending (true) or descending (false) order.

Returns: N/A

Description

With this function you can sort all the values within a list, either in ascending or descending order. If the list contains strings, these will be sorted alphabetically, based on the english 26 letter alphabet.

Example:

if newgame
{
ds_list_sort(name_list, true);
}

The above code will sort the list indexed in the variable "name_list" if the variable "newgame" is flagged as true.

Back: DS Lists
Next: ds_list_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_list_write

Writes the data structure out as a string.

Syntax:

ds_list_write(id);

Argument | Description
id | The id of the data structure to write.

Returns: String

Description

This function returns a string which can then be stored or transferred to another data structure using the ds_list_read function.

NOTE: The returned string is not a human readable string, but rather a dump of the contents of the data-structure

Example:

var str;
ini_open("save.ini");
str =ds_list_write(list);
ini_write_string("Lists", "0", str);
ds_list_clear(list);
ini_close();

The above code opens an ini file and then writes a string containing the information stored in the ds_list indexed in the variable "list". The list is then cleared and the ini file closed.

Back: DS Lists
Next: ds_list_mark_as_list

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


DS Maps

A ds_map is a data structure that stores data in linked pairs consisting of a key and a corresponding value.

The ds_map data structure is an exceptionally useful one as it lets you store key and value pairs. For example, a character in your game can have a quantity of different items (keys) and for each individual item he can have a number of them (values), like in an RPG where you can have 10 health potions, 5 mana potions and 100 gold. Maps maintain such pairs all together in the one place and you can add pairs to the map and search for the value corresponding to certain keys as well using some simple functions. There are a couple of things you should know about maps before you use them, however! Maps are not sorted in any (recognisable) way, meaning that to find a certain key you may have to iterate through the whole thing (which is very slow). There is also no way to hold two keys that are the same, nor can you assign one key two values.

NOTE: The ds_map functions have changed since previous versions of GameMaker so imported games may not work or behave as you expect.

NOTE: As with all dynamic resources, data structures take up memory and so should always be destroyed when no longer needed to prevent memory leaks which will slow down and eventually crash your game.

The following functions exist that deal with DS maps.

  1. ds_map_exists
  2. ds_map_create
  3. ds_map_add
  4. ds_map_clear
  5. ds_map_copy
  6. ds_map_replace
  7. ds_map_delete
  8. ds_map_empty
  9. ds_map_size
  10. ds_map_find_first
  11. ds_map_find_last
  12. ds_map_find_next
  13. ds_map_find_previous
  14. ds_map_find_value
  15. ds_map_read
  16. ds_map_write
  17. ds_map_destroy

There are four further functions available for saving and loading a ds_map. These functions will encrypt the map and store it in a secure location on the target platform, so you can use this to save In App Purchase details, passwords, sensitive game information, etc...

  1. ds_map_secure_save
  2. ds_map_secure_save_buffer
  3. ds_map_secure_load
  4. ds_map_secure_load_buffer

Apart from these specific functions you can all use an expression (called an accessor) to add or modify the contents of your ds_map. This accessor looks similar to a 1D array with the following syntax:

map_index[? key]

You can find more information, plus examples, from from the GML Overview page on Accessors.

JSON And Ds_maps

One of the uses that ds_maps have is when working with JSON, and so there are a few special functions that are specific to that:

  1. ds_map_add_list
  2. ds_map_add_map
  3. ds_map_replace_list
  4. ds_map_replace_map

There are also a couple of complimentary functions for ds_lists:

  1. ds_list_mark_as_list
  2. ds_list_mark_as_map

NOTE: While these functions permit you to add lists and maps within a map, they are useless for anything other than JSON, and nested maps and lists will not be read correctly if written to disk or accessed in any other way.

NOTE: if you need to check if a data structure exists, you can use the ds_exists() function.

Back: Data Structures
Next: DS Priority Queues

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_add

Adds the given value and associated key into the map.

Syntax:

ds_map_add(id, key, val);

Argument | Description
id | The id of the map to add to.
key | The key of the value to add.
val | The value to add to the map.

Returns: Boolean

Description

This function should be used to add sets of key/value pairs into the specified ds_map. You can check this function to see if it was successful or not, as it may fail if there already exists the same key in the ds_map or you specify a non-existent ds_map as the id of the map to add to. Both keys and values can be made up of either integers or strings, so all of the following are acceptable:

ds_map_add(map, 5, 1);
ds_map_add(map, "level", 100);
ds_map_add(map, 89, "hello world");
ds_map_add(map, "fish", "good");

You can also add to a map using the accessor "?", as shown below:

map[? 5] = 1;
map[? "level"] = 100;
map[? 89] = "hello world";
map[? "fish"] = "good";

NOTE: Unlike other data structures in GameMaker: Studio this key will not go to the start (nor the end) of the ds_map, but rather it will just go into the ds_map somewhere.

Example:

inventory = ds_map_create();
ds_map_add(inventory, "hp potion", 1);
ds_map_add(inventory, "gold", 100);

This will create a new map, assigning its id to the variable "inventory". It then adds two new keys to the map, "hp potion" and "gold", and sets their initial values as 1 and 100.

Back: DS Maps
Next: ds_map_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_add_list

Adds a previously created ds_list to a given ds_map.

Syntax:

ds_map_add_list(id, key, value)

Argument | Description
id | The id of the map to use.
key | The key for the added list.
value | The id of the list to add.

Returns: N/A

Description

With this function you can assign a (previously created) ds_list to a key within the given ds_map. This function is designed for creating JSON compatible maps which you would then encode using json_encode and should only be used in conjunction with that functionality. If a ds_map has a list added in this way, destroying the parent map will also destroy the contained lists and free their memory.

Example:

var j_list = ds_list_create();
ds_list_add(j_list, health);
ds_list_add(j_list, lives);
ds_list_add(j_list, score);
var j_map = ds_map_create();
ds_map_add_list(j_map, "list", j_list);
var j = json_encode(j_map);
ds_map_destroy(j_map);

The above code will create a list and populate it with the various values of global variables. This list is then "nested" within a ds_map, and the map is then encoded into a JSON string, before the map is destroyed, removing it, and any lists it contains, from memory.

Back: DS Maps
Next: ds_map_add_map

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_add_map

Adds a previously created ds_map to a given ds_map.

Syntax:

ds_map_add_map(id, key, value)

Argument | Description
id | The id of the map to use.
key | The key for the added map.
value | The id of the map to add.

Returns: N/A

Description

With this function you can assign a (previously created) ds_map to a key within the given ds_map. This function is designed for creating JSON compatible maps which you would then encode using json_encode and should only be used in conjunction with that functionality. If a ds_map has another map added in this way, then destroying the parent map will also destroy the contained maps and free their memory.

Example:

var j_map = ds_map_create();
var j_list = ds_list_create();
var sub_map = ds_map_create();
ds_map_add_list(sub_map, "list", j_list);
ds_map_add(sub_map, "array", j_array);
ds_map_add_map(j_map, "map", sub_map);
var j = json_encode(j_map);
ds_map_destroy(j_map);

The above code will create two ds_maps, and then populate one with a list and an array before adding it into the second, which is then encoded into a JSON string. The map is then destroyed to remove it, and any other maps or lists that it contains, from memory.

Back: DS Maps
Next: ds_map_replace_list

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_clear

Clears all of the data from a given map.

Syntax:

ds_map_clear(id);

Argument | Description
id | The id of the data structure to clear.

Returns: N/A.

Description

This function will clear the (previously created) ds_map of all key/value pairs, but it will not delete the ds_map itself from memory. For that you should use the function ds_map_destroy.

Example:

if global.new_game
{
ds_map_clear(inventory);
}

The above function will check a global variable to see if it is true and, if it is, then the ds_map indexed in the instance variable "inventory" will be cleared of all key/value pairs (but it is not destroyed).

Back: DS Maps
Next: ds_map_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_copy

Copies the contents of an entire map into another id.

Syntax:

ds_map_copy(id, source);

Argument | Description
id | The id of the map you are copying to
source | The id of the map you are copying from

Returns: N/A

Description

You can use this function to copy the contents of one map into another one that you have previously created using ds_map_create(). If the ds_map that is being copied to is not empty, then this function will clear it first before copying. The original ds_map remains un-changed by this process.

Example:

inventory_2 = ds_map_create();
ds_map_copy(inventory_2, inventory_1);

The above code will create a new map and assign it to the variable "inventory_2". It will then copy the contents of the ds_map indexed in the variable "inventory_1" to this new map.

Back: DS Maps
Next: ds_map_replace

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_create

Creates a new ds_map.

Syntax:

ds_map_create();

Returns: Map id.

Description

This function is used to create a new, empty, ds_map and will return its id which is then used to access the data structure in all other ds_map functions.

Example:

inventory = ds_map_create();

The above code will create a new, empty ds_map and store its id index in the variable "inventory".

Back: DS Maps
Next: ds_map_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_delete

Deletes the key from the ds_map.

Syntax:

ds_map_delete(id, key);

Argument | Description
id | The id of the map to change.
key | The key (along with its associated value) to delete.

Returns: N/A

Description

With this function you can remove any given key (and its corresponding value) from the given, previously created, ds_map.

Example:

ds_map_delete(inventory, "shield");

The above code will delete the key "shield" (and the value it is paired with) from the ds_map (inventory).

Back: DS Maps
Next: ds_map_empty

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_destroy

Destroys a given map permanently, removing it from memory.

Syntax:

ds_map_destroy(id);

Argument | Description
id | The id of the map to destroy.

Returns: N/A.

Description

Ds_maps take up space in memory, which is allocated to them when they are created. This means that you also need to free this memory when the ds_map is not needed to prevent errors, memory leaks and loss of performance when running your game. This function does just that.

Example:

ds_map_destroy(inventory);

The above code will destroy the ds_map with the id indexed in the variable "inventory".

Back: DS Maps
Next: ds_map_secure_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_empty

Returns whether the given map is empty of key/value pairs or not.

Syntax:

ds_map_empty(id);

Argument | Description
id | The id of the data structure to check.

Returns: Boolean.

Description

This function will simply return false if the specified (previously created) ds_map contains any key/value pairs, or true if it does not.

Example:

if ds_map_empty(inventory)
{
weight = 0;
}

The above code checks to see if the ds_map indexed in the variable "inventory" has any key/value pairs and if it does not it sets the variable "weight" to 0.

Back: DS Maps
Next: ds_map_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_exists

Returns if the given key exists or not in the ds_map specified.

Syntax:

ds_map_exists(id, key);

Argument | Description
id | the id of the data structure to check
key | the key to check for

Returns: boolean

Description

This function will return true if the specified key exists in the (previously created) ds_map, and false if it does not.

Example:

if !ds_map_exists(inventory, "potions")
{
ds_map_add(inventory, "potions", 1);
}

The above code will check the ds_map indexed in the variable "inventory" for the key "potions" and if it doesn't exist it will add it to the map.

Back: DS Maps
Next: ds_map_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_find_first

Finds and returns the first key, as stored by the computer, in the ds_map.

Syntax:

ds_map_find_first(id);

Argument | Description
id | The id of the map to use.

Returns: Real or String

Description

This function returns the first key stored in the ds_map. This is not the first key in the order you added them! Ds_maps are not stored in a linear form, for that use ds_lists, so all this does is find the first key as stored by the computer. This can be useful if your have to iterate through the ds_map looking for something, but should be avoided if possible as it can be slow.

Example:

var size = ds_map_size(inventory) ;
var key = ds_map_find_first(inventory);
for (var i = 0; i < size; i++;)
{
if key != "gold"
{
key = ds_map_find_next(inventory, key);
}
else break;
}

The above code creates some temporary variables and then gets the ds_map size and finds the first key as stored by the computer in the map. It then uses a for loop to iterate through the ds_map looking for the key value "gold". If it finds it, it breaks out the loop.

Back: DS Maps
Next: ds_map_find_last

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_find_last

Finds and returns the last key, as stored by the computer, in the ds_map.

Syntax:

ds_map_find_last(id);

Argument | Description
id | The id of the map to use.

Returns: Real or string

Description

This function returns the last key stored in the ds_map. This is not the last key in the order that you have added them! Ds_maps are not stored in a linear form, for that use ds_lists, so all this does is find the last key as stored by the computer. This can be useful if your have to iterate through the ds_map looking for something, but should be avoided if possible as it can be slow.

Example:

var size, key, i;
size = ds_map_size(inventory);
key = ds_map_find_last(inventory);
for (i = size; i > 0; i--;)
{
if key != "gold" key = ds_map_find_previous(inventory, key) else break;
}

The above code creates some temporary variables and then gets the ds_map size and finds the last key as stored by the computer in the map. It then uses a for loop to iterate back through the ds_map looking for the key value "gold". If it finds it, it breaks out the loop.

Back: DS Maps
Next: ds_map_find_next

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_find_next

Finds and returns the next key in the ds_map after the one specified in the function.

Syntax:

ds_map_find_next(id, key);

Argument | Description
id | The id of the map to use.
key | The key to find the next one to.

Returns: Real, string or undefined

Description

This function returns the next key stored in the ds_map after the one specified in the function. This can be useful if your have to iterate through the ds_map looking for something, but should be avoided if possible as it can be slow. If no such key exists then the function will return <undefined>. You should always check this using the is_undefined() function.

Example:

var size, key, i;
size = ds_map_size(inventory);
key = ds_map_find_first(inventory);
for (i = 0; i < size; i++;)
{
if key != "gold" key = ds_map_find_next(inventory, key) else break;
}

The above code creates some temporary variables and then gets the ds_map size and finds the first key as stored by the computer in the map. It then uses a for loop to iterate through the ds_map looking for the key value "gold". If it finds it, it breaks out the loop.

Back: DS Maps
Next: ds_map_find_previous

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_find_previous

Finds and returns the previous key in the ds_map above the one specified in the function.

Syntax:

ds_map_find_previous(id, key);

Argument | Description
id | The id of the map to use.
key | The key to find the previous one to.

Returns: Real, string or undefined

Description

This function returns the next key stored in the ds_map after the one specified in the function. This can be useful if your have to iterate through the ds_map looking for something, but should be avoided if possible as it can be slow. If no such key exists then the function will return <undefined>. You should always check this using the is_undefined() function.

Example:

var size, key, i;
size = ds_map_size(inventory) - 1;
key = ds_map_find_last(inventory);
for (i = size; i > 0; i --;)
{
if key != "gold" key = ds_map_find_previous(inventory, key) else break;
}

The above code creates some temporary variables and then gets the ds_map size and finds the last key as stored by the computer in the map. It then uses a for loop to iterate back through the ds_map looking for the key value "gold". If it finds it, it breaks out the loop.

Back: DS Maps
Next: ds_map_find_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_find_value

Finds the key specified and returns the paired value from the ds_map.

Syntax:

ds_map_find_value(id, key)

Argument | Description
id | The id of the map to use.
key | The key to find.

Returns: Real, string or undefined

Description

With this function you can get the value from a specified key. The input values of the function are the (previously created) ds_map to use and the key to check for.

NOTE: If no such key exists then the function will return <undefined>. You should always check this using the is_undefined() function.

Example:

amount = ds_map_find_value(inventory, "food");

Or, using the map accessor "?":

amount = inventory[? "food"];

The above code will get the value of the key "food" and store it in the variable "amount".

Back: DS Maps
Next: ds_map_read

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_read

Reads the map data structure from a string.

Syntax:

ds_map_read(id, str [, legacy]);

Argument | Description
id | The id of the data structure to read the string into
str | The string to read
legacy (optional) | Can be either true or false or omitted completely.

Returns: N/A.

Description

This function will take a string that has previously been created by the function ds_map_write and then read it into a previously created ds_map. If the map that the string is being read into contains any key/value pairs, these will be cleared first before the saved map is re-constructed. Note that if the data structure was created with previous versions of GameMaker you should add the optional argument "legacy", setting it to true as the string format has changed with this version.

Example:

inventory = ds_map_create();
ini_open("map.ini");
var t_string = ini_read_string("Saved", "0", "");
if t_string != ""
{
ds_map_read(inventory, t_string);
}
ini_close();

The above code creates a new ds_map and stores its id index in the variable "inventory". It then opens an ini file and reads a string from that file into the temporary variable "t_string". Finally, it checks to make sure that the string is valid (not the default ini value of "") and if it is it then reads the string into the newly created ds_map before closing the ini again.

Back: DS Maps
Next: ds_map_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_replace

Replaces the value of a given key in the map with a new value.

Syntax:

ds_map_replace( id, key, val );

Argument | Description
id | The id of the map to change.
key | The key with the value that should be replaced by the new one
val | The new value to replace the given value with

Returns: N/A.

Description

With this function you can change the value for the given key within the (previously created) ds_map. Please note that if the key to be replaced does not exists, it is created and the given value assigned to it.

Example:

ds_map_replace(inventory, "torso", 55);

The above code looks up the ds_map for the key "torso" and when it finds it (or it is created if it doesn't exist) the current value is replaced with the one specified.

Back: DS Maps
Next: ds_map_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_replace_list

Replace a list with another list after it has been added to a ds_map.

Syntax:

ds_map_replace_list(id, key, value)

Argument | Description
id | The id of the map to use.
key | The key to replace.
value | The id of the ds_list to use to replace the one previously stored in the given key.

Returns: N/A

Description

With this function you can replace a ds_list that has been stored in the given "key" with another list that has been created previously. This function is designed for creating JSON compatible maps which you would then encode using json_encode and should only be used in conjunction with that functionality.

Example:

var j_list = ds_list_create();
ds_list_add(j_list, health);
ds_list_add(j_list, lives);
ds_list_add(j_list, score);
ds_map_replace_list(j_map, "list", j_list);
var j = json_encode(j_map);
ds_list_destroy(j_list);

The above code will create a ds_list and populate it with the values of various global variables before replacing a previously stored list in the ds_map "j_map".

Back: DS Maps
Next: ds_map_replace_map

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_replace_map

list

Replace a ds_map that has been previously added into a distinct ds_map, with another ds_map.

Syntax:

ds_map_replace_map(id, key, value)

Argument | Description
id | The id of the ds_map to use.
key | The key to replace.
value | The id of the ds_map to use to replace the one previously stored in the given key.

Returns: N/A

Description

With this function you can replace a ds_map that has been stored in the given "key" with another map that has been created previously. This function is designed for creating JSON compatible maps which you would then encode using json_encode and should only be used in conjunction with that functionality.

Example:

var temp_map = ds_map_create();
ds_map_add_list(temp_map, "list", j_list);
ds_map_add(temp_map, "array", j_array);
ds_map_replace_map(j_map, "maps", temp_map);
var j = json_encode(j_map);
ds_map_destroy(temp_map);

The above code will create a ds_map and populate it with an array and a ds_list before replacing a previously stored map in the ds_map "j_map".

Back: DS Maps
Next: ds_map_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_secure_load

This function will create a ds_map containing the key/value data from a secure file.

Syntax:

ds_map_secure_load(filename);

Argument | Description
filename | The name of the file to load the map data from.

Returns: Ds_map Index

Description

This function will load a previously saved ds_map from the given file. This file must have been previously created using the ds_map_secure_save() function, and, when loaded, the function will return the index of the ds_map that has been created from the loaded data. This ds_map index should be stored in a variable and used for all further function calls to this map.

Example:

p_map = ds_map_secure_load("p_data.dat");

The above code will load a securely saved ds_map and store its index value in a variable for future use.

Back: DS Maps
Next: ds_map_secure_load_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_secure_load_buffer

Syntax:

ds_map_secure_load_buffer(buffer);

Argument | Description
filename | The buffer ID of the buffer to load the map data from.

Returns: DS Map

Description

This function will load a secure saved DS map from a buffer. You must previously have loaded the buffer into memory (using buffer_load) and then passing that into this function will return a DS map populated with the contents of the buffer. Note that the buffer must have been created using the function ds_map_secure_save_buffer for this to work correctly.

Example:

var buff = buffer_load("save.dat");
map = ds_map_secure_load_buffer(buff);
buffer_delete(buff);

The above code will load a securely saved ds_map from a buffer and store its index value in a variable for future use.

Back: DS Maps
Next: ds_map_add_list
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_secure_save

This function will save the given ds_map to a secure location on the target platform.

Syntax:

ds_map_secure_save(map, filename);

Argument | Description
map | The id of the data structure to use
filename | The name of the file to save the map to

Returns: Boolean

Description

This function will save the contents of the given ds_map to a file. The file itself can have almost any extension (for example, *.dat, *.json, *.bin, etc...) and will be encrypted and stored to a safe location on the target platform. In this way you can store sensitive information, like in app purchase details or passwords, locally in a secure way. you can then re-load the ds_map using the function ds_map_secure_load().

Example:

ds_map_secure_save(purchase_map, "p_data.dat");

The above code will save the ds_map indexed in the variable "p_data" to the given file for later retrieval.

Back: DS Maps
Next: ds_map_secure_save_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_secure_save_buffer

Syntax:

ds_map_secure_save_buffer(filename);

Argument | Description
id | The DS map ID value.
buffer | The buffer ID value.

Returns: Ds_map Index

Description

This function will save a previously created DS map to a buffer. You supply the DS map ID value (as returned by the function ds_map_create) and the ID of the buffer to write to (as returned by the function buffer_create).

Example:

buff = buffer_create(128,buffer_grow,4);
var map = ds_map_create();
ds_map_add(map,"bob","ajob");
ds_map_add(map,"money",10);
ds_map_secure_save_buffer(map, buff);
ds_map_destroy(map);

The above code will create a buffer and a DS map, then populate the map with some values and write it to the buffer before deleting the map.

Back: DS Maps
Next: ds_map_secure_load
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_size

Returns the size of given ds_map.

Syntax:

ds_map_size(id);

Argument | Description
id | The id of the data structure to check.

Returns: Real

Description

With this function you can find how many key/values pairs the (previously created) ds_map contains.

Example:

if ds_map_size(inventory) > 49
{
full = true;
}

The above code will check the size of the ds_map (ie: number of key/value pairs) and if it is greater than 49 it sets the variable "full" to true.

Back: DS Maps
Next: ds_map_find_first

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_map_write

This function writes the data from a ds_map as a string.

Syntax:

ds_map_write(id);

Argument | Description
id | The id of the data structure to use

Returns: String

Description

This function will turn the ds_map data of the specified map into string format which can then be written to an *.ini or a *.txt file for easy storage. This string can then be later read back into a new ds_map using ds_map_read().

NOTE: The returned string is not a human readable string, but rather a dump of the contents of the data-structure

Example:

ini_open("map.ini");
var t_string;
t_string = ds_map_write(inventory);
ini_write_string("Saved", "0", t_string);
ini_close();

The above code opens an ini file ready to be written to. It then uses ds_map_write() to generate a string which is stored in the temporary variable "t_string". Finally, it writes that string to the ini file before closing it.

Back: DS Maps
Next: ds_map_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


DS Priority Queues

A ds_priority is a data structure based on the importance value of the information it contains.

A ds_priority queue is a special data structure similar to a ds_queue, only here the queue of values is ordered by the priorities (always real numbers) that the values have been assigned. This structure can be very useful for constructing leaderboards or information lists where the importance of each entry can be weighted.

NOTE: As with all dynamic resources, data structures take up memory and so should always be destroyed when no longer needed to prevent memory leaks which will slow down and eventually crash your game.

The following functions exist that deal with ds_priority queues:

  1. ds_priority_create
  2. ds_priority_destroy
  3. ds_priority_clear
  4. ds_priority_empty
  5. ds_priority_size
  6. ds_priority_add
  7. ds_priority_change_priority
  8. ds_priority_delete_max
  9. ds_priority_delete_min
  10. ds_priority_delete_value
  11. ds_priority_find_max
  12. ds_priority_find_min
  13. ds_priority_find_priority
  14. ds_priority_copy
  15. ds_priority_read
  16. ds_priority_write

NOTE: if you need to check if a data structure exists, you can use the ds_exists() function.

Back: Data Structures
Next: DS Grids

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_add

Adds a prioritized value to the queue.

Syntax:

ds_priority_add(id, val, priority);

Argument | Description
id | The id of the priority queue to add to.
val | The value to add to the priority queue.
priority | The priority of the value to add.

Returns: N/A

Description

With this function you can add a value (either a real number or a string) to a priority queue, at the same time assigning it a priority value.

Example:

ds_priority_add(ai_priority, scr_AI_Search, 5);

The above code adds a script to the priority queue indexed in the variable "ai_priority" and assigns it a priority of 5.

Back: DS Priority Queues
Next: ds_priority_change_priority

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_change_priority

Changes the priority of the given value in the priority queue.

Syntax:

ds_priority_change_priority(id, val, priority);

Argument | Description
id | The id of the priority queue to change.
val | The value to change the priority of.
priority | The new priority of the value.

Returns: N/A

Description

This function will take a given value and change its priority within the referenced priority queue.

Example:

if global.Game_Time < 1000
{
ds_priority_change(ai_priority, scr_AI_Search, 1);
}

The above code checks a global variable and if it is below a certain value it will then change the priority of the script index held in the priority queue.

Back: DS Priority Queues
Next: ds_priority_delete_max

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_clear

Clears all of the data from a given priority queue.

Syntax:

ds_priority_clear(id);

Argument | Description
id | The id of the data structure to clear.

Returns: N/A

Description

With this function you can clear all data from the given priority queue data-structure. This does NOT destroy the data-structure (for that you should use ds_priority_destroy) it only wipes all data from it and returns an empty priority queue.

Example:

if count = 15 && !ds_priority_empty(command_queue)
{
ds_priority_clear(command_queue);
alarm[0] = room_speed;
ai_count = 0;
}

The above code checks a variable to see if it has reached a specific value and if it has it clears the ds_priority queue indexed in the variable "command_queue", sets an alarm, and resets the variable to 0.

Back: Priority Queues
Next: ds_priority_empty


ds_priority_copy

Copies a priority queue to another.

Syntax:

ds_priority_copy(id, source);

Argument | Description
id | The id of the priority queue to copy to.
source | The id of the priority queue to copy from.

Returns: N/A

Description

This function can be used to copy the contents of one priority queue into another. Note that this does NOT remove the contents from the original priority queue, nor does it destroy the original priority queue. When using this function the priority queue being copied to must have been previously created and if it contained any items before the copy, then these will be cleared first (meaning this information will be lost).

Example:

with (instance_create(x, y, obj_Enemy))
{
p_queue = ds_priority_create();
ds_priority_copy(p_queue, other.p_queue);
}

The above function creates a new instance and then in that instance it creates a new ds_priority and copies the contents of the priority queue in the instance running the code block, into the newly created instance priority queue.

Back: DS Priority Queues
Next: ds_priority_read

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_create

Creates a new priority queue, returning its id.

Syntax:

ds_priority_create();

Returns: Real

Description

This function will create a new priority queue data-structure and return the index value. This value should be stored in a variable and used in all further function calls relating to the priority queue.

Example:

p_queue = ds_priority_create();

This will create a new priority queue and assign its index id to the instance variable "p_queue".

Back: Priority Queues
Next: ds_priority_destroy


ds_priority_delete_max

Returns the value in the priority queue with the largest priority, and deletes it.

Syntax:

ds_priority_delete_max(id);

Argument | Description
id | The id of the priority queue to use.

Returns: Real or String

Description

This function will return the value that has the highest priority in the queue and then remove the value (and priority) from the data structure. If more than one value has the same priority, the one that was added to the priority queue first will be the one to get removed, but all other values with the same priority will still be in the queue.

Example:

if ai_move
{
script_execute(ds_priority_delete_max(ai_priority));
}

The above code checks an instance variable and if it returns true it will execute a script indexed in the priority queue with the highest priority value and then remove that script from the queue.

Back: DS Priority Queues
Next: ds_priority_delete_min

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_delete_min

Returns the value in the priority queue with the smallest priority, and deletes it.

Syntax:

ds_priority_delete_min(id);

Argument | Description
id | The id of the priority queue to use.

Returns: Real or String

Description

This function will return the value that has the lowest priority in the queue and then remove the value (and priority) from the data structure. If more than one value has the same priority, the one that was added to the priority queue first will be the one to get removed, but all other values with the same priority will still be in the queue.

Example:

if ai_move
{
script_execute(ds_priority_delete_min(ai_priority));
}

The above code checks an instance variable and if it returns true it will execute a script indexed in the priority queue with the lowest priority value and then remove that script from the queue.

Back: DS Priority Queues
Next: ds_priority_delete_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_delete_value

Deletes the given value (along with its priority) from the priority queue.

Syntax:

ds_priority_delete_value(id,val);

Argument | Description
id | The id of the priority queue to use.
val | The value to delete from the priority queue.

Returns: N/A

Description

This function will simply delete the given value, along with its priority, from the indexed priority queue.

Example:

if ai_move = false
{
ds_priority_delete_value(ai_priority, scr_AI_Move);
}

The above code checks an instance variable and if it returns false it will remove the indexed script from the priority queue.

Back: DS Priority Queues
Next: ds_priority_find_max

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_destroy

Destroys a given priority queue and removes it from memory.

Syntax:

ds_priority_destroy(id);

Argument | Description
id | The id of the data structure to remove.

Returns: N/A

Description

This function will remove the given priority queue data-structure from memory, freeing up the resources it was using and removing all values that it contained. This function should always be used when you are finished using the ds_priority queue to prevent memory leaks that can slow down and crash your game.

Example:

if lives = 0
{
ds_priority_destroy(AI_queue);
room_goto(rm_Menu);
}

The above code will check the value of the built in global variable "lives" and if it is 0, it destroys the ds_queue indexed in the variable "AI_queue" and then changes rooms.

Back: Priority Queues
Next: ds_priority_clear


ds_priority_empty

Returns whether the given priority queue is empty or not.

Syntax:

ds_priority_empty(id);

Argument | Description
id | The id of the data structure to check.

Returns: Boolean

Description

With this function you can check the given ds_priority queue to see if it is empty (returns true) or not (returns false).

Example:

if count == 15 && !ds_priority_empty(command_queue)
{
ds_priority_clear(command_queue);
alarm[0] = room_speed;
ai_count = 0;
}

The above code checks a variable to see if it has reached a specific value and if it has it clears the ds_priority queue indexed in the variable "command_queue", sets an alarm, and resets the variable to 0.

Back: Priority Queues
Next: ds_priority_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_find_max

Returns the value in the priority queue with the largest priority.

Syntax:

ds_priority_find_max(id);

Argument | Description
id | The id of the priority queue to use.

Returns: Real or String

Description

With this function you can find the value stored in the priority queue with the highest priority, and if more than one value has the same priority, the one that was added to the priority queue first will be the one to get returned. However, unlike ds_priority_delete_max, this function will not remove the value from the queue.

Example:

if ai_move
{
script_execute(ds_priority_find_max(ai_priority);
}

The above code checks an instance variable and if it returns true it will execute a script indexed in the priority queue with the highest priority value.

Back: DS Priority Queues
Next: ds_priority_find_min

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_find_min

Returns the value in the priority queue with the smallest priority without deleting it.

Syntax:

ds_priority_find_min(id);

Argument | Description
id | The id of the priority queue to use.

Returns: Real or String

Description

With this function you can find the value stored in the priority queue with the lowest priority, and if more than one value has the same priority, the one that was added to the priority queue first will be the one to get returned. However, unlike ds_priority_delete_min, this function will not remove the value from the queue.

Example:

if ai_move
{
script_execute(ds_priority_find_min(ai_priority);
}

The above code checks an instance variable and if it returns true it will execute a script indexed in the priority queue with the lowest priority value.

Back: DS Priority Queues
Next: ds_priority_find_priority

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_find_priority

Finds and returns the priority of the given value in the priority queue.

Syntax:

ds_priority_find_priority(id, val);

Argument | Description
id | The id of the priority queue to use.
val | The value to find the priority of.

Returns: Real or undefined

Description

With this function you can retrieve the priority of any given value. If the value does not exist in the priority queue then undefined will be returned.

Example:

p = ds_priority_find_priority(ai_priority, "intelligence");

The above code will store the returned priority for the given value in the instance variable "p".

Back: DS Priority Queues
Next: ds_priority_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_read

Reads the priority queue data structure from a string.

Syntax:

ds_priority_read(id, str [, legacy]);

Argument | Description
id | The id of the data structure to write.
str | The string to write from.
legacy (optional) | Can be either true or false or omitted completely.

Returns: N/A

Description

With this function you can recreate a saved ds_priority (one that has previously been written as a string using ds_priority_write). You must first create a new ds_priority to read the string into, and if the ds_priority already exists and has information stored in it, then this will be cleared before reading. This function is of vital importance when creating save/load mechanisms for your game. Note that if the data structure was created with previous versions of GameMaker you should add the optional argument "legacy", setting it to true as the string format has changed with this version.

Example:

p_queue = ds_priority_create();
ini_open("save.ini");
var str = ini_read_string("P_Queues", "0", "");
if str != ""
{
ds_priority_read(p_queue, str);
}
ini_close();

The above code creates a priority queue and stores the index in the variable "p_queue". It then opens an ini file and reads a string from that, checking to make sure that the string is not returned as empty first. This string is then read into the newly created ds_priority.

Back: DS Priority Queues
Next: ds_priority_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_size

Returns the number of values stored in the given priority queue.

Syntax:

ds_priority_size(id);

Argument | Description
id | The id of the data structure to check.

Returns: Real

Description

This function will return the "size" of the priority queue, ie: the number of items that have been prioritized in it.

Example:

if !ds_priority_empty(control_priority)
{
num = ds_priority_size(control_priority);
}

The above code checks a ds_priority queue to see if it is empty or not, and if it is not, it gets the number of items that it contains and stores the value in a variable.

Back: Priority Queues
Next: ds_priority_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_priority_write

Writes the data structure to a returned string. This enables the structure to be saved in something like an .ini file for future use.

Syntax:

ds_priority_write(id);

Argument | Description
id | The id of the data structure to check.

Returns: String

Description

This function returns a string which can then be stored or transferred to another data structure using the ds_priority_read function.

NOTE: The returned string is not a human readable string, but rather a dump of the contents of the data-structure

Example:

var str;
ini_open("save.ini");
str =ds_priority_write(p_queue);
ini_write_string("P_Queues", "0", str);
ds_priority_clear(p_queue);
ini_close();

The above code opens an ini file and then writes a string containing the information stored in the ds_priority queue indexed in the variable "p_queue". The priority queue is then cleared and the ini file closed.

Back: DS Priority Queues
Next: ds_priority_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


DS Queues

A ds_queue is a first-in-first-out data structure.

A ds_queue is somewhat similar to a ds_stack but it works on a first-in first-out (FIFO) basis. The value that is put into the queue first is also the first to be removed from it. You can think of it like a queue in a shop for paying, where the person that is first in the queue pays first and then leaves the shop. Queues are typically used to store actions or behaviours (in the form of scripts, for example) that still need to be done by an instance but there are many other uses.

NOTE: As with all dynamic resources, data structures take up memory and so should always be destroyed when no longer needed to prevent memory leaks which will slow down and eventually crash your game.

The following functions exist that deal with ds_queues:

  1. ds_queue_create
  2. ds_queue_destroy
  3. ds_queue_clear
  4. ds_queue_empty
  5. ds_queue_size
  6. ds_queue_dequeue
  7. ds_queue_enqueue
  8. ds_queue_head
  9. ds_queue_tail
  10. ds_queue_copy
  11. ds_queue_read
  12. ds_queue_write

NOTE: if you need to check if a data structure exists, you can use the ds_exists() function.

Back: Data Structures
Next: DS Lists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_clear

Clears all of the data from a given queue.

Syntax:

ds_queue_clear(id);

Argument | Description
id | The id of the data structure to clear.

Returns: N/A

Description

With this function you can clear all data from the given queue data-structure. This does NOT destroy the data-structure (for that you should use ds_queue_destroy) it only wipes all data from it and returns an empty queue.

Example:

if count = 15 && !ds_queue_empty(command_queue)
{
ds_queue_clear(command_queue);
alarm[0] = room_speed;
ai_count = 0;
}

The above code checks a variable to see if it has reached a specific value and if it has it clears the ds_queue indexed in the variable "command_queue", sets an alarm, and resets the variable to 0.

Back: Queues
Next: ds_queue_empty

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_copy

Copies the contents of one queue to another.

Syntax:

ds_queue_copy(id, source);

Argument | Description
id | The id of the NEW queue.
source | The ORIGINAL queue to copy to id.

Returns: N/A

Description

This function can be used to copy the contents of one queue into another. Note that this does NOT remove the contents from the original queue, nor does it destroy the original queue. When using this function the queue being copied to must have been previously created and if it contained any items before the copy, then these will be cleared first (meaning this information will be lost).

Example:

with (instance_create(x, y, obj_Enemy))
{
queue = ds_queue_create();
ds_queue_copy(queue, other.queue);
}

The above function creates a new instance and then in that instance it creates a new ds_queue and copies the contents of the queue in the instance running the code block, into the newly created instance queue.

Back: Queues
Next: ds_queue_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_create

Creates a new queue, returning its id.

Syntax:

ds_queue_create();

Returns: Real

Description

This function will create a new queue data-structure and return the index value. This value should be stored in a variable and used in all further function calls relating to the queue.

Example:

queue = ds_queue_create();

This will create a new queue and assign its index id to the instance variable "queue".

Back: Queues
Next: ds_queue_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_dequeue

Dequeues the value from the head of the queue.

Syntax:

ds_queue_dequeue(id);

Argument | Description
id | The id of the queue to dequeue from.

Returns: Real or String

Description

This function will dequeue the head value off of the ds_queue, removing it from the queue and returning the value to be stored in a variable.

Example:

if !ds_queue_empty(move_queue)
{
var xx, yy;
xx = ds_queue_dequeue(move_queue);
yy = ds_queue_dequeue(move_queue);
move_towards_point(xx, yy, 4);
}

The above code checks the ds_queue indexed in the variable "move_queue" to see if it is empty, and if it is not, it then dequeues the two values from the head of the queue and use them to set a direction for movement.

Back: Queues
Next: ds_queue_head

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_destroy

Destroys a given queue and removes it from memory.

Syntax:

ds_queue_destroy(id);

Argument | Description
id | The id of the data structure to remove.

Returns: N/A

Description

This function will remove the given queue data-structure from memory, freeing up the resources it was using and removing all values that it contained. This function should always be used when you are finished using the ds_queue to prevent memory leaks that can slow down and crash your game.

Example:

if lives = 0
{
ds_queue_destroy(AI_queue);
room_goto(rm_Menu);
}

The above code will check the value of the built in global variable "lives" and if it is 0, it destroys the ds_queue indexed in the variable "AI_queue" and then changes rooms.

Back: Queues
Next: ds_queue_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_empty

Returns whether the given queue is empty or not.

Syntax:

ds_queue_empty(id);

Argument | Description
id | The id of the data structure to check.

Returns: Boolean

Description

With this function you can check the given ds_queue to see if it is empty (returns true) or not (returns false).

Example:

if count == 15 && !ds_queue_empty(command_queue)
{
ds_queue_clear(command_queue);
alarm[0] = room_speed;
ai_count = 0;
}

The above code checks a variable to see if it has reached a specific value and if it has it clears the ds_queue indexed in the variable "command_queue", sets an alarm, and resets the variable to 0.

Back: Queues
Next: ds_queue_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_enqueue

Adds the given value (or values) into the given queue.

Syntax:

ds_queue_enqueue(id, val [, val2, ... val15]);

Argument | Description
id | The id of the queue to add to.
val | The value to add to the queue.
[val2, ... val15] | Optional values to be added to the queue.

Returns: N/A

Description

This function will add a value (real or string) onto the tail of the ds_queue. The function can take a further 14 optional arguments (making a total of 15 possible additions), permitting you to add multiple values consecutively to the tail of the queue in a single call.

Example:

move_queue = ds_queue_create();
ds_queue_enqueue(move_queue, x + 200);
ds_queue_enqueue(move_queue, y);
ds_queue_enqueue(move_queue, x + 200);
ds_queue_enqueue(move_queue, y + 200);
ds_queue_enqueue(move_queue, x);
ds_queue_enqueue(move_queue, y + 200);
ds_queue_enqueue(move_queue, x);
ds_queue_enqueue(move_queue, y);

The above code creates a new ds_queue and stores its index in the variable "move_queue". It then pushes a number of values onto the queue for future use.

Back: Queues
Next: ds_queue_dequeue

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_head

Reads the value from the head of the queue.

Syntax:

ds_queue_head(id);

Argument | Description
id | The id of the data structure to read from.

Returns: Real or String

Description

This function will only read the first value of the queue (that which is "at the head"). It will not dequeue the value, meaning that it can still be read in the future by this function or the ds_queue_dequeue.

Example:

num = ds_queue_head(control_queue);

The above code will read the value from the queue indexed in the variable "control_queue" and store the return value in the variable "num".

Back: Queues
Next: ds_queue_tail

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_read

Reads a queue data structure from a string.

Syntax:

ds_queue_read(id, str [, legacy]);

Argument | Description
id | The id of the data structure to read into.
str | The string to read from.
legacy (optional) | Can be either true or false or omitted completely.

Returns: N/A

Description

With this function you can recreate a saved ds_queue (one that has previously been written as a string using ds_queue_write). You must first create a new ds_queue to read the string into, and if the ds_queue already exists and has information stored in it, then this will be cleared before reading. This function is of vital importance when creating save/load mechanisms for your game. Note that if the data structure was created with previous versions of GameMaker you should add the optional argument "legacy", setting it to true as the string format has changed with this version.

Example:

queue = ds_queue_create();
ini_open("save.ini");
var str = ini_read_string("Queues", "0", "");
if str != ""
{
ds_queue_read(queue, str);
}
ini_close();

The above code creates a queue and stores the index in the variable "queue". It then opens an ini file and reads a string from that, checking to make sure that the string is not returned as empty first. This string is then read into the newly created ds_queue.

Back: Queues
Next: ds_queue_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_size

Returns the number of values stored in the given queue.

Syntax:

ds_queue_size(id);

Argument | Description
id | The id of the data structure to check.

Returns: Real

Description

This function will return the "size" of the queue, ie: the number of items that have been queued onto it.

Example:

if !ds_queue_empty(control_queue)
{
num = ds_queue_size(control_queue);
}

The above code checks a ds_queue to see if it is empty or not, and if it is not, it gets the number of items that it contains and stores the value in a variable.

Back: Queues
Next: ds_queue_enqueue

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_tail

Reads the value from the tail of the queue.

Syntax:

ds_queue_tail(id);

Argument | Description
id | The id of the data structure to read from.

Returns: Real or String

Description

This function will only read the last value of the queue (that which is "at the tail"). It will not dequeue the value, meaning that it can still be read in the future by this function or the ds_queue_dequeue.

Example:

num = ds_queue_tail(control_queue);

The above code will read the value from the queue indexed in the variable "control_queue" and store the return value in the variable "num".

Back: Queues
Next: ds_queue_read

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_queue_write

Writes the data structure out as a string.

Syntax:

ds_queue_write(id);

Argument | Description
id | The id of the data structure to write.

Returns: String

Description

This function returns a string which can then be stored or transferred to another data structure using the ds_queue_read function.

NOTE: The returned string is not a human readable string, but rather a dump of the contents of the data-structure

Example:

var str;
ini_open("save.ini");
str =ds_queue_write(queue);
ini_write_string("Queues", "0", str);
ds_queue_clear(queue);
ini_close();

The above code opens an ini file and then writes a string containing the information stored in the ds_queue indexed in the variable "queue". The queue is then cleared and the ini file closed.

Back: Queues
Next: ds_queue_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


DS Stacks

A ds_stack is a last-in-first-out data structure.

A stack data structure is a so called last-in-first-out (LIFO) structure. You can push values onto a stack and the remove them again by popping them from the stack, and the value that was pushed on the stack most recently is the first to be popped from it again (just think of a stack of coins, where each coin that you add has to be removed again first before you can get to the rest of the coins beneath). Stacks are often used when there are interrupts to handle, or when having recursive functions, or even when constructing a rudimentary AI for your games.

NOTE: As with all dynamic resources, data structures take up memory and so should always be destroyed when no longer needed to prevent memory leaks which will slow down and eventually crash your game.

The following functions exist that deal with DS Stacks.

  1. ds_stack_create
  2. ds_stack_destroy
  3. ds_stack_clear
  4. ds_stack_empty
  5. ds_stack_size
  6. ds_stack_copy
  7. ds_stack_top
  8. ds_stack_pop
  9. ds_stack_push
  10. ds_stack_read
  11. ds_stack_write

NOTE: if you need to check if a data structure exists, you can use the ds_exists() function.

Back: Data Structures
Next: Queues

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_clear

Clears all of the data from a given stack.

Syntax:

ds_stack_clear(id);

Argument | Description
id | The id of the data structure to clear.

Returns: N/A

Description

With this function you can clear all data from the given stack data-structure. This does NOT destroy the data-structure (for that you should use ds_stack_destroy) it only wipes all data from it and returns an empty stack.

Example:

if ai_count = 15 && !ds_stack_empty(AI_stack)
{
ds_stack_clear(AI_stack);
alarm[0] = room_speed;
ai_count = 0;
}

The above code checks a variable to see if it has reached a specific value and if it has it clears the ds_stack indexed in the variable "AI_stack", sets an alarm, and resets the variable to 0.

Back: Stacks
Next: ds_stack_empty

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_copy

Copies the contents of one stack to another.

Syntax:

ds_stack_copy(id, source);

Argument | Description
id | The id of the NEW stack.
source | The ORIGINAL stack to copy to id.

Returns: N/A

Description

This function can be used to copy the contents of one stack into another. Note that this does NOT remove the contents from the original stack, nor does it destroy the original stack. When using this function the stack being copied to must have been previously created and if it contained any items before the copy, then these will be cleared first (meaning this information will be lost).

Example:

with (instance_create(x, y, obj_Enemy))
{
stack = ds_stack_create();
ds_stack_copy(stack, other.stack);
}

The above function creates a new instance and then in that instance it creates a new ds_stack and copies the contents of the stack in the instance running the code block, into the newly created instance stack.

Back: Stacks
Next: ds_stack_top

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_create

Creates a new stack, returning its id.

Syntax:

ds_stack_create();

Returns: Real

Description

This function will create a new stack data-structure and return the index value. This value should be stored in a variable and used in all further function calls relating to the stack.

Example:

stack = ds_stack_create();

This will create a new stack and assign its index id to the instance variable "stack".

Back: Stacks
Next: ds_stack_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_destroy

Destroys a given stack and removes it from memory.

Syntax:

ds_stack_destroy(id);

Argument | Description
id | The id of the data structure to remove.

Returns: N/A

Description

This function will remove the given stack data-structure from memory, freeing up the resources it was using and removing all values that it contained. This function should always be used when you are finished using the ds_stack to prevent memory leaks that can slow down and crash your game.

Example:

if lives = 0
{
ds_stack_destroy(AI_stack);
room_goto(rm_Menu);
}

The above code will check the value of the built in global variable "lives" and if it is 0, it destroys the ds_stack indexed in the variable "AI_stack" and then changes rooms.

Back: Stacks
Next: ds_stack_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_empty

Returns whether the given stack is empty or not.

Syntax:

ds_stack_empty(id);

Argument | Description
id | The id of the data structure to check.

Returns: Boolean

Description

With this function you can check the given ds_stack to see if it is empty (returns true) or not (returns false).

Example:

if ai_count == 15 && !ds_stack_empty(AI_stack)
{
ds_stack_clear(AI_stack);
alarm[0] = room_speed;
ai_count = 0;
}

The above code checks a variable to see if it has reached a specific value and if it has it clears the ds_stack indexed in the variable "AI_stack", sets an alarm, and resets the variable to 0.

Back: Stacks
Next: ds_stack_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_pop

Pops the value from the top of the stack.

Syntax:

ds_stack_pop(id);

Argument | Description
id | The id of the data structure to pop from.

Returns: Real or String

Description

This function will pop the top value off of the ds_stack, removing it from the stack and returning the value to be stored in a variable.

Example:

if !ds_stack_empty(move_stack)
{
var xx, yy;
xx = ds_stack_pop(move_stack);
yy = ds_stack_pop(move_stack);
move_towards_point(xx, yy, 4);
}

The above code checks the ds_stack indexed in the variable "move_stack" to see if it is empty, and if it is not, it then pops the top two values from the stack and use them to set a direction for movement.

Back: Stacks
Next: ds_stack_push

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_push

Pushes a given value (or values) onto the top of the stack.

Syntax:

ds_stack_push(id, val [, val2, ... val15]);

Argument | Description
id | The id of the data structure to push onto.
val | The value to push onto the stack.
[val2, ... val13] | Optional values to be added to the stack.

Returns: N/A

Description

This function will push (add) a value, which can be either a real or a string, onto the top of the stack. The function can take a further 14 optional arguments (making a total of 15 possible additions), permitting you to push multiple values consecutively to the stack in a single call.

Example:

move_stack = ds_stack_create();
ds_stack_push(move_stack, x, y, x, y + 200, x + 200, y + 200, x +200, y);

The above code creates a new ds_stack and stores its index in the variable "move_stack". It then pushes a number of values onto the stack for future use.

Back: Stacks
Next: ds_stack_read

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_read

Reads a stack data structure from a string.

Syntax:

ds_stack_read(id, str [, legacy] );

Argument | Description
id | The id of the data structure to read into.
str | The string to read from.
legacy (optional) | Can be either true or false or omitted completely.

Returns: N/A

Description

With this function you can recreate a saved ds_stack (one that has previously been written as a string using ds_stack_write). You must first create a new ds_stack to read the string into, and if the ds_stack already exists and has information stored in it, then this will be cleared before reading. This function is of vital importance when creating save/load mechanisms for your game. Note that if the data structure was created with previous versions of GameMaker you should add the optional argument "legacy", setting it to true as the string format has changed with this version.

Example:

stack = ds_stack_create();
ini_open("save.ini");
var str = ini_read_string("Stacks", "0", "");
if str != ""
{
ds_stack_read(stack, str);
}
ini_close();

The above code creates a stack and stores the index in the variable "stack". It then opens an ini file and reads a string from that, checking to make sure that the string is not returned as empty first. This string is then read into the newly created ds_stack.

Back: Stacks
Next: ds_stack_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_size

Returns the number of values stored in the given stack.

Syntax:

ds_stack_size(id);

Argument | Description
id | The id of the data structure to check.

Returns: Real

Description

This function will return the "size" of the stack, ie: the number of items that have been pushed onto it.

Example:

if !ds_stack_empty(control_stack)
{
num = ds_stack_size(control_stack);
}

The above code checks a ds_stack to see if it is empty or not, and if it is not, it gets the number of items that it contains and stores the value in a variable.

Back: Stacks
Next: ds_stack_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_top

Reads the value from the top of the stack.

Syntax:

ds_stack_top(id);

Argument | Description
id | The id of the data structure to read from.

Returns: Real or String

Description

This function will only read the first value of the stack (that which is "on top"). It will not pop the value, meaning that it can still be read in the future by this function or the ds_stack_pop.

Example:

num = ds_stack_top(control_stack);

The above code will read the value from the stack indexed in the variable "control_stack" and store the return value in the variable "num".

Back: Stacks
Next: ds_stack_pop

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ds_stack_write

Writes the data structure out as a string.

Syntax:

ds_stack_write(id);

Argument | Description
id | The id of the data structure to write.

Returns: String

Description

This function returns a string which can then be stored or transferred to another data structure using the ds_stack_read function.

NOTE: The returned string is not a human readable string, but rather a dump of the contents of the data-structure

Example:

var str;
ini_open("save.ini");
str =ds_stack_write(stack);
ini_write_string("Stacks", "0", str);
ds_stack_clear(stack);
ini_close();

The above code opens an ini file and then writes a string containing the information stored in the ds_stack indexed in the variable "stack". The stack is then cleared and the ini file closed.

Back: Stacks
Next: ds_stack_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Date And Time

This section deals with functions related to dates and time.

GameMaker: Studio has a great many functions and variables related to getting the date and time and calculating other values based off of them. by default these functions return the local time as set by the system, but you can use the following function to switch between local and UTC time:

  1. date_set_timezone
  2. date_get_timezone

Time Variables

The following built in variables can be used to get specific date and time components:

  1. current_time
  2. current_second
  3. current_minute
  4. current_hour
  5. current_day
  6. current_weekday
  7. current_month
  8. current_year

Time Functions

The following functions can be used to get specific date and time components, as well as for creating new ones or for getting the span of days/hours between two given dates etc...

  1. date_create_datetime
  2. date_current_datetime
  3. date_compare_date
  4. date_compare_datetime
  5. date_compare_time
  6. date_valid_datetime
  7. date_date_of
  8. date_time_of
  9. date_is_today
  10. date_leap_year
  11. date_date_string
  12. date_datetime_string
  13. date_time_string
  14. date_second_span
  15. date_minute_span
  16. date_hour_span
  17. date_day_span
  18. date_week_span
  19. date_month_span
  20. date_year_span
  21. date_days_in_month
  22. date_days_in_year
  23. date_get_second
  24. date_get_minute
  25. date_get_hour
  26. date_get_day
  27. date_get_weekday
  28. date_get_week
  29. date_get_month
  30. date_get_year
  31. date_get_second_of_year
  32. date_get_minute_of_year
  33. date_get_hour_of_year
  34. date_get_day_of_year
  35. date_inc_second
  36. date_inc_minute
  37. date_inc_hour
  38. date_inc_day
  39. date_inc_week
  40. date_inc_month
  41. date_inc_year

We also have two special time functions that give you a higher level of precision and control when running your game:

  1. get_timer
  2. delta_time

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


current_day

Returns the current day.

Syntax:

current_day;

Returns: Real

Description

This read only variable will return the day as a value from 1 to 31, depending on the month.

Example:

draw_text(32, 32, "Today is " + string(current_day) + "/" + string (current_month) + "/" + string(current_year) +".");

The above code will draw the day, month and year.

Back: Date And Time
Next: current_weekday

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


current_hour

Returns the hour corresponding to the current moment.

Syntax:

current_hour;

Returns: Real

Description

This read only variable will return the hour that corresponds to the current moment based on the default time zone for the system (ie: local time). You can change the base time zone to use with the function date_set_timezone().

Example:

draw_text(32, 32, "The time is " + string(current_hour) + ":" + string(current_minute) + "." + string(current_second));

The above code would draw the current international time on the screen.

Back: Date And Time
Next: current_day

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


current_minute

Returns the minute corresponding to the current moment.

Syntax:

current_minute;

Returns: Real

Description

This read only variable will return the minutes that correspond to the current moment.

Example:

draw_text(32, 32, "The time is " + string(current_hour) + ":" + string(current_minute) + "." + string(current_second));

The above code would draw the current international time on the screen.

Back: Date And Time
Next: current_hour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


current_month

Returns the current month.

Syntax:

current_month;

Returns: Real

Description

This read only variable returns the current month as a numeric value where 1 is January and 12 is December.

Example:

draw_text((32, 32, "Today is " + string(current_day) + "/" + string (current_month) + "/" + string(current_year) +".");

The above code will draw the day, month and year.

Back: Date And Time
Next: current_year

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


current_second

Returns the second corresponding to the current moment.

Syntax:

current_second;

Returns: Real

Description

This read only variable will return the seconds that correspond to the current moment.

Example:

draw_text(32, 32, "The time is " + string(current_hour) + ":" + string(current_minute) + "." + string(current_second));

The above code would draw the current international time on the screen.

Back: Date And Time
Next: current_minute

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


current_time

Returns the milliseconds passed since the OS was started.

Syntax:

current_time;

Returns: Real

Description

This read only variable will return the number of milliseconds that have passed since the OS was started.

Example:

if current_time > 600000
{
msg = show_question_async("Would you like to rate?");
}

The above code checks to see if more than 10 minutes have passed before asking the user a question.

Back: Date And Time
Next: current_second

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


current_weekday

Returns the current weekday as a real number.

Syntax:

current_weekday;

Returns: Real

Description

This read only variable will return the weekday as a value, where Sunday is 0 and Saturday is 6.

Example:

var day;
switch(current_weekday)
{
case 0: day = "Sunday"; break;
case 1: day = "Monday"; break;
case 2: day = "Tuesday"; break;
case 3: day = "Wednesday"; break;
case 4: day = "Thursday"; break;
case 5: day = "Friday"; break;
case 6: day = "Saturday"; break;
}
draw_text(32, 32, "Today is " + day +".");

The above code uses the current_weekday value to set a variable with the correct day in text, then draws that for the user to see.

Back: Date And Time
Next: current_month

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


current_year

Returns the current year.

Syntax:

current_year

Returns: Real

Description

This read only variable will return the current year.

Example:

draw_text((32, 32, "Today is " + string(current_day) + "/" + string (current_month) + "/" + string(current_year) +".");

The above code will draw the day, month and year.

Back: Date And Time
Next: current_time

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_compare_date

Returns which of two dates is the latest.

Syntax:

date_compare_date( date1, date2 );

Argument | Description
date1 | The first date.
date2 | The date to compare it to.

Returns: Real

Description

With this function you can check two dates to see which one is the earlier or later than the other. The function returns -1 if date1 is earlier, 0 if both dates are the same, and 1 if date1 is later.

Example:

d = date_compare_date(date_create_datetime(2011, 9, 15, 11, 4, 0), date_current_datetime());

This would set "d" to the corresponding value depending on which of the dates was the earliest, likely 1 since the current date would be further ahead than 15th September 2011.

Back: Date And Time
Next: date_compare_datetime

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_compare_datetime

Returns which of two times on specific dates is the latest.

Syntax:

date_compare_datetime(date1, date2);

Argument | Description
date1 | The first datetime.
date2 | The datetime to compare it to.

Returns: Real

Description

With this function you can check two dates and times to see which one is the earlier or later than the other. The function returns -1 if date1 is earlier, 1 if date1 is later and 0 if they are the same, although since this takes time into account as well, a 0 for matching is very rare (it literally has to be the same second of the same day of the same month of the same year to return a 0).

Example:

d = date_compare_date(date_create_datetime( 2011, 9, 15, 11, 4, 0 ), date_current_datetime());

This would set d to the corresponding value depending on which of the datetimes was the earliest, likely -1 since the current date would be further ahead than 15th September 2011.

Back: Date And Time
Next: date_compare_time

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_compare_time

Returns which of two times is the latest.

Syntax:

date_compare_time(datetime1, datetime2);

Argument | Description
datetime1 | The first datetime.
datetime2 | The datetime to compare the first one to.

Returns: Real

Description

With this function you can check two dates and times to see which one has the time component earlier or later than the other. The function returns -1 if datetime1 is earlier, 1 if datetime1 is later and 0 if they are the same, and it ignores the date, so literally just which of the times is further through its given day.

Example:

d = date_compare_time(date_create_datetime( 2011, 9, 15, 11, 4, 0 ), date_current_datetime());

This would set "d" to the corresponding value depending on which of the times was the earliest. Basically, if the current time is later than 11:04 am, it would return 1. If earlier, -1. If the time is 11:04, it would return 0.

Back: Date And Time
Next: date_create_datetime

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_create_datetime

Creates and returns a datetime value based on given values.

Syntax:

date_create_datetime(year, month, day, hour, minute, second);

Argument | Description
year | The year to set.
month | The month to set.
day | The day to set.
hour | The hour to set.
minute | The minute to set.
second | The second to set.

Returns: Real

Description

This function will create a datetime value from the component given as the arguments.

Example:

mydatetime = date_create_datetime(2011, 9, 15, 9, 43, 30);

This would set "mydatetime" to the given date and time and store the returned value in the variable "mydatetime".

Back: Date And Time
Next: date_current_datetime

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_current_datetime

Returns the date-time value corresponding to the current moment.

Syntax:

date_current_datetime();

Returns: Real

Description

Returns the date-time value of the current moment. The time returned is based on the default time zone for the system (ie: local time). You can change the base time zone to use with the function date_set_timezone()

Example:

myhour = date_get_hour(date_current_datetime());
myday = date_get_day(date_current_datetime());

This would set local variable myhour to the hour of the current time, and myday to the day of the current date.

Back: Date And Time
Next: date_date_of

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_date_of

Returns the date section of a datetime value.

Syntax:

date_date_of(date);

Argument | Description
date | The datetime to extract the date from.

Returns: Real

Description

Returns the date value of the given datetime.

Example:

today = date_date_of(date_current_datetime());

This would return the current date only and store the value in the variable "today".

Back: Date And Time
Next: date_date_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_date_string

Returns a string indicating the given date in the default format for the system.

Syntax:

date_date_string(date);

Argument | Description
date | The date to use.

Returns: String

Description

With this function you can create a string containing the given date, formatted as day/month/year.

Example:

str = date_date_string(date_current_datetime());
draw_text(32, 32, str);

This would set "str" to hold a formatted string of the current date and time as shown by the system.

Back: Date And Time
Next: date_datetime_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_datetime_string

Returns a string indicating the given date and time in the default format for the system.

Syntax:

date_datetime_string(date);

Argument | Description
date | The date to use.

Returns: String

Description

With this function you can create a string containing the given datetime, formatted for the system or device that is running the game when the function is called.

Example:

str = date_datetime_string(date_current_datetime());

This would set "str" to something like "September 15th 2011, 11:33.00" depending on the system settings for date/time displaying and the current date and time.

Back: Date And Time
Next: date_day_span

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_day_span

Returns the number of days between two datetime.

Syntax:

date_day_span(date1, date2);

Argument | Description
date1 | The first datetime.
date2 | The datetime to compare it to.

Returns: Real

Description

With this function you can get the number of days between two dates. This value is always positive, and incomplete days will be returned as a fraction.

Example:

diff = date_day_span(date_create_datetime(2011, 9, 15, 11, 4, 0), date_current_datetime());

This would set diff to the number of days between 15th September 2011, 11:04.0 and the current date and time.

Back: Date And Time
Next: date_days_in_month

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_days_in_month

Returns the number of days in the month of the given datetime.

Syntax:

date_days_in_month(date);

Argument | Description
date | The date to use.

Returns: Real

Description

With this function you can get the number of days that the given month has, either 28, 29, 30 or 31.

Example:

days = date_days_in_month(date_current_datetime());

This would set "days" to the number of days in the current month.

Back: Date And Time
Next: date_days_in_year

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_days_in_year

Returns the number of days in the year of the given datetime.

Syntax:

date_days_in_year(date);

Argument | Description
date | The date to use.

Returns: Real

Description

With this function you can get the number of days that the given year has, returning 365 for a normal year, and 366 for a leap year.

Example:

days = date_days_in_year(date_current_datetime());

This would set "days" to the number of days in the current year.

Back: Date And Time
Next: date_get_day

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_day

Returns the day corresponding to the date.

Syntax:

date_get_day(date);

Argument | Description
date | The date to check.

Returns: Real

Description

This function returns the day (from 1 to 31) of the given datetime.

Example:

myday = date_get_day( date_current_datetime() );

This would set "myday" to the current day.

Back: Date And Time
Next: date_get_day_of_year

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_day_of_year

Returns the day of the year corresponding to the date.

Syntax:

date_get_day_of_year( date );

Argument | Description
date | The date to check.

Returns: Real

Description

This function returns the day (from 1 to 366) within the year of the given datetime.

Example:

mydayyear = date_get_day_of_year(date_current_datetime());

This would set mydayyear to the current day of the year.

Back: Date And Time
Next: date_get_hour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_hour

Returns the hour corresponding to the datetime.

Syntax:

date_get_hour(date);

Argument | Description
date | The datetime to check.

Returns: Real

Description

This function returns the hour of the given datetime value.

Example:

myhour = date_get_hour(date_current_datetime());

This would set "myhour" to the current hour.

Back: Date And Time
Next: date_get_hour_of_year

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_hour_of_year

Returns the hour of the year corresponding to the datetime.

Syntax:

date_get_hour_of_year(date);

Argument | Description
date | The datetime to check.

Returns: Real

Description

This function returns the hour of the given datetime value within the year (from the total number of hours for the year, taking into account leap years).

Example:

myhouryear = date_get_hour_of_year(date_current_datetime());

This would set "myhouryear" to the current hour of the year.

Back: Date And Time
Next: date_get_minute

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_minute

Returns the minute corresponding to the datetime.

Syntax:

date_get_minute(date);

Argument | Description
date | The datetime to check.

Returns: Real

Description

This function returns the minute of the given datetime value.

Example:

myminute = date_get_minute(date_current_datetime());

This would set "myminute" to the current minute.

Back: Date And Time
Next: date_get_minute_of_year

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_minute_of_year

Returns the minute of the year corresponding to the datetime.

Syntax:

date_get_minute_of_year(date);

Argument | Description
date | The date to check.

Returns: Real

Description

This function returns the minute of the given datetime value within the year (from the total number of minutes for the year, taking into account leap years).

Example:

myminuteyear = date_get_minute_of_year(date_current_datetime());

This would set myminuteyear to the current minute of the year.

Back: Date And Time
Next: date_get_month

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_month

Returns the month corresponding to the datetime.

Syntax:

date_get_month(date);

Argument | Description
date | The datetime to check.

Returns: Real

Description

This function returns the month of the given datetime value.

Example:

mymonth = date_get_month(date_current_datetime());

This would set mymonth to the current month.

Back: Date And Time
Next: date_get_second

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_second

Returns the second corresponding to the datetime.

Syntax:

date_get_second(date);

Argument | Description
date | The datetime to check.

Returns: Real

Description

This function returns the second of the given datetime value.

Example:

mysecond = date_get_second(date_current_datetime());

This would set mysecond to the current second.

Back: Date And Time
Next: date_get_second_of_year

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_second_of_year

Returns the second of the year corresponding to the datetime.

Syntax:

date_get_second_of_year( date );

Argument | Description
date | The date to check.

Returns: Real

Description

This function returns the second of the given datetime value within the year (from the total number of seconds for the year, taking into account leap years).

Example:

mysecondyear = date_get_second_of_year(date_current_datetime());

This would set "mysecondyear" to the current second of the year.

Back: Date And Time
Next: date_get_week

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_timezone

Sets the base timezone to use for all the date and time functions.

Syntax:

date_get_timezone();

Returns: Constant

Description

Gets the base time zone being used for all the rest of the date and time functions. This time zone can either be local (as set by the system) or UTC, and the function will return one of the following constants:

Constant | Description
timezone_local | use the local time zone as set by the system
timezone_utc | use Coordinated Universal Time

Example:

if date_get_timezone() != timezone_utc
br> date_set_timezone(timezone_utc);
}

This code checks the base time zone setting for the game and if it is not UTC it then changes it.

Back: Date And Time
Next: current_time

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_week

Returns the week corresponding to the datetime.

Syntax:

date_get_week(date);

Argument | Description
date | The datetime to check.

Returns: Real

Description

This function returns the week of the given datetime value within the year.

Example:

myweek = date_get_week(date_current_datetime());

This would set myweek to the current week.

Back: Date And Time
Next: date_get_weekday

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_weekday

Returns the weekday corresponding to the datetime.

Syntax:

date_get_weekday(date);

Argument | Description
date | The date to check.

Returns: Real

Description

This function returns the week day value of the given datetime. This will be a value from 0 to 6.

Example:

myweekday = date_get_weekday(date_current_datetime());

This would set "myweekday" to the current weekday.

Back: Date And Time
Next: date_get_year

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_get_year

Returns the year corresponding to the datetime.

Syntax:

date_get_year(date);

Argument | Description
date | The datetime to check.

Returns: Real

Description

This function returns the year of the given datetime.

Example:

myyear = date_get_year(date_current_datetime());

This would set "myyear" to the current year.

Back: Date And Time
Next: date_hour_span

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_hour_span

Returns the number of hours between two datetimes.

Syntax:

date_hour_span(date1, date2);

Argument | Description
date1 | The first datetime.
date2 | The datetime to compare the first one to.

Returns: Real

Description

With this function you can get the number of hours between two dates. This value is always positive, and incomplete hours will be returned as a fraction.

Example:

diff = date_hour_span(date_create_datetime( 2011, 9, 15, 11, 4, 0 ), date_current_datetime());

This would set "diff" to the number of hours between 15th September 2011, 11:04.0 and the current date and time.

Back: Date And Time
Next: date_inc_day

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_inc_day

Returns a datetime after a given number of days have been added.

Syntax:

date_inc_day(date, amount);

Argument | Description
date | The datetime to add to.
amount | The number of days (must be an integer) to add.

Returns: Real

Description

With this function you can increment a given datetime value by a specific number of days, and it will return the new datetime value.

Example:

mynewdatetime = date_inc_day(date_current_datetime(), 365);

This would set "mynewdatetime" to the current date but with 365 days added.

Back: Date And Time
Next: date_inc_hour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_inc_hour

Returns a datetime after a given number of hours have been added.

Syntax:

date_inc_hour(date, amount);

Argument | Description
date | The datetime to add to.
amount | The number of hours (must be an integer) to add.

Returns: Real

Description

With this function you can increment a given datetime value by a specific number of hours, and it will return the new datetime value.

Example:

mynewdatetime = date_inc_hour(date_current_datetime(), 24);

This would set mynewdatetime to the current date but with 24 hours added.

Back: Date And Time
Next: date_inc_minute

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_inc_minute

Returns a datetime after a given number of minutes have been added.

Syntax:

date_inc_minute( date, amount );

Argument | Description
date | The datetime to add to.
amount | The number of minutes (must be an integer) to add.

Returns: Real

Description

With this function you can increment a given datetime value by a specific number of minutes, and it will return the new datetime value.

Example:

mynewdatetime = date_inc_minute(date_current_datetime(), 60);

This would set "mynewdatetime" to the current date but with 60 minutes added.

Back: Date And Time
Next: date_inc_month

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_inc_month

Returns a datetime after a given number of months have been added.

Syntax:

date_inc_month( date, amount );

Argument | Description
date | The datetime to add to.
amount | The number of months (must be an integer) to add.

Returns: Real

Description

With this function you can increment a given datetime value by a specific number of months, and it will return the new datetime value.

Example:

mynewdatetime = date_inc_month(date_current_datetime(), 12);

This would set "mynewdatetime" to the current date but with 12 months added.

Back: Date And Time
Next: date_inc_second

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_inc_second

Returns a datetime after a given number of seconds have been added.

Syntax:

date_inc_second(date, amount);

Argument | Description
date | The datetime to add to.
amount | The number of seconds (must be an integer) to add.

Returns: Real

Description

With this function you can increment a given datetime value by a specific number of seconds, and it will return the new datetime value.

Example:

mynewdatetime = date_inc_second(date_current_datetime(), 60);

This would set "mynewdatetime" to the current date but with 60 seconds added.

Back: Date And Time
Next: date_inc_week

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_inc_week

Returns a datetime after a given number of weeks have been added.

Syntax:

date_inc_week(date, amount);

Argument | Description
date | The datetime to add to.
amount | The number of weeks (must be an integer) to add.

Returns: Real

Description

With this function you can increment a given datetime value by a specific number of weeks, and it will return the new datetime value.

Example:

mynewdatetime = date_inc_week(date_current_datetime(), 52);

This would set mynewdatetime to the current date but with 52 weeks added.

Back: Date And Time
Next: date_inc_year

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_inc_year

Returns a datetime after a given number of years have been added.

Syntax:

date_inc_year(date, amount);

Argument | Description
date | The datetime to add to
amount | The number of years (must be an integer) to add.

Returns: Real

Description

With this function you can increment a given datetime value by a specific number of years, and it will return the new datetime value.

Example:

mynewdatetime = date_inc_year(date_current_datetime(), 1000);

This would set mynewdatetime to the current date but with 1000 years added.

Back: Date And Time
Next: date_is_today

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_is_today

Returns whether the given datetime is today or not.

Syntax:

date_is_today(date);

Argument | Description
date | The datetime to use.

Returns: Boolean

Description

This function will return true if the given datetime value is the day it is being checked on (ie: today), or false otherwise. This can be a handy function for things like Easter Eggs in your games, or for unlocking seasonal content. Note that this function will be affected by the time zone set (default is local time) which you can change using the date_set_timezone() function.

Example:

if date_is_today(global.Halloween)
{
global.Max_Levels = 200;
}

The above code will check the datetime stored in the global variable "Halloween" to see if it is today, and if it is it sets another global variable to a new value.

Back: Date And Time
Next: date_leap_year

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_leap_year

Returns whether the year in the given datetime is a leap year or not.

Syntax:

date_leap_year(date);

Argument | Description
date | The datetime to use.

Returns: Boolean

Description

This function will return true if the year component of the given datetime value is a leap year or false otherwise. This can be a handy function for things like Easter Eggs in your games, or for unlocking special content.

Example:

if date_leap_year(date_current_datetime())
{
if !global.ExtraContent
{
global.ExtraContent = true;
}
}

The above code will check the current datetime to see if the year is a leap year or not. If it is it sets a global variable.

Back: Date And Time
Next: date_minute_span

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_minute_span

Returns the number of minutes between two datetime, with incomplete ones reporting as a fraction.

Syntax:

date_minute_span(date1, date2);

Argument | Description
date1 | The first datetime.
date2 | The datetime to compare it to.

Returns: Real

Description

With this function you can get the number of minutes between two dates. This value is always positive, and incomplete minutes will be returned as a fraction.

Example:

diff = date_minute_span(date_create_datetime(2011, 9, 15, 11, 4, 0 ), date_current_datetime());

This would set "diff" to the number of minutes between 15th September 2011, 11:04.0 and the current date and time.

Back: Date And Time
Next: date_month_span

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_month_span

Returns the number of months between two datetime, with incomplete ones reporting as a fraction.

Syntax:

date_month_span(date1, date2);

Argument | Description
date1 | The first datetime.
date2 | The datetime to compare it to.

Returns: Real

Description

With this function you can get the number of months between two dates. This value is always positive, and incomplete months will be returned as a fraction.

Example:

diff = date_month_span(date_create_datetime(2011, 9, 15, 11, 4, 0 ), date_current_datetime());

This would set "diff" to the number of months between 15th September 2011, 11:04.0 and the current date and time.

Back: Date And Time
Next: date_second_span

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_second_span

Returns the number of seconds between two datetime values.

Syntax:

date_second_span(date1, date2);

Argument | Description
date1 | The first datetime.
date2 | The datetime to compare it to.

Returns: Real

Description

With this function you can get the number of seconds between two dates. The return value is always positive and will be a whole number.

Example:

diff = date_second_span(date_create_datetime(2011, 9, 15, 11, 4, 0 ), date_current_datetime());

This would set "diff" to the number of seconds between 15th September 2011, 11:04 and the current date and time.

Back: Date And Time
Next: date_time_of

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_set_timezone

Sets the base timezone to use for all the date and time functions.

Syntax:

date_set_timezone(timezone);

Argument | Description
timezone | The time zone to use for the base time.

Returns: N/A

Description

Sets the base time zone to use for all the rest of the date and time functions. This time zone can either be local (as set by the system) or UTC, and you would use one of the following constants to define which is being used (by default this is local time):

Constant | Description
timezone_local | use the local time zone as set by the system
timezone_utc | use Coordinated Universal Time

Example:

if date_get_timezone() != timezone_utc
{
date_set_timezone(timezone_utc);
}

This code checks the base time zone setting for the game and if it is not UTC it then changes it.

Back: Date And Time
Next: date_get_timezone

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_time_of

Returns the time section of a datetime value.

Syntax:

date_time_of(date);

Argument | Description
date | The datetime to extract the time from.

Returns: Real

Description

Returns the time value of the given datetime. The time returned ignores Daylight Saving Time (and so is Universal Time) and would normally be used in conjunction with another date/time handling function.

Example:

time = date_time_of(date_current_datetime());

This would return the current time only and store the value in the variable "time".

Back: Date And Time
Next: date_time_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_time_string

Returns a string indicating the given time in the default format for the system.

Syntax:

date_time_string( date );

Argument | Description
date | The datetime to use.

Returns: String

Description

With this function you can create a string containing the given time, formatted for the system or device that is running the game when the function is called.

Example:

str = date_time_string( date_current_datetime() );

This would set str to something like "11:36.00" depending on the system settings for date/time displaying and the current date and time.

Back: Date And Time
Next: date_second_span

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_valid_datetime

Returns whether a given datetime is valid.

Syntax:

date_valid_datetime(year, month, day, hour, minute, second);

Argument | Description
year | The year to check.
month | The month to check.
day | The day to check.
hour | The hour to check.
minute | The minute to check.
second | The second to check.

Returns: Boolean

Description

With this function you can check a datetime value to see if it is valid (returns true) or not (returns false). Note that this function will only consider a valid datetime as being after 1/1/1970 and anything before that will return false, so the earliest you can check would be:

date_valid_datetime(1970, 01, 01, 0, 0, 0);

Example:

if date_valid_datetime(2011, 9, 15, 10, 3, 30))
{
mydatetime = date_create_datetime( 2011, 9, 15, 10, 3, 30 );
}

This will set "mydatetime" to 15th September 2011, 10:03.30, if it is a valid value (which it is).

Back: Date And Time
Next: date_date_of

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_week,span

date_week_span

Returns the number of weeks between two datetime, with incomplete ones reporting as a fraction.

Syntax:

date_week_span(date1, date2);

Argument | Description
date1 | The first datetime.
date2 | The datetime to compare it to.

Returns: Real

Description

With this function you can get the number of weeks between two dates. This value is always positive, and incomplete weeks will be returned as a fraction.

Example:

diff = date_week_span( date_create_datetime( 2011, 9, 15, 11, 4, 0 ), date_current_datetime() );

This would set "diff" to the number of weeks between 15th September 2011, 11:04.0 and the current date and time.

Back: Date And Time
Next: date_year_span

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


date_year_span

Returns the number of years between two datetime, with incomplete ones reporting as a fraction.

Syntax:

date_year_span(date1, date2);

Argument | Description
date1 | The first datetime.
date2 | The datetime to compare it to.

Returns: Real

Description

With this function you can get the number of years between two dates. This value is always positive, and incomplete years will be returned as a fraction.

Example:

diff = date_year_span(date_create_datetime(2011, 9, 15, 11, 4, 0), date_current_datetime());

This would set diff to the number of years between 15th September 2011, 11:04.0 and the current date and time.

Back: Date And Time
Next: date_compare_date

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


delta_time

The time passed in microseconds between one step and another.

Syntax:

delta_time

Returns: Real

Description

The purpose of delta timing is to eliminate the effects of the lag or slowness of computers that try to handle complex graphics or a lot of code. It is a value that can be added on to the speed of objects so that they will eventually move at the same speed, regardless of lag. This is achieved in GameMaker: Studio by using the read only variable delta_time every step as it measures the time that has passed between one step and the next in microseconds (1microsecond is 1,000,000th of a second). Therefore the variable delta_time can be used to calculate how much faster (for example) a game character has to move to make up for a lag spike in the game.

Example:

speed = spd * (ot - delta_time);

The above code will set the speed of the instance using delta-time to correct for lag. The variable "ot" would be used to hold the previously calculated delta_time value so that the ratio can be used to multiply the base speed value (held in the variable "spd") and so get a consistent speed for the instance.

Back: Date And Time Functions
Next:get_timer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_timer

This returns the time since your game started.

Syntax:

get_timer();

Returns: Real

Description

This function returns the time that your game has been running on the chosen platform in microseconds (there are 1 million microseconds per second).

Example:

time = get_timer();

This would store the timer value in the variable "time".

Back: Date And Time Functions
Next:delta_time

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Debugging

This section deals with those functions supported for debug use only

While making a game, it is often very important that you know certain details of the game mechanics at specific points in time, or to be able to input certain key values for some functions to test out different methods and ideas for your game. To that end GameMaker: Studio provides you with a number of debug functions that will show messages and ask for input while in debug mode (or on a Windows target) but that will be ignored when compiled for other target modules due to the fact that these functions put the game in a closed loop until the input is resolved.

NOTE: Although they may work on certain platforms they are not to be used for anything other than debugging.

  1. debug_mode
  2. get_integer
  3. get_string
  4. show_error
  5. show_message
  6. show_question
  7. show_debug_message
  8. show_debug_overlay
  9. code_is_compiled
  10. fps
  11. fps_real

Apart from those specialist functions, to help you out when creating your game, GameMaker: Studio also has a long list of error messages that can be shown either when compiling your game or when the game itself is running. These messages point to the specific error in question and can be used to pinpoint a problem within a specific object or script, helping greatly with the process of debugging your game. However, it may not always be obvious exactly what the error message means and so the following two sections list all of the possible messages and explain what they mean to make life easier for you:

  1. Compile Errors
  2. Runner Errors

You can also find further information on how to debug your game in the section Advanced Use - Debugging.

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


code_is_compiled

Check to see if the code was compiled using the YoYo Compiler.

Syntax:

code_is_compiled();

Returns: Boolean

Description

This function will return true if the platform compiles outside of the virtual machine, such as for the YYC and JS platforms.

Example:

if code_is_compiled()
{
show_debug_message("Compiler okay!");
}

The above code checks to see if the game was compiled using the YoYo Compiler and shows a debug message if it was.

Back: Debugging
Next: fps

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Compile Errors

This section lists all the possible errors given by the asset compiler.

When creating your game it's very easy to forget to declare a variable or mis-type a string as a real etc... These errors will be caught by GameMaker: Studio as the game is being compiled and a window will open with the error given as well as where the error was found as shown in the image below: You can click any of the lines of text that are shown and you will be taken directly to the object that has thrown the error, and then you can use the information contained within the message to pinpoint exactly where in the object the error has occurred. However, sometimes these errors can seem a bit cryptic, so below you can find a complete list of all errors and a brief explanation of what they mean.

  1. >unknown function or script

    You have referenced a function or script that does not exist. This can happen when you mis-type a function or remove a script that is being used in an object from the game.

  2. >Unable to find script

    You have referenced a script that can no longer be found in the resources.

  3. >Execute script action is not bound to a script

    You have used the "execute script" action on a script that no longer exists.

  4. >Failed to parse action_execute_script() - incorrect number of arguments received

    The execute script action has been given the wrong number of arguments for the script

  5. >Trying to set a read only variable

    You have tried to assign a value (string or real) to a variable that is flagged as read-only. For example:
    phy_com_x = 12;
    This would give an error as phy_com_x is read-only.

  6. >Constant is invalid here

    You have placed a constant in your code that is not appropriate to the code.

  7. >Malformed repeat statement

    >Malformed if statement

    >Malformed while statement

    >Malformed do statement

    >Malformed for statement

    >Malformed with statement

    >Malformed switch statement

    >Malformed break statement

    >Malformed continue statement

    >Malformed exit statement

    >Malformed return statement

    The structure of your statement is incorrect. For specific details please see the relevant section here: GML Overview

  8. >Keyword until expected

    You have set up a "do... until" loop but failed to supply the "until" part. See GML Overview - Do

  9. >If requires a then statement

    You have omitted the then part of an if statement. See: GML Overview: If

  10. >Statement in a switch MUST appear after case or default

    You have added a function statement into a switch outside of the cases or default. For example:
    switch(id)
       {
       if x == 12 game_end(); break;
       }

  11. >Break used without context

    You have added a break into your code where it is not needed or makes no sense to have one.

  12. >Continue used without context

    You have added a continue into your code where it is not needed or makes no sense to have one.

  13. >Calling a function that needs an instance and no instance is available

    This error will be shown should you be using an instance_* function when no instances exist at the time of running the code.

  14. >Calling a function that needs an \"other\" and no \"other\" is available

    You will get this error when using other to reference an instance when that instance no longer exists, for example, in a collision event where you have already destroyed the other instance.

  15. >Argument naming error, {n} arguments but no reference found to {a}

    You have supplied a series of arguments to a script, of which one or more does not represent any value.

  16. >Wrong type of arguments for *

    >Wrong type of arguments for /

    >Wrong type of arguments for div

    >Wrong type of arguments for Mod

    >Wrong type of arguments for +

    >Wrong type of arguments for -

    >Wrong type of arguments for &&

    >Wrong type of arguments for ||

    >Wrong type of arguments for &

    >Wrong type of arguments for |

    >Wrong type of arguments for ^

    >Wrong type of arguments for <<

    >Wrong type of arguments for >>

    You have supplied an expression with the wrong type of arguments (either real or string). For example if you have something like this:
    if "Hello" div 4
       {
       //do something;
       }
    you will get this error as you cannot use div on a string. For specific details please see the relevant section here: GML Overview - Expressions

  17. >Division by 0

    It is impossible to divide by 0 and so you get this error should a GameMaker: Studio code try to do this.

  18. >Modulo by 0

    You get this error should the modulo expression try to use 0 as its operator.

  19. >Cannot compare arguments

    this error tells you that one or more expressions are trying to operate on both strings and reals, something that is not permitted. For example:
    if "Hello" == 74
       {
       //do something;
       }
    This would give the error as you cannot compare the two values in the expression as they are different types.

  20. >Symbol } expected

    >Symbol { expected

    >Symbol ) expected

    >Symbol ( expected

    >Symbol: expected

    >Symbol , or ) expected

    >Symbol , or ] expected

    >Symbol ] expected

    Your code is missing one of the above symbols from its syntax. This error is normally caught by the code editor and highlighted for you.

  21. >Assignment operator expected

    This error will be fired when you have omitted one of the operators from an expression. For example:
    if var1 var2 == var3
       {
       //do something;
       }
    the above code is missing the operator between "var1" and "var2" and so would give this error, although normally this would be caught by the code editor before being compiled.

  22. >Unexpected symbol in expression

    You have a symbol (like /, *, +, etc...) in the wrong place within the expression. This should normally be caught by the code editor syntax checker

  23. >Only 1 or 2 dimensional arrays are supported

    GameMaker: Studio only permits 1 or 2 dimension arrays and should you try to create any that are larger then you will get this error. For more information please see: GML Overview - Arrays

  24. >Variable name expected

    You have written an expression that expects a variable to be used when none has been supplied. For example:
    if obj_Control. = "Hello"
       {
       //do something;
       }
    Since there is no variable after the assignment ".", you would get this error.

Back: Debugging
Next: Runner Errors

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


debug_mode

Tells you if the game is running in debug mode or not.

Syntax:

debug_mode

Returns: Boolean

Description

This read only variable returns true when the game is being played in debug mode and false when being played as normal.

Example:

if debug_mode
{
ini_open("Cheats.ini");
}
else
{
ini_open("Game.ini");
}

The above code opens a different ini file depending on the value of the read-only variable debug_mode.

Back: Debugging
Next: get_integer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


fps

Returns the frames per second capped at room speed.

Syntax:

fps

Returns: Real

Description

In GameMaker: Studio there are two main ways that can be used to tell the speed at which your game runs. The room_speed (as specified in the room editor) and the fps (frames per second). These values are often confused, but basically one is the number of game steps that GameMaker: Studio is supposed to be completing in a second, while the other (the fps) is the number of CPU steps that GameMaker: Studio is actually completing in a second up to a maximum value of the room speed itself. To get the true fps, ie. the actual number of cpu steps per game step, use the fps_real variable.

This read-only variable returns the current fps as an integer value. Please note that the function will only update once every step of your game and so may appear to "jump" from one value to another, but this is quite normal.

Example:

if debug_mode
{
draw_text(32, 32, "FPS = " + string(fps));
}

The above code will check to see if the game is in debug mode and if it is it will display the current fps on the screen.

Back: Debugging
Next: fps_real

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


fps_real

Returns the real frames per second.

Syntax:

fps_real

Returns: Real

Description

In GameMaker: Studio there are two main ways that can be used to tell the speed at which your game runs. The room_speed (as specified in the room editor) and the fps (frames per second). These values are often confused, but basically one is the number of game steps that GameMaker: Studio is supposed to be completing in a second (room speed), while the other is the number of CPU steps that GameMaker: Studio is actually completing in a second (the real fps), and this value is generally much higher than the room speed, but will drop as your game gets more complex and uses more processing power to maintain the set room speed.

This read-only variable returns the current fps as an integer value. Please note that the function will only update once every step of your game and so may appear to "jump" from one value to another, but this is quite normal.

Example:

if debug_mode
{
draw_text(32, 32, "FPS = " + string(fps_real));
}

The above code will check to see if the game is in debug mode and if it is it will display the current real fps on the screen.

Back: Miscellaneous
Next: debug_mode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_integer

Displays a pop-up message for the user to input an integer.

Syntax:

get_integer(str, def);

Argument | Description
str | The string to show in the pop-up message.
def | The default value in the text box.

Returns: Real

Description

This creates a pop-up window showing a custom message, with a button labeled "Ok", and prompts the user to input an integer value. The function will return the typed in integer, or the default value if nothing has been entered.

NOTE: THIS FUNCTION IS FOR DEBUG USE ONLY. Should you require this functionality in your final game, please use get_integer_async.

Example:

global.level = get_integer("Level to test?", 1);

The above code will display a message prompting the user to select a level for testing. The return value will be stored in the global variable "global.level".

Back: Debugging
Next: get_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_string

Displays a pop-up message for the user to input a string.

Syntax:

get_string(str, def);

Argument | Description
str | The string to show in the pop-up message.
def | The default string in the text box.

Returns: String

Description

This creates a pop-up window showing a standard message, with a button labeled "Ok", that prompts the user to input a string. The function will return the input string, or the default value if nothing has been entered.

NOTE: THIS FUNCTION IS FOR DEBUG USE ONLY. Should you require this functionality in your final game, please use get_string_async.

Example:

global.test_name = get_string("Test highscore name:", "Anonymous");

The above code will prompt the user to give a name which will then be stored in the global variable "test_name". If nothing is entered and the user just presses "Ok" then the default value,"Anonymous", will be returned.

Back: Debugging
Next: show_error

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Runner Errors

Here you can see the possible errors that the Virtual Machine runner can throw.

Even after syntax checking in the code editor and then having the compiler check your code, there are still occasions when something can go wrong. in most cases this will throw a VM (virtual machine) error which looks like this: VM errors are generally more serious than compile errors as it means that there is something seriously wrong with your code that neither the code editor nor the compiler have been able to detect, and as such you should pay attention to all such errors. When one occurs, you can use the "copy" button on the pop-up to copy the error to the clipboard which you can then paste into a text file (or wherever) for future reference.

Certain error messages will be prefixed by a negative value. these values can be used to pinpoint the exact nature of the error and what it refers to with the following values possible:

Prefix | Scope
-1 | Self
-2 | Other
-3 | All
-4 | Noone
-5 | Global
-6 | Not Specified
-7 | Local

The possible errors from the VM runner are as follows:

NOTE: All runner errors will try and point you to the object or script that has caused the crash.

  1. Comparisons

    DoSet ::Invalid comparison type

    This denotes that the runner has tried to compare two incompatible data types, like a real number with a string.

  2. Conversions

    DoConv:: Execution Error

    This denotes an error in the conversion of one data-type into another.

  3. Addition

    DoAdd:: Execution Error

    Something has gone wrong when using the addition (+) expression.

  4. Multiplication

    DoMul:: Execution Error

    Something has gone wrong when using the multiplication (*) expression.

  5. Subtraction

    DoSub:: Execution Error

    Something has gone wrong when using the subtraction (-) expression.

    DoSub:: Execution Engine - Cannot operate on string type

    You are trying to subtract the wrong type of variables (for example subtract a string from a real).

  6. Division

    DoDiv:: Execution Error

    Something has gone wrong when using the division (/ or div) expression.

    DoDiv:: Execution Engine - Cannot operate on string type

    You are trying to divide the wrong type of variables (for example divide a string by a real).

    DoDiv:: Divide by zero

    You are attempting to divide by 0.

  7. Remainders

    DoMod:: Execution Error

    Something has gone wrong when using the modulo (mod) expression.

    DoMod:: Execution Engine - Cannot operate on string type

    You are trying to use modulo on the wrong type of variables (for example mod a string by a real).

  8. Bitwise And

    DoAnd:: Execution Error

    Something has gone wrong when using the bitwise "and" (&) expression.

    DoAnd:: Execution Engine - Cannot operate on string type

    You are trying to use "and" on the wrong type of variables (for example trying to "and" a string with a real).

  9. Bitwise Or

    DoOr:: Execution Error

    Something has gone wrong when using the bitwise "or" (|) expression.

    DoOr:: Execution Engine - Cannot operate on string type

    You are trying to use "or" on the wrong type of variables (for example trying to "or" a string with a real).

  10. Bitwise Xor

    DoXor:: Execution Error

    Something has gone wrong when using the bitwise "xor" (^) expression.

    DoXor:: Execution Engine - Cannot operate on string type

    You are trying to use "xor" on the wrong type of variables (for example trying to "xor" a string with a real).

  11. Bitshift Left

    DoShl:: Execution Error

    Something has gone wrong when bitshifting left (<<) a value.

    DoShl:: Execution Engine - Cannot operate on string type

    You are trying to left bitshift the wrong type of variables (for example trying to bitshift a string).

  12. Bitshift Right

    DoShr:: Execution Error

    Something has gone wrong when bitshifting right (>>) a value.

    DoShr:: Execution Engine - Cannot operate on string type

    You are trying to right bitshift the wrong type of variables (for example trying to bitshift a string).

  13. Negative

    DoNeg:: Execution Error

    You are trying to turn a variable type into a negative when this type does not permit such an operation.

  14. Not

    DoNot:: Execution Error

    You are trying to "not" a variable type when this type does not permit such an operation.

  15. Stack Push

    Push:: Execution Error - Variable Index out of range (var)

    The variable being accessed is out with the established range for the runner.

    Push:: Execution Error - Variable Get (var)

    The given variable has not been defined or is unknown.

  16. Stack Pop

    Pop:: Execution Error - Variable Index out of range (var)

    The variable being accessed is out with the established range for the runner.

    Pop:: Execution Error - Variable Get (var)

    The given variable has not been defined or is unknown.

  17. With

    Cannot use global in with statement

    You have tried to use "global" as a variable within a "with" statement, ie:
    with (global)
       {
       //do something;
       }

    Cannot use local in with statement

    You have tried to use "local" as a variable within a "with" statement, ie:
    with (local)
       {
       //do something;
       }

  18. General

    DoCall:: Execution Engine type error

    This is an undefined error within the Virtual Machine. You should file a bug report should this happen (see: The Help Menu for details on how to do this.

    19. Stack Overflow...

    A stack overflow occurs when too much memory is used on the call stack and when your game attempts to use more space than is available on the call stack (that is, when it attempts to access memory beyond the call stack's bounds, which is essentially a buffer overflow), the stack is said to overflow, resulting in a program crash. Restart your computer and GameMaker: Studio and if the error persists please get in touch with support and/or file a bug (as explained above).

Back: Debugging
Next: Compile Errors

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


show_debug_message

Show a debug message in the compiler window.

Syntax:

show_debug_message(string);

Argument | Description
string | The custom debug message to show.

Returns: N/A

Description

This function will create a custom debug message that is shown in the compiler window at runtime.

Example:

if !instance_exists(obj_Exit)
{
show_debug_message("Exit not created!");
game_end();
}

The above code checks to see if an instance exists and if it does not, a debug message is shown in the compile window and the game is ended.

Back: Miscellaneous
Next: show_debug_overlay

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


show_debug_overlay

Show the debug overlay.

Syntax:

show_debug_overlay(enable);

Argument | Description
enable | switch on (true) or off (false) the debug overlay.

Returns: N/A

Description

This function can be used to switch on and off the standard debug overlay when testing your game and is disabled by default. The debug overlay shows a graphic CPU/GPU usage bar in the actual game window itself along with the current real fps value, number of texture swaps and the number of vertex batches (note that texture swaps and vertex batches will never be zero and will normally show values of 2 or 3, since even with an empty room an no objects GameMaker: Studio still has to draw and batch things).

This bar is split into sections, with each section being 1/60th of a second. As you can see from the image above, the bar is made up of various colours:

  • Green - Input / Output processing (ie: keyboard, mouse, gamepad, networking etc...)
  • Red - The update speed of the step event
  • Yellow - The time required for the draw event
  • Orange -Debug update time, which is only normally visible when you use the debug module
  • White - GPU left over time, which is the time spent waiting for the GPU to finish the rendering of the frame before the next one can start
  • Cyan - The text rendering time
  • Grey - The time required to clear screen each draw step
  • Dark Red - The GPU flush, which is how long the GPU takes to clear images from memory

Using this function you can add the overlay whether in debug mode or not, and in this way, you can see how efficiently your game runs and get a visual cue as to how it is using the available resources, without the over-head of having the debugger running alongside.

Example:

if global.debug
{
show_debug_overlay(true);
}
else
{
show_debug_overlay(false);
}

The above code will toggle the debug on or off depending on the value of a global variable.

Back: Miscellaneous
Next: code_is_compiled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


show_error

Displays a pop-up message with a custom error string.

Syntax:

show_error(str, abort);

Argument | Description
str | The string to show in the pop-up message.
abort | Whether to abort (true) or not (false).

Returns: N/A

Description

This function will show a custom string as an error message and give the option to abort the game afterwards if necessary.

NOTE: THIS FUNCTION IS FOR DEBUG USE ONLY.

Example:

if room != rm_Dungeon
{
show_error("Error: Went to wrong area. Aborting game.", true);
}

The above code will check to see if the room that the player is in is "rm_Dungeon" and if not it will show an error message and force the user to abort the game.

Back: Debugging
Next: show_message

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


show_message

Displays a pop-up message.

Syntax:

show_message(str);

Argument | Description
str | The string to show in the pop-up message.

Returns: N/A

Description

This function creates a pop-up message box which displays the string defined in the code and a button marked "Ok" to close it.

NOTE: THIS FUNCTION IS FOR DEBUG USE ONLY.

Example:

var i, tot;
tot = 0;
for (i = 0; i < 10; i += 1)
{
tot += inv[i];
}
show_message("Total = " + string(tot));

The above code will loop through the values stored in the array "inv" and add them to the variable "tot" before showing a message with the total.

Back: Debugging
Next: show_question

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


show_question

Displays a pop-up question.

Syntax:

show_question(str);

Argument | Description
str | The string to show in the pop-up question.

Returns: Boolean

Description

This function creates a pop-up message box with two buttons for "Yes" and "No". It returns true or false depending on which one of the two buttons the user presses.

NOTE: THIS FUNCTION IS FOR DEBUG USE ONLY.

Example:

if score > 500
{
if show_question("Continue to next room?")
{
room_goto(rm_Level2);
}
else game_end();
}

The above code will check the score and if it is over 500, it will ask the user if they wish to continue or not and if the "yes" button is clicked it will go to another room, but if the "no" button is selected it will end the game.

Back: Debugging
Next: show_debug_message

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Drawing

This section has all the different functions that are for drawing things with GameMaker: Studio.

When an object has a sprite assigned to it, it will draw that sprite without any need to add anything into the draw event. But there are many, many occasions when you will need to add other things into the draw event of an object and this section has all the functions that are available for the different things that you can draw, from simple circles and rectangles, through sprites and text, and on through 2D primitives, surfaces and 3D:

  1. Colour And Blending
  2. Drawing Basic Forms
  3. Drawing Sprites And Backgrounds
  4. Drawing Text
  5. Drawing Primitives
  6. Drawing 3D
  7. Drawing Surfaces

There are also a few special functions relating to the way that GameMaker: Studio draws the textures that it uses. Please realise that a sprite is actually a textured quad (a four point primitive made of two triangles) and as such some of the following functions will also affect how they are drawn:

  1. texture_get_width
  2. texture_get_height
  3. texture_get_texel_width
  4. texture_get_texel_height
  5. texture_set_interpolation
  6. texture_set_interpolation_ext
  7. texture_set_blending
  8. texture_set_repeat
  9. texture_set_repeat_ext
  10. texture_set_stage
  11. texture_global_scale

Finally, there are two extra draw functions for advanced users to better control how things are drawn:

  1. draw_texture_flush
  2. draw_enable_drawevent

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_enable_drawevent

Enables or disables the draw event.

Syntax:

draw_enable_drawevent(enable);

Argument | Description
enable | Enable (true) or disable (false) the draw event for all instances.

Returns: N/A

Description

With this function you can choose to enable (true) or disable (false) the draw event for all instances in the game, thus giving you control over how and when things are draw, useful if you wish to implement a "frame skip" technique. Note that this doesn't just prevent instances drawing to the screen, it suppresses the draw event completely meaning that care should be taken since any game logic that is present in that event will not be run either.

Example:

frame_skip ++;
if (frame_skip mod 5) == 0
{
draw_enable_drawevent(true);
}
else
{
draw_enable_drawevent(false);
}

The above code checks a variable and if it returns true, it enables the draw event, otherwise the draw event is disabled.

Back: Drawing
Next: texture_get_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_texture_flush

Clears all textures from texture memory.

Syntax:

draw_texture_flush();

Returns: N/A

Description

With this function you can remove all textures from video memory, and they will then be reloaded on first use. This is the only effective way to manage video memory when you have multiple texture pages for a game, and you should flush the texture memory between levels on your game and organise the graphics using the texture group feature to ensure that the minimum number of textures are used.

It is worth noting that this function works as described on all target platforms except for Windows (YYC and standard), where by default all textures will always be loaded into memory on start-up. You can, however, change this behaviour from the Global Game Settings and have Windows behave the same as all other target platforms.

NOTE: There is a performance hit as the texture is uploaded to texture memory on most devices, so the best idea is to do a dummy render of the required graphics at the start of a level to avoid any stalls. You would only need to render a single graphic from each texture page to ensure that texture is loaded, and you should be aware that texture groups can have more than one texture page which means that each load will cause a stall.

Example:

draw_texture_flush();

The above code flushes the video memory of texture data, and would probably be placed in the create event of the first instance of an object placed in the room.

Back: Drawing
Next: draw_enable_drawevent

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_get_height

Gets the height of a given texture asset.

Syntax:

texture_get_height(tex);

Argument | Description
tex | The texture page asset pointer to use

Returns: Real

Description

Returns the height of the texture page with the given id, which is always a value within the range 0 - 1. This can then be used when mapping textures to models or primitives.

Example:

tex_h = texture_get_height(surface_get_texture(global.Surf));

The above code will get the height of the texture taken from a previously created surface.

Back: Drawing
Next: texture_get_texel_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_get_texel_height

Get the height of a single texel for a texture page.

Syntax:

texture_get_texel_height(tex);

Argument | Description
tex | The texture page asset pointer to use

Returns: Real

Description

A texel, or texture element is the fundamental unit of texture space used in computer graphics. Textures are represented by arrays of texels, just as pictures are represented by arrays of pixels, and this function returns the height of a single texel from the texture page of the image asset used.

Example:

var tex = sprite_get_texture(sprite_index, 0);
tex_w = texture_get_texel_width(tex);
tex_h = texture_get_texel_height(tex);

The above code will get the texel width and height of the texture taken from a sprite asset.

Back: Drawing
Next: texture_set_interpolation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_get_texel_width

Get the width of a single texel for a texture page.

Syntax:

texture_get_texel_width(tex);

Argument | Description
tex | The texture page asset pointer to use

Returns: Real

Description

A texel, or texture element is the fundamental unit of texture space used in computer graphics. Textures are represented by arrays of texels, just as pictures are represented by arrays of pixels, and this function returns the width of a single texel from the texture page of the image asset used.

Example:

var tex = sprite_get_texture(sprite_index, 0);
tex_w = texture_get_texel_width(tex);
tex_h = texture_get_texel_height(tex);

The above code will get the texel width and height of the texture taken from a sprite asset.

Back: Drawing
Next: texture_get_texel_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_get_width

Gets the width of a given texture asset.

Syntax:

texture_get_width(tex);

Argument | Description
tex | The texture page asset pointer to use

Returns: Real

Description

Returns the width of the texture page with the given id, which is always a value within the range 0 - 1. This can then be used when mapping textures to models or primitives.

Example:

tex_w = texture_get_width(sprite_get_texture(spr_Model_tex, 0));

The above code will get the width of the texture taken from a sprite asset.

Back: Drawing
Next: texture_get_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_global_scale

Used to control the scaling of the texture pages on load from the WAD file.

Syntax:

texture_global_scale(pow2integer);

Argument | Description
pow2integer | The scale factor to use (1, no scale, 2, half scale, 4, quarter scale, etc...)

Returns: N/A

Description

This function allows you to control the scaling of the texture pages on load from the WAD file that is part of your final game executable. The input value must be a power of two value and will work such that:

  • To set the texture pages to be 1:1 use texture_global_scale(1)
  • To half textures all the time use texture_global_scale(2)
  • To quarter them use texture_global_scale(4), etc...

In this way you can better control texture page memory usage on platforms with low memory issues, although note that for Windows, you will need to have checked the Create Textures On Demand option in the Global Game Settings - Graphics and then call the function draw_texture_flush before loading any scaled textures.

Example:

draw_texture_flush();
texture_global_scale(2);
sprite_prefetch(spr_Trees);

The above code will flush all textures from memory, then set the texture scaling to 2 (so texture pages are half size) and then finally pre-fetch the texture page that the sprite "spr_Trees" is contained within.

Back: Drawing
Next: draw_texture_flush

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_set_blending

Indicates whether to use blending with colours and alpha values.

Syntax:

texture_set_blending(blend);

Argument | Description
blend | Turn blending on (true) or off (false)

Returns: N/A

Description

This function can be used to turn off all alpha and colour blending in GameMaker: Studio. This will over-ride all other functions and means that all image assets (sprites and backgrounds) with an image alpha or image blend other than 1 and c_white, will be drawn with an alpha of 1 and blended with the default white colour. Switching this off can give a minor performance boost, but the default value is true.

Example:

if global.Blend
{
texture_set_blending(true);
}
else
{
texture_set_blending(false);
}

The above code will turn interpolation on or off depending on the value of a global variable.

Back: Drawing
Next: texture_set_repeat

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_set_interpolation

Indicates whether to use linear interpolation or not.

Syntax:

texture_set_interpolation(linear);

Argument | Description
linear | Turn linear interpolation on (true) or off (false).

Returns: N/A

Description

This function can be used to set the linear interpolation of all images drawn on the game screen with GameMaker: Studio. When this is set to on (true) all textures will be smoothed when drawn (this includes sprites as they too are considered textures), meaning that when scaled or moved if there is not a 1:1 pixel ratio then there will be a "smudging" across various pixels which may make images appear blurry depending on the art style used. If this is switch off (false) then images will be drawn based on the nearest pixel when scaled or moving which may lead to "blocky" images. The default value is false, and this can also be changed in the Global Game Settings for individual target platforms.

NOTE: This setting will over-ride any texture stage interpolation set for shaders using the function texture_set_interpolation_ext.

Example:

if global.Smoothing
{
texture_set_interpolation(true);
}
else
{
texture_set_interpolation(false);
}

The above code will turn interpolation on or off depending on the value of a global variable.

Back: Drawing
Next: texture_set_interpolation_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_set_interpolation_ext

Indicates whether to use linear interpolation or not for a given shader sampler.

Syntax:

texture_set_interpolation_ext(sampler_id, linear);

Argument | Description
sampler_id | The sampler id from the shader.
linear | Turn linear interpolation on (true) or off (false).

Returns: N/A

Description

This function can be used to set the linear interpolation a single sampler "slot" when using Shaders in GameMaker: Studio. When this is set to on (true) the sampler texture will be smoothed and if this is switch off (false) then images will be drawn based on the nearest pixel. The default value is that set by the Global Game Settings for your game, or that set using the function texture_set_interpolation.

NOTE: This setting will be over-ridden by the value set when calling the function texture_set_interpolation().

Example:

shader_sample = shader_get_sampler_index(shader_glass, "s_NoiseSampler");
texture_set_interpolation_ext(shader_sample, false);

The above code will turn interpolation of for the image used in the shader sampler.

Back: Drawing
Next: texture_set_blending

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_set_repeat

Indicates whether to use texture repeats.

Syntax:

texture_set_repeat(repeat);

Argument | Description
repeat | Turn texture repeats on (true) or off (false)

Returns: N/A

Description

This function can be used to indicate to GameMaker: Studio whether textures should repeat (true) or not (false) when used for models and primitives. Normally texture widths and heights lie in the range 0 - 1, but if you specify a value larger than 1 by default the rest is not drawn (the entire texture will be drawn with an "empty" section corresponding to the percentage over 1 that is used. So a value of 2 for a texture width or height would draw the texture in half the space and leave the other half empty). However, by using this function to set repeat to true the texture is repeated automatically over all models and primitives.

NOTE: Sprites and backgrounds are always drawn without repeating, so once you draw a sprite or background this value is reset to false. This default behaviour will not affect texture stage settings (ie: calling the function will, but the internal setting to false will not).

NOTE: This setting will over-ride any texture stage repeats set for shaders when using the function texture_set_interpolation_ext.

Example:

if global.Repeat
{
texture_set_repeat(true);
}
else
{
texture_set_repeat(false);
}

The above code will turn interpolation on or off depending on the value of a global variable.

Back: Drawing
Next: texture_set_repeat_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_set_repeat_ext

Indicates whether a given shader sampler texture should repeat or not.

Syntax:

texture_set_repeat_ext(sampler_id, repeat);

Argument | Description
sampler_id | The sampler id from the shader.
repeat | Indicate whether the texture should repeat (true) or not (false).

Returns: N/A

Description

This function can be used to set whether a single sampler "slot" repeats the given texture when using Shaders in GameMaker: Studio. Setting it to true will repeat the texture if the uv coordinates are out with the 0-1 range, while a setting of false will mean no repeating.

NOTE: This setting will be over-ridden by the value set when calling the function texture_set_repeat().

Example:

shader_sample = shader_get_sampler_index(shader_glass, "s_NoiseSampler");
texture_set_repeat_ext(shader_sample, true);

The above code will permit the texture to repeat of for the image used in the shader sampler.

Back: Drawing
Next: texture_set_stage

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


texture_set_stage

Indicates which texture "slot" to add a texture to when working with shaders.

Syntax:

texture_set_stage(stage, tex);

Argument | Description
stage | The texture "slot" to use.
tex | The texture to use.

Returns: N/A

Description

This function will set the given stage "slot" a texture to be used. The number of stage "slots" available will depend on the platform you are compiling to, with a maximum of 8 being available for Windows, Mac and Linux, but on lower end Android devices (for example) this number can be as low as 2. It is also worth noting that the first stage "slot" is always used automatically by GameMaker: Studio.

NOTE: This function will do nothing outside of the context of a running shader! See Shaders for more information.

Example:

glassshader_bgsampler = shader_get_sampler_index(GlassShader, "s_BackgroundSampler")
spr = sprite_get_texture(sprite_index, 0);
shader_set(GlassShader);
texture_set_stage(glassshader_bgsampler, spr);
shader_reset();

The above code will get the handle for the sampler within the shader indexed as "GlassShader" and then set that shader constant to the given sprite texture.

Back: Drawing
Next: texture_global_scale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Colour And Blending

This section deals with the functions related to colour, alpha and blending.

GameMaker: Studio has a comprehensive selection of functions to manipulate the colour, alpha and blending of what is drawn on the screen. Using these functions you can separate colours into their component parts, create new colours, manipulate the draw alpha and also play with blend modes to change how different things in your game are drawn together. Apart from these functions, there are also a number of constants that can be used as base colours in these (and other) functions:

Constant | Colour | Value
c_aqua |  | 16776960
c_black |  | 0
c_blue |  | 16711680
c_dkgray |  | 4210752
c_fuchsia |  | 16711935
c_gray |  | 8421504
c_green |  | 32768
c_lime |  | 65280
c_ltgray |  | 12632256
c_maroon |  | 128
c_navy |  | 8388608
c_olive |  | 32896
c_orange |  | 4235519
c_purple |  | 8388736
c_red |  | 255
c_silver |  | 12632256
c_teal |  | 8421376
c_white |  | 16777215
c_yellow |  | 65535

Getting colour and Alpha Values

The following functions can be used to get the component hues, compound hue, saturation and luminosity of a selected colour as well as the alpha and other properties:

  1. colour_get_blue
  2. colour_get_green
  3. colour_get_red
  4. colour_get_hue
  5. colour_get_saturation
  6. colour_get_value
  7. draw_getpixel
  8. draw_getpixel_ext
  9. draw_get_colour
  10. draw_get_alpha

Creating colours

These functions can be used to create colours from raw input values for colour components:

  1. make_colour_hsv
  2. make_colour_rgb
  3. merge_colour

Note that you can also create colours from their hexadecimal value using the "$" symbol beforehand, and these values can also be used in the colour functions to get component hues or for mixing, etc... The hexadecimal value for these colours is split into three parts with the format Blue - Green - Red so, for example, to define a purple colour you could use:

col = $983c95

Where 98 is the blue component, 3c is the green component and 95 is the red component.

Setting colour, Alpha and Blending

The following functions can be used to set the various different options for drawing to the screen, including alpha, colour and blending:

  1. draw_clear
  2. draw_clear_alpha
  3. draw_set_alpha
  4. draw_set_colour
  5. draw_set_colour_write_enable
  6. draw_set_blend_mode
  7. draw_set_blend_mode_ext
  8. draw_set_alpha_test
  9. draw_set_alpha_test_ref_value
  10. draw_get_alpha_test
  11. draw_get_alpha_test_ref_value
  12. draw_enable_alphablend

Back: Drawing

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


colour_get_blue

Returns the blue component of the colour given.

Syntax:

colour_get_blue(col);

Argument | Description
col | The colour to check

Returns: Real

Description

This function returns the amount of blue used to make the given colour, with the value being between 0 and 255, where 0 is no blue and 255 is all blue. The following image illustrates this:

Example:

b_comp = colour_get_blue(c_teal);

The above code will get the blue component of the colour constant "c_teal" and store the value in the variable "b_comp".

Back: colour And Blending
Next: colour_get_green

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


colour_get_green

Returns the green component of the colour given.

Syntax:

colour_get_green(col);

Argument | Description
col | The colour to check

Returns: Real

Description

This function returns the amount of green used to make the given colour, with the value being between 0 and 255, where 0 is no green and 255 is all green. The following image illustrates this:

Example:

g_comp = colour_get_green(c_teal);

The above code will get the green component of the colour constant "c_teal" and store the value in the variable "g_comp".

Back: colour And Blending
Next: colour_get_red

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


colour_get_hue

Returns the hue of the colour given.

Syntax:

colour_get_hue(col);

Argument | Description
col | The colour to check

Returns: Real

Description

This function will return the hue of the given colour. This is the "pure" colour tone which is part of the hue, saturation and value (luminosity) method for defining a colour. The following image illustrates how this value corresponds to the HSV scale of colour:

Example:

col = merge_colour(colour_get_hue(c_teal), c_white, 0.5);

The above code gets the hue used to make the colour constant "c_teal" and then merges it with white at a 50:50 ratio, storing the resulting colour in the variable "col".

Back: colour And Blending
Next: colour_get_saturation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


colour_get_red

Returns the red component of the colour given.

Syntax:

colour_get_red(col);

Argument | Description
col | The colour to check

Returns: Real

Description

This function returns the amount of red used to make the given colour, with the value being between 0 and 255, where 0 is no red and 255 is all red. The following image illustrates this:

Example:

r_comp = colour_get_red(c_teal);

The above code will get the red component of the colour constant "c_teal" and store the value in the variable "r_comp".

Back: colour And Blending
Next: colour_get_hue

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


colour_get_saturation

Returns the saturation of the colour given.

Syntax:

colour_get_saturation(col);

Argument | Description
col | The colour to check

Returns: Real

Description

This function will return the saturation of the given colour. This is the amount of the colour tone that is mixed into the final colour and is part of the hue, saturation and value (luminosity) method for defining a colour. The following image illustrates how this value corresponds to the HSV scale of colour:

Example:

col = make_colour_hsv(random(255), colour_get_sat(c_teal), 255);

The above code gets the saturation used to make the colour constant "c_teal" and then uses that value to set a random colour to have the same saturation, storing the resulting colour in the variable "col".

Back: colour And Blending
Next: colour_get_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


colour_get_value

Returns the value of the colour given.

Syntax:

colour_get_value(col);

Argument | Description
col | The colour to check

Returns: Real

Description

This function will return the value (luminosity) of the given colour. This is the amount of the "light" that is mixed into the final colour and is part of the hue, saturation and value method for defining a colour. The following image illustrates how this value corresponds to the HSV scale of colour:

Example:

col = make_colour_hsv(random(255), 255, colour_get_value(c_teal));

The above code gets the value used to make the colour constant "c_teal" and then uses that value to set a random colour to have the same luminosity, storing the resulting colour in the variable "col".

Back: colour And Blending
Next: draw_getpixel

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_clear

Clears the entire screen with colour.

Syntax:

draw_clear(col);

Argument | Description
col | The colour with which the screen will be cleared

Returns: N/A

Description

This function can be used to clear the entire screen (with no alpha blend) to the given colour, and is only for use in the draw event of an instance (it will not show if used in any other event). It can also be useful for clearing surfaces when they are newly created.

Example:

draw_clear(c_blue);

This will clear the screen with the colour blue.

Back: colour And blending
Next: draw_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_clear_alpha

Clears the entire screen with an alpha-blended given colour.

Syntax:

draw_clear_alpha(col, alpha);

Argument | Description
col | The colour with which the screen will be cleared
alpha | The transparency of the colour with which the screen will be cleared

Returns: N/A

Description

This function can be used to clear the entire screen with a given colour and the alpha component of the destination is set to the value you have set - this function does not do any blending as it works but any subsequent blend operations can be set up to use the destination alpha that you have set. This is only for use in the draw event of an instance (it will not show if used in any other event), and it can also be very useful for clearing surfaces when they are newly created.

It is worth noting that when using the HTML5 module, you can use this function to make the canvas background transparent, which will then permit any images being used in the host HTML to be seen with the game running over them. To achieve this effect you must first go into the room editor and untick the "Draw Background colour" option from the Background Tab, then untick the option "Clear Background with Window colour" found on the Views Tab. Finally, you will need to make a new object, place it in the first room of the game, and assign it a very low depth (for example, -1000000). Then in the Pre Draw event use this function to set the canvas alpha to the colour and transparency that you wish it to have.

Example:

draw_clear_alpha(c_red, 0.5);

This will clear the screen with 50% (0.5) transparency with the colour red.

Back: colour And blending
Next: draw_set_alpha

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_enable_alphablend

Toggles alpha blending on or off.

Syntax:

draw_enable_alphablend(val)

Argument | Description
val | This can be either true (switched on) or false (switched off)

Returns: N/A

Description

This function can be used to toggle alphablending on an off. Basically, if you have this set to false, all images being drawn will be drawn 100% opaque, meaning that any transparent, or semi transparent, areas of a sprite or background will be visible. It is encouraged that you have alpha blending off whenever possible (especially when developing for mobile devices) as this greatly increases the draw speed.

Example:

draw_enable_alphablend(false);
draw_background(0,0,back1);
draw_enable_alphablend(true);

The above code switches off alpha blending to draw a background resource and then switches it back on again to continue drawing.

Back: colour And blending
Next: draw_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_get_alpha

Gets the current draw alpha value.

Syntax:

draw_get_alpha()

Returns: Real

Description

This function returns the current value of the draw alpha, which will range between 0 (fully transparent) and 1 (fully opaque). The draw alpha affects the transparency of all draw functions, and can be set with the draw_set_alpha function.

Example:

if draw_get_alpha() != 1
{
draw_set_alpha(1);
}

The above code first checks the current draw alpha and then if it is not set to 1 it sets it to 1.

Back: colour And Blending
Next: draw_get_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_get_alpha_test

Returns the current state of alpha testing (enabled or not).

Syntax:

draw_get_alpha_test();

Returns: Boolean

Description

With this function you can check to see whether alpha testing is enabled (returns true) or not (returns false). For more information on alpha testing, see the function draw_set_alpha_test.

Example:

if !draw_get_alpha_test()
{
draw_set_alpha_test(true);
draw_set_alpha_test_ref_value(128);
}

The above code will check to see if alpha testing is enabled and if not it will switch on alpha testing and set the test threshold to 128 (only pixels with an alpha over 0.5 will be drawn).

Back: Drawing
Next: draw_get_alpha_test_ref_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_get_alpha_test_ref_value

Returns the current alpha testing reference value.

Syntax:

draw_get_alpha_test_ref_value();

Returns: Real

Description

You can use this function to find the current value for the alpha test reference (default is 0, but you can use draw_set_alpha_test_ref_value to set this value to something other than this).

Example:

if draw_get_alpha_test()
{
if draw_get_alpha_test_ref_value() < 254
{
draw_set_alpha_test_ref_value(254);
}
}

The above code checks to see if alpha testing is enabled, and if it is, it then checks the current alpha test reference value and sets it if it is less than 254.

Back: Drawing
Next: draw_enable_alphablend

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_get_colour

Gets the current draw colour.

Syntax:

draw_get_colour()

Returns: Real

Description

This function returns the current draw colour which is used for drawing forms, text, primitives and un-textured 3D models. This can be set with the draw_set_colour function.

Example:

if draw_get_colour() != c_black
{
draw_set_colour(c_black);
}

The above code first checks the current draw colour and then if it is not set to c_black it sets it to c_black.

Back: colour And Blending
Next: colour_get_blue

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_getpixel

Returns the colour of the pixel displayed at a given coordinate.

Syntax:

draw_getpixel(x, y);

Argument | Description
x | The x coordinate of the pixel to check
y | The y coordinate of the pixel to check

Returns: Real

Description

With this function you can get the colour value of any pixel that is being drawn to the current render target. This means that the results will depend on the event in which the function is called, and also on the target surface being used. Note that this will not return any alpha values, for that you should use draw_getpixel_ext.

NOTE: This function is incredibly slow and so should only be used when absolutely necessary.

Example:

draw_set_colour(draw_getpixel(500,200))

The above code will set the drawing colour for all text, forms and primitives to the colour of the pixel at (500,200) on the game screen.

Back: colour And Blending
Next: draw_getpixel_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_getpixel_ext

Returns the full 32bit value for the pixel displayed at a given coordinate.

Syntax:

draw_getpixel_ext(x, y);

Argument | Description
x | The x coordinate of the pixel to check
y | The y coordinate of the pixel to check

Returns: Real

Description

With this function you can get the full abgr 32bit value of any pixel that is being drawn to the current render target. This means that the results will depend on the event in which the function is called, and also on the target surface being used.

NOTE: This function is slow and so should only be used when absolutely necessary.

Example:

col = draw_getpixel_ext(mouse_x, mouse_y);
alpha = (col >> 24) & 255;
blue = (col >> 16) & 255;
green = (col >> 8) & 255;
red = col & 255;

The above code will get the 32bit colour value at the position of the mouse and then split it into its component values, storing them in variables.

Back: colour And Blending
Next: draw_get_alpha

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_alpha

Sets the base alpha blend for the draw functions.

Syntax:

draw_set_alpha(alpha);

Argument | Description
alpha | The alpha to set (between 0 and 1)

Returns: N/A

Description

With this function you can set the base draw alpha for the game. This value can be set from 0 to 1 with 0 being fully transparent and 1 being fully opaque (the default value), and will affect all further drawing, including backgrounds, sprites, fonts, primitives and 3D. If any of those assets are drawn with their own alpha value changed, this will be added to the base alpha value set by this function, so a base alpha of 0.5 and a sprite being drawn with an alpha of 0.5 will actually draw the sprite with an alpha of 0.25.

Example:

draw_set_alpha(0.5);
draw_set_colour(c_black);
draw_text(x+5, y+5, "LEVEL 1");
draw_set_alpha(1);
draw_set_colour(c_white);
draw_text(x, y, "LEVEL 1");

The above code will draw some text at the specified position with a shadow effect created by modified draw alpha and colour.

Back: colour And blending
Next: draw_set_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_alpha_test

Enable or disable alpha testing in your game.

Syntax:

draw_set_alpha_test(enable);

Argument | Description
enable | Set to true or false to enable or disable alpha testing.

Returns: N/A

Description

This function will enable or disable alpha testing for your game (by default this is disabled). By switching alpha testing on you can then use the companion function draw_set_alpha_test_ref_value to set the "cut-off" value at which all alpha values will be set to 0. The image below shows the difference that can be seen when alpha testing is switched on or off:

NOTE: This function may negatively affect performance on iOS and Android devices.

Example:

draw_set_alpha_test(true);
draw_set_alpha_test_ref_value(128);

The above code will switch on alpha testing and set the test threshold to 128 (only pixels with an alpha over 0.5 will be drawn).

Back: Drawing
Next: draw_set_alpha_test_ref_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_alpha_test_ref_value

Sets the reference value used by the alpha testing.

Syntax:

draw_set_alpha_test_ref_value(value);

Argument | Description
value | Sets the reference value for alpha testing from 0 to 255 (default value is 0)

Returns: N/A

Description

This function will set the reference value for the alpha testing (when it has been enabled using the draw_set_alpha_test). This is the "cut-off" threshold at which pixels with alpha will not be drawn.

Basically, if you have this value set to 0 and you have texture interpolation turned on, you can still get visual errors at the edges of overlapping objects. This is because you can have almost completely transparent areas that block things drawn behind them, but if you set this reference value to, for example, 254 (i.e. one below maximum), this guarantees that only 100% opaque pixels are going to be drawn. You can also turn texture interpolation off, which would normally allow you to use the default values with no problems and no need to use this function at all, however a lot depends on the source artwork.

NOTE: This is an advanced drawing feature, so if you are not sure whether you need it or not, or don't know exactly what it does, you are probably better off not using it as it can seriously corrupt how your game is drawn.

Example:

draw_set_alpha_test(true);
draw_set_alpha_test_ref_value(128);

The above code will switch on alpha testing and set the test threshold to 128 (only pixels with an alpha over 0.5 will be drawn).

Back: Drawing
Next: draw_get_alpha_test

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_blend_mode

Sets the blend mode for drawing.

Syntax:

draw_set_blend_mode( mode );

Argument | Description
mode | The blend mode constant to set to (see the table below).

Returns: N/A

Description

When GameMaker: Studio goes to draw a pixel there is a source colour (the colour of the pixel we're going to draw) and a destination colour(the colour that's already in the pixel we're drawing to), so when determining the new colour of the pixel, the source and destination colours are calculated according to the chosen blend mode. Each component of the colours is stored as a floating point value between 0 and 1, and the new colour is calculated by multiply each component of the source colour by some factor and by multiplying each component of destination colour by some other factor and then adding the results together component by component.

This function permits you to set the blend mode in four basic ways using the following constants:

Constant | Description | Extended Modes
bm_normal | Normal blending (the default blend mode). | (bm_src_alpha, bm_inv_src_alpha)
bm_add | Additive blending. Luminosity values of light areas are added. | (bm_src_alpha, bm_one)
bm_subtract | Subtractive blending. Luminosity values of light areas are subtracted. | (bm_zero, bm_inv_src_colour)
bm_max | Max blending. Similar to additive blending. | (bm_src_alpha, bm_inv_src_colour)

As you can see these modes are really composites of extended blend modes and those can be found on the page describing draw_set_blend_mode_ext.

Example:

draw_set_blend_mode( bm_add );
draw_circle_colour(100, 100, 50, c_white, c_black, 0);
draw_set_blend_mode( bm_normal );

This will turn the black into transparency, creating a 'glow' effect from the white being strong on the outside and gradually weakening further from the circle centre. The blend mode is reset after the circle is drawn to ensure additive blending is not also applied to everything else after it.

Back: colour And blending
Next: draw_set_blend_mode_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_blend_mode_ext

Sets an extended blend mode for drawing.

Syntax:

draw_set_blend_mode_ext(src, dest);

Argument | Description
src | Source (see constants above).
dest | Destination (see constants above)

Returns: N/A

Description

When GameMaker: Studio goes to draw a pixel there is a source colour (the colour of the pixel we're going to draw) and a destination colour(the colour that's already in the pixel we're drawing to), so when determining the new colour of the pixel, the source and destination colours are calculated according to the chosen blend mode. Each component of the colours is stored as a floating point value between 0 and 1, and the new colour is calculated by multiply each component of the source colour by some factor and by multiplying each component of destination colour by some other factor and then adding the results together component by component.

This function permits you to set the different component parts that should be factored together to create a custom blend mode. The source and destination both have a red, green, blue and alpha component, and in the following chart the source's RGBA are considered (Rs, Gs, Bs, As) while the destination's are (Rd, Gd, Bd, Ad). The eleven constants that are available for use can be either source or destination (or both) when used in this function.

Constant | Blend factor (Red, Green, Blue, Alpha)
bm_zero | (0, 0, 0, 0)
bm_one | (1, 1, 1, 1)
bm_src_colour | (Rs, Gs, Bs, As)
bm_inv_src_colour | (1-Rs, 1-Gs, 1-Bs, 1-As)
bm_src_alpha | (As, As, As, As)
bm_inv_src_alpha | (1-As, 1-As, 1-As, 1-As)
bm_dest_alpha | (Ad, Ad, Ad, Ad)
bm_inv_dest_alpha | (1-Ad, 1-Ad, 1-Ad, 1-Ad)
bm_dest_colour | (Rd, Gd, Bd, Ad)
bm_inv_dest_colour | (1-Rd, 1-Gd, 1-Bd, 1-Ad)
bm_src_alpha_sat | (f, f, f, 1) where f = min(As, 1-Ad)

It can be quite difficult to visualise how these different blend modes work, so below you can find a simple chart that shows the basic interaction of a single sprite being drawn with different combinations of blend modes over a single background. Please note that the actual results of the blend mode you use will very much depend on the colour in the sprite, the alpha value of the sprite and the colour and alpha of the background.

WARNING!: Not all blend modes are available on all platforms. Android, iOS, and HTML5 without WebGL enabled, will not be able to display the following modes correctly:

  • bm_src_colour
  • bm_inv_src_colour
  • bm_dest_colour
  • bm_inv_dest_colour
  • bm_src_alpha_sat

Example:

draw_set_blend_mode_ext(bm_src_alpha, bm_one);
draw_circle_colour(100, 100, 50, c_white, c_black, 0);
draw_set_blend_mode(bm_normal);

This will turn the black into transparency, creating a 'glow' effect from the white being strong on the outside and gradually weakening further from the circle centre. The blend mode is reset after the circle is drawn to ensure additive blending is not also applied to everything else after it.

Back: Colour And blending
Next: draw_set_alpha_test

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_colour

Sets the base colour for the draw functions.

Syntax:

draw_set_colour(col);

Argument | Description
col | The colour to set for drawing.

Returns: N/A

Description

With this function you can set the base draw colour for the game. This value will affect all further drawing where appropriate, including fonts, forms, primitives and 3D. If any of those assets are drawn with their own colour value changed, this value will be ignored.

Example:

draw_set_alpha(0.5);
draw_set_colour(c_black);
draw_text(x+5, y+5, "LEVEL 1");
draw_set_alpha(1);
draw_set_colour(c_white);
draw_text(x, y, "LEVEL 1");

The above code will draw some text at the specified position with a shadow effect created by modified draw alpha and colour.

Back: colour And blending
Next: draw_set_colour_write_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_colour_write_enable

Enable or disable separate channels for drawing.

Syntax:

draw_set_colour_write_enable(red, green, blue, alpha);

Argument | Description
red | The colour to set for drawing.
green | The colour to set for drawing.
blue | The colour to set for drawing.
alpha | The colour to set for drawing.

Returns: N/A

Description

With this function you can switch on or off the colour channels and the alpha channel for all further drawing. You can use this function to create alpha-channel only surfaces (switch off the RGB writing before using the surface), or to create special effects while drawing to the screen. The default value for each of the components is true.

Example:

draw_set_colour_write_enable(false, false, true, true);
draw_self();
draw_set_colour_write_enable(true, true, true, true);

The above code will draw only the blue and alpha channel of the current sprite for the instance.

Back: colour And blending
Next: draw_set_blend_mode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


make_colour_hsv

Returns a colour based on hue, saturation and value.

Syntax:

make_colour_hsv(hue, sat, val);

Argument | Description
hue | The hue of the colour
sat | How saturated the colour is
val | How dark the colour is

Returns: value

Description

GameMaker: Studio provides this function (as well as others) to permit the user to make their own colours. This particular function takes three component parts, the hue, the saturation and the value (also know as "luminosity") to create the colour desired. These values are taken as being between 0 and 255 so you can make 16,777,216 (256*256*256) colours with this! Below you can see an image of how these components look when separated: The image on the left is a break-down of the individual components of the function, and then on the right is an illustration of how changing these components affects the end colour. As you can see, even without changing the hue (it stays at 0, red), we can dramatically change the colour with the other two settings, with saturation making the colour tone go from grey (0) to a pure tone (255), and with the value making it go from darker (0) to lighter (255).

Example:

col = make_colour_hsv(100, 145, 255);

The above code uses the function to create a colour and store its value in the variable "col" for later use.

Back: colour and Blending
Next: make_colour_rgb

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


make_colour_rgb

Returns a colour based on the mix of red, green and blue component values.

Syntax:

make_colour_rgb(red, green, blue);

Argument | Description
red | The red component of the colour
green | The green component of the colour
blue | The blue component of the colour

Returns: value

Description

GameMaker: Studio provides this function (as well as others) to permit the user to make their own colours. This particular function takes three component parts, the red, the green and the blue components of the colour that you wish to make. These values are taken as being between 0 and 255 so you can make 16,777,216 (256*256*256) colours with this! Below you can see an image of how these components look when separated: The image on the left is a break-down of the individual components of the function, and then on the right is an illustration of how changing these components affects the end colour.

Example:

col = make_colour_rgb(100, 145, 255);

The above code uses the function to create a colour and store its value in the variable "col" for later use.

Back: colour and Blending
Next: merge_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


merge_colour

Merges two colours by a given amount.

Syntax:

merge_colour(col1, col2, amount);

Argument | Description
col1 | The first colour to merge
col2 | The second colour to merge
amount | How much of each colour should be merged. For example, 0 will return col1, 1 will return col2, and 0.5 would return a merge of both colours equally

Returns: value

Description

With this function you can take two colours and then merge them together to make a new colour. The amount of each of the component colours can be defined by changing the "amount" argument, where a value of 0 will return the first colour (col1), a value of 1 will return the second colour (col2) and a value in between will return the corresponding mix. For example, a value of 0.5 will mix the two colours equally. The following image illustrates how this works by merging the colours red and blue together:

Example:

col = merge_colour(c_lime, c_orange, 0.5);

The above code uses the function to create a colour by merging lime and orange 50/50 and then stores its value in the variable "col" for later use.

Back: colour and Blending
Next: make_colour_hsv

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Working With 3D

This section details all the functions available to you to create 3D games.

GameMaker: Studio is a primarily a program meant for making 2D (2-dimensional) and isometric games but there is the functionality to create 3D (3-dimensional) graphics and use 3D effects if you wish. Before you start with this though there are a few things you should understand:

  • The 3D functionality in GameMaker is limited to the graphics part. There is no support for other 3D functionality. Once you start using 3D graphics you might get problems with other aspects of GameMaker if you are not used to working with 3D. Things like views, depth ordering, etc... require you to have sound understanding of how GameMaker: Studio works as well as how to code 3D in general.

  • When you use the 3D functionality, there are a number of other things that can no longer be used:
    1. You cannot use background and foregrounds in your rooms anymore as they are tiled to fill the image but with perspective projections this no longer work correctly.
    2. You cannot use the mouse position as normal anymore either, because the mouse coordinates will not be transformed into 3D coordinates. You can, however, still get the position of the mouse on the screen (in the view) but you will have to do positional calculations yourself for 3D (or not use the mouse at all).
    3. You should not use tiles anymore as most tiles will likely no longer match up correctly. Collision checking still uses the 2-d positions of the instances in the room, so there is no collision detection in 3D. Sometimes you can still use this however, if you use the room as a representation of a flat world (e.g. for racing or FPS games) but in other situations you will have to do things yourself.
  • All 3D functionality is through code, so you must have a sound understanding of GML (the GameMaker language).

  • You must have some basic knowledge about 3D graphics, in things like perspective projections, hidden surface removal, lighting, and fog as this manual will not give much explanation and takes for granted that you are familiar with such terms.

NOTE: These functions do not work with the HTML5 module unless you have enabled WebGL in the Global Game Settings.

Information on 3d graphics can be found in the following pages:

  1. 3D Setup
  2. 3D Drawing
  3. 3D Projections
  4. 3D Transformations
  5. 3D Lighting and Fog
  6. 3D Models

Back: Game Graphics

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


3D Drawing

This section details all the functions available for drawing primitives and shapes in 3D.

The problem with drawing in the traditional (2D) way is that a sprite or polygon always lies in the xy-plane, that is, all corners have the same depth. For true 3D you want to be able to have vertices at different depths, and this depth is called the z-axis. So from this moment on we will talk about z-coordinate rather than depth, and we will specify coordinates as (x,y,z) tuples. It should also be noted that unless the colour or alpha is set by the function itself, you can use draw_set_colour and draw_set_alpha to set the drawing colour and alpha of the object being drawn.

For drawing basic primitives in 3D mode with these x,y,z coordinates we have the following functions:

  1. d3d_primitive_begin
  2. d3d_vertex
  3. d3d_vertex_colour
  4. d3d_primitive_end

For drawing textured primitives in 3D mode with these x,y,z coordinates we have the following functions (to end drawing use the d3d_primitive_end() function above):

  1. d3d_primitive_begin_texture
  2. d3d_vertex_texture
  3. d3d_vertex_texture_colour

You are not limited to just drawing your own shapes made from primitives either , as GameMaker: Studio has a set of functions that allow you to draw pre-defined shapes at any point in the 3D environment, with (or without) a texture mapping too (note that these functions can also be used with backface culling switched on):

  1. d3d_draw_block
  2. d3d_draw_cylinder
  3. d3d_draw_cone
  4. d3d_draw_ellipsoid
  5. d3d_draw_wall
  6. d3d_draw_floor

Back: Working With 3D
Next: 3D Projections

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_draw_block

Draws a simple 3D block.

Syntax:

d3d_draw_block(x1, y1, z1, x2, y2, z2, tex, hrepeat, vrepeat)

Argument | Description
x1 | The initial x coordinate of the block.
y1 | The initial y coordinate of the block.
z1 | The initial z coordinate of the block.
x2 | The opposite x coordinate of the block.
y2 | The opposite y coordinate of the block.
z2 | The opposite z coordinate of the block.
tex | The id of the texture to use (-1 for no texture)
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.

Returns: N/A

Description

This function draws a simple block in 3D space. You set the first corner coordinates (x1,y1,z1) and then the coordinates for the opposite corner. You can also specify a texture for the block and the amount of times that you wish this texture to be repeated vertically and horizontally. If you do not wish to use a texture you can set this to -1 and the hrepeat and vrepeat values will be ignored.

Note:If the texture has to repeat over the block, the source texture must be a power of 2 in size (eg: 8x8, 128x128, 256x256 etc...), otherwise you can use any size texture.

Example:

var tex;
tex = background_get_texture(bck_Wall);
d3d_draw_block(20, 20, 20, 80, 40, 200, tex, 1, 1);
d3d_draw_block(200, 300, -10, 240, 340, 100, tex, 1, 1);

The above code stores a texture in the variable "tex" and then uses it to texture two blocks that have been drawn at different positions.

Back: 3D Drawing
Next: d3d_draw_cylinder

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_draw_cone

Draws a simple 3D cone.

Syntax:

d3d_draw_cone(x1, y1, z1, x2, y2, z2, tex, hrepeat, vrepeat, closed, steps)

Argument | Description
x1 | The initial x coordinate of the cone.
y1 | The initial y coordinate of the cone.
z1 | The initial z coordinate of the cone.
x2 | The opposite x coordinate of the cone.
y2 | The opposite y coordinate of the cone.
z2 | The opposite z coordinate of the cone.
tex | The id of the texture to use (-1 for no texture)
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.
closed | Sets whether to close (true) the bottom of the cone or not (false).
steps | How many steps are used to make the cone "round" (typically 24)

Returns: N/A

Description

This function draws a simple cone in 3D space. You set the first bounding corner coordinates (x1,y1,z1) and then the bounding coordinates for the opposite corner, with the final cone being drawn inside this defined rectangular area. You then specify a texture for the cone and the amount of times that you wish this texture to be repeated vertically and horizontally (1 for no repeat). If you do not wish to use a texture you can set this to -1 and the hrepeat and vrepeat values will be ignored. Finally you have to set whether you want to close the base of the cone or not (set to true for closed, and false for open) as well as how many "steps" should be used to make the cone look "round", with a value of 24 being the average.

Note:If the texture has to repeat over the cone, the source texture must be a power of 2 in size (eg: 8x8, 128x128, 256x256 etc...), otherwise you can use any size texture.

Example:

var tex;
tex = background_get_texture(bck_Wall);
d3d_draw_cone(20, 20, 20, 80, 40, 200, tex, 1, 1, true, 24);
d3d_draw_cone(200, 300, -10, 240, 340, 100, tex, 1, 1, false, 24);

The above code stores a texture in the variable "tex" and then uses it to texture two cones (one open and one closed) that have been drawn at different positions.

Back: 3D Drawing
Next: d3d_draw_ellipsoid

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_draw_cylinder

Draws a simple 3D cylinder.

Syntax:

d3d_draw_cylinder(x1, y1, z1, x2, y2, z2, tex, hrepeat, vrepeat, closed, steps)

Argument | Description
x1 | The initial x coordinate of the cylinder.
y1 | The initial y coordinate of the cylinder.
z1 | The initial z coordinate of the cylinder.
x2 | The opposite x coordinate of the cylinder.
y2 | The opposite y coordinate of the cylinder.
z2 | The opposite z coordinate of the cylinder.
tex | The id of the texture to use (-1 for no texture)
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.
closed | Sets whether to close (true) the top and bottom of the cylinder or not (false).
steps | How many steps are used to make the cylinder "round" (typically 24)

Returns: N/A

Description

This function draws a simple cylinder in 3D space. You set the first bounding corner coordinates (x1,y1,z1) and then the bounding coordinates for the opposite corner, with the final cylinder being drawn inside this defined rectangular area. You then specify a texture for the cylinder and the amount of times that you wish this texture to be repeated vertically and horizontally (1 for no repeat). If you do not wish to use a texture you can set this to -1 and the hrepeat and vrepeat values will be ignored. Finally you have to set whether you want to close the ends of the cylinder or not (set to true for closed, and false for open) as well as how many "steps" should be used to make the cylinder look "round", with a value of 24 being the average.

Note:If the texture has to repeat over the cylinder, the source texture must be a power of 2 in size (eg: 8x8, 128x128, 256x256 etc...), otherwise you can use any size texture.

Example:

var tex;
tex = background_get_texture(bck_Wall);
d3d_draw_cylinder(20, 20, 20, 80, 40, 200, tex, 1, 1, true, 24);
d3d_draw_cylinder(200, 300, -10, 240, 340, 100, tex, 1, 1, false, 24);

The above code stores a texture in the variable "tex" and then uses it to texture two cylinders (one open and one closed) that have been drawn at different positions.

Back: 3D Drawing
Next: d3d_draw_cone

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_draw_ellipsoid

Draws a simple 3D ellipsoid.

Syntax:

d3d_draw_ellipsoid(x1, y1, z1, x2, y2, z2, tex, hrepeat, vrepeat, closed, steps)

Argument | Description
x1 | The initial x coordinate of the ellipsoid.
y1 | The initial y coordinate of the ellipsoid.
z1 | The initial z coordinate of the ellipsoid.
x2 | The opposite x coordinate of the ellipsoid.
y2 | The opposite y coordinate of the ellipsoid.
z2 | The opposite z coordinate of the ellipsoid.
tex | The id of the texture to use (-1 for no texture)
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.
steps | How many steps are used to make the ellipsoid "round" (typically 24)

Returns: N/A

Description

This function draws a simple ellipsoid in 3D space. You set the first bounding corner coordinates (x1,y1,z1) and then the bounding coordinates for the opposite corner, with the final ellipsoid being drawn inside this defined rectangular area. You then specify a texture for the ellipsoid and the amount of times that you wish this texture to be repeated vertically and horizontally (1 for no repeat). If you do not wish to use a texture you can set this to -1 and the hrepeat and vrepeat values will be ignored. Finally you have to set whether you want to close the base of the cone or not (set to true for closed, and false for open) as well as how many "steps" should be used to make the ellipsoid look "round", with a value of 24 being the average.

Note:If the texture has to repeat over the ellipsoid, the source texture must be a power of 2 in size (eg: 8x8, 128x128, 256x256 etc...), otherwise you can use any size texture.

Example:

var tex;
tex = background_get_texture(bck_Wall);
d3d_draw_ellipsoid(20, 20, 20, 80, 40, 200, tex, 1, 1, 24);
d3d_draw_ellipsoid(200, 300, -10, 240, 340, 100, tex, 1, 1, 24);

The above code stores a texture in the variable "tex" and then uses it to texture two ellipsoids that have been drawn at different positions.

Back: 3D Drawing
Next: d3d_draw_wall

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_draw_floor

Draws a simple 3D floor.

Syntax:

d3d_draw_floor(x1, y1, z1, x2, y2, z2, tex, hrepeat, vrepeat)

Argument | Description
x1 | The initial x coordinate of the floor.
y1 | The initial y coordinate of the floor.
z1 | The initial z coordinate of the floor.
x2 | The opposite x coordinate of the floor.
y2 | The opposite y coordinate of the floor.
z2 | The opposite z coordinate of the floor.
tex | The id of the texture to use (-1 for no texture)
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.

Returns: N/A

Description

This function draws a simple floor in 3D space. You set the first corner coordinates (x1,y1,z1) and then the coordinates for the opposite lower corner. You can also specify a texture for the floor and the amount of times that you wish this texture to be repeated vertically and horizontally. If you do not wish to use a texture you can set this to -1 and the hrepeat and vrepeat values will be ignored. This function appears to be exactly the same as the function to draw a wall, but the way they work is actually quite different, as illustrated in the image below:

Note:If the texture has to repeat over the floor, the source texture must be a power of 2 in size (eg: 8x8, 128x128, 256x256 etc...), otherwise you can use any size texture.

Example:

var tex;
tex = background_get_texture(bck_Floor);
d3d_draw_floor(100, 140, 200, 20, 20, 0, tex, 1, 1);

The above code stores a texture in the variable "tex" and then uses it to texture a sloping floor that has been drawn.

Back: 3D Drawing
Next: d3d_primitive_begin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_draw_wall

Draws a simple 3D vertical wall.

Syntax:

d3d_draw_wall(x1, y1, z1, x2, y2, z2, tex, hrepeat, vrepeat)

Argument | Description
x1 | The initial x coordinate of the wall.
y1 | The initial y coordinate of the wall.
z1 | The initial z coordinate of the wall.
x2 | The opposite x coordinate of the wall.
y2 | The opposite y coordinate of the wall.
z2 | The opposite z coordinate of the wall.
tex | The id of the texture to use (-1 for no texture)
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.

Returns: N/A

Description

This function draws a simple wall in 3D space. You set the first corner coordinates (x1,y1,z1) and then the coordinates for the opposite, lower corner. You can also specify a texture for the wall and the amount of times that you wish this texture to be repeated vertically and horizontally. If you do not wish to use a texture you can set this to -1 and the hrepeat and vrepeat values will be ignored. This function appears to be exactly the same as the function to draw a floor, but the way they work is actually quite different, as, with this, the end result will always be vertical in the 3D plane, as illustrated in the image below:

Note:If the texture has to repeat over the wall, the source texture must be a power of 2 in size (eg: 8x8, 128x128, 256x256 etc...), otherwise you can use any size texture.

Example:

var tex;
tex = background_get_texture(bck_Wall);
d3d_draw_wall(100, 140, 200, 20, 20, 0, tex, 1, 1);
d3d_draw_wall(240, 340, 200, 200, 320, 0, tex, 1, 1);

The above code stores a texture in the variable "tex" and then uses it to texture two walls that have been drawn at different positions.

Back: 3D Drawing
Next: d3d_draw_floor

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_primitive_begin

Begins the process of defining a primitive in 3D.

Syntax:

d3d_primitive_begin(kind)

Argument | Description
kind | The kind of primitive you are going to draw.

Returns: N/A

Description

This function must be called before you can define any primitives. There are 6 types of primitives you can define with the following constants:

  • pr_pointlist
  • pr_linelist
  • pr_linestrip
  • pr_trianglelist
  • pr_trianglestrip
  • pr_trianglefan (This is not available on the HTML5 target platform and may not work correctly on some devices for other platforms)

The following image illustrates basically how these should look and also the order in which you should define the vertexes:

Example:

d3d_primitive_begin(pr_trianglelist);
d3d_vertex(100, 100, 0);
d3d_vertex(100, 200, 0);
d3d_vertex(150, 150, 200);
d3d_vertex(100, 200, 0);
d3d_vertex(200, 200, 0);
d3d_vertex(150, 150, 200);
d3d_vertex(200, 200, 0);
d3d_vertex(100, 100, 0);
d3d_vertex(150, 150, 200);
d3d_vertex(100, 100, 0);
d3d_vertex(100, 200, 0);
d3d_vertex(200, 200, 0);
d3d_primitive_end();

The above code will draw a tetrahedron standing on the z=0 plane with its top at z = 200.

Back: 3D Drawing
Next: d3d_vertex

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_primitive_begin

d3d_primitive_begin_texture

Begins the process of defining a textured primitive in 3D.

Syntax:

d3d_primitive_begin_texture(kind, tex)

Argument | Description
kind | The kind of primitive you are going to draw.
tex | The texture to use with the primitive.

Returns: N/A

Description

This function must be called before you define the vertexes for a textured primitive. You must give the kind of primitive to use (see d3d_primitive_begin for more information) and the texture to use, which is a sprite or background resource. One thing you must realize is that in a texture the position (0,0) is the top-left corner, but often when using projections the bottom-left corner is (0,0). In such a case you might need to flip the texture vertically.

Note:If the texture has to repeat over the primitive, the source texture must be a power of 2 in size (eg: 8x8, 128x128, 256x256 etc...), otherwise you can use any size.

Example:

var tex;
tex = background_get_texture(back);
d3d_primitive_begin_texture(pr_trianglelist, tex);
d3d_vertex_texture(0, 480, 0, 0, 0);
d3d_vertex_texture(640, 480, 0, 1, 0);
d3d_vertex_texture(640, 480, 1000, 1, 1);
d3d_vertex_texture(0, 480, 1000, 0, 1);
d3d_primitive_end();

The above code will draw a 4 vertex triangle list textured with the texture held in the "tex" variable.

Back: 3D Drawing
Next: d3d_vertex_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_primitive_end

Ends the process of defining a primitive in 3D.

Syntax:

d3d_primitive_end()

Returns: N/A

Description

This function must be called when you have finished defining the points of your primitive. If you do not call this function, nothing will be drawn as this effectively tells GameMaker: Studio that you have finished and that it can now draw the defined primitive.

Example:

d3d_primitive_begin(pr_trianglelist);
d3d_vertex_colour(100, 100, 0, c_blue, 0.1);
d3d_vertex_colour(100, 200, 0, c_blue, 0.1);
d3d_vertex_colour(150, 150, 200, c_red, 1);
d3d_vertex_colour(100, 200, 0, c_blue, 0.1);
d3d_vertex_colour(200, 200, 0, c_blue, 0.1);
d3d_vertex_colour(150, 150, 200, c_red, 1);
d3d_vertex_colour(200, 200, 0, c_blue, 0.1);
d3d_vertex_colour(100, 100, 0, c_blue, 0.1);
d3d_vertex_colour(150, 150, 200, c_red, 1);
d3d_vertex_colour(100, 100, 0, c_blue, 0.1);
d3d_vertex_colour(100, 200, 0, c_blue, 0.1);
d3d_vertex_colour(200, 200, 0, c_blue, 0.1);
d3d_primitive_end();

The above code will draw a tetrahedron standing on the z=0 plane with its top coloured red and fully opaque at z = 200, while its base will be blue and transparent.

Back: 3D Drawing
Next: d3d_primitive_begin_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_vertex

Defines a vertex for a primitive in 3D.

Syntax:

d3d_vertex(x, y, z)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.

Returns: N/A

Description

This function defines the position of a vertex for a primitive. The final look of the primitive will depend on the primitive type chosen to draw and the order with which you add the vertexes to it. See d3d_primitive_begin for more information. To end and draw the primitive you must call d3d_primitive_end.

Example:

d3d_primitive_begin(pr_trianglelist);
d3d_vertex(100, 100, 0);
d3d_vertex(100, 200, 0);
d3d_vertex(150, 150, 200);
d3d_vertex(100, 200, 0);
d3d_vertex(200, 200, 0);
d3d_vertex(150, 150, 200);
d3d_vertex(200, 200, 0);
d3d_vertex(100, 100, 0);
d3d_vertex(150, 150, 200);
d3d_vertex(100, 100, 0);
d3d_vertex(100, 200, 0);
d3d_vertex(200, 200, 0);
d3d_primitive_end();

The above code will draw a tetrahedron standing on the z=0 plane with its top at z = 200.

Back: 3D Drawing
Next: d3d_vertex_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_vertex_colour

Defines a primitive vertex with colour and alpha blending in 3D.

Syntax:

d3d_vertex_colour(x, y, z, col, alpha)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
col | The colour to draw this vertex with.
alpha | The alpha to draw this vertex with (0-1).

Returns: N/A

Description

This function defines the position of a vertex for a primitive, with its own colour and alpha setting. The final look of the primitive will depend on the primitive type chosen to draw and the order with which you add the vertexes to it (see d3d_primitive_begin for more information) and the vertexes with different colours and alphas will blend smoothly from one to the other. To end and draw the primitive you must call d3d_primitive_end.

Example:

d3d_primitive_begin(pr_trianglelist);
d3d_vertex_colour(100, 100, 0, c_blue, 0.1);
d3d_vertex_colour(100, 200, 0, c_blue, 0.1);
d3d_vertex_colour(150, 150, 200, c_red, 1);
d3d_vertex_colour(100, 200, 0, c_blue, 0.1);
d3d_vertex_colour(200, 200, 0, c_blue, 0.1);
d3d_vertex_colour(150, 150, 200, c_red, 1);
d3d_vertex_colour(200, 200, 0, c_blue, 0.1);
d3d_vertex_colour(100, 100, 0, c_blue, 0.1);
d3d_vertex_colour(150, 150, 200, c_red, 1);
d3d_vertex_colour(100, 100, 0, c_blue, 0.1);
d3d_vertex_colour(100, 200, 0, c_blue, 0.1);
d3d_vertex_colour(200, 200, 0, c_blue, 0.1);
d3d_primitive_end();

The above code will draw a tetrahedron standing on the z=0 plane with its top coloured red and fully opaque at z = 200, while its base will be blue and transparent.

Back: 3D Drawing
Next: d3d_primitive_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_vertex_texture

Defines a vertex for a textured primitive in 3D.

Syntax:

d3d_vertex_texture(x, y, z, xtex, ytex)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xtex | Starting x coordinate within the texture.
ytex | Starting y coordinate within the texture.

Returns: N/A

Description

This function defines the position of a textured vertex for a primitive. The final look of the primitive will depend on the primitive type chosen to draw (See d3d_primitive_begin for more information), the order with which you add the vertexes to it and the position of the start point you set for the texture. To end and draw the primitive you must call d3d_primitive_end.

Note: In a texture the position (0,0) is the top-left corner, but often when using projections the bottom-left corner is (0,0). In such a case you might need to flip the texture vertically.

Example:

var tex;
tex = background_get_texture(back);
d3d_primitive_begin_texture(pr_trianglelist, tex);
d3d_vertex_texture(0, 480, 0, 0, 0);
d3d_vertex_texture(640, 480, 0, 1, 0);
d3d_vertex_texture(640, 480, 1000, 1, 1);
d3d_vertex_texture(0, 480, 1000, 0, 1);
d3d_primitive_end();

The above code will draw a 4 vertex triangle list textured with the texture held in the "tex" variable.

Back: 3D Drawing
Next: d3d_vertex_texture_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_vertex_texture_colour

Defines a vertex for a textured primitive in 3D, giving a blend colour and alpha.

Syntax:

d3d_vertex_texture_colour(x, y, z, xtex, ytex, col, alpha)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xtex | Starting x coordinate within the texture.
ytex | Starting y coordinate within the texture.
col | The colour to blend with the texture at this vertex (-1 or c_white for no blending).
alpha | The alpha to draw this vertex with (0-1).

Returns: N/A

Description

This function defines the position of a textured vertex for a primitive. The final look of the primitive will depend on the primitive type chosen to draw (See d3d_primitive_begin for more information), the order with which you add the vertexes to it, the position of the start point you set for the texture and the colour and alpha values that you have set. To maintain the texture appearance while changing only the alpha, a value of -1 (or c_white) may be used for the colour argument. To end and draw the primitive you must call d3d_primitive_end.

Note: In a texture the position (0,0) is the top-left corner, but often when using projections the bottom-left corner is (0,0). In such a case you might need to flip the texture vertically.

Example:

var tex;
tex = background_get_texture(back);
d3d_primitive_begin_texture(pr_trianglelist, tex);
d3d_vertex_texture_colour(0, 480, 0, 0, 0, c_blue, 1);
d3d_vertex_texture_colour(640, 480, 0, 1, 0, c_red, 1);
d3d_vertex_texture_colour(640, 480, 1000, 1, 1, c_green, 1);
d3d_vertex_texture_colour(0, 480, 1000, 0, 1, c_fuchsia, 1);
d3d_primitive_end();

The above code will draw a 4 vertex triangle list textured with the texture held in the "tex" variable. Each of the 4 vertexes will be blended with a different colour.

Back: 3D Drawing
Next: d3d_draw_block

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


3D Lighting and Fog

This section details all the functions available to you for lighting the 3D scene.

Scenes you draw with the GameMaker: Studio functions may look rather flat because there is no lighting to give them realism and life, meaning that the colour of the faces is equal all over, independent of their orientation or position. Therefore, to create more realistically looking scenes you must enable lighting and place lights at the correct places within the 3D world, and this section outlines the functions available to help you achieve that:

  1. d3d_set_fog
  2. d3d_set_lighting
  3. d3d_set_shading
  4. d3d_light_define_direction
  5. d3d_light_define_point
  6. d3d_light_enable
  7. d3d_light_define_ambient

It is worth noting that all targets except Android use smooth shading for lighting, but on Android this is hard shading. On the Windows platform this can be changed using the d3d_set_shading() function, but for all other platforms you should use a shader to create different lighting types.

Vertex Normal Functions

The way an object reflects light depends on the angle between the light direction and the normal of the surface, that is, the vector pointing away from the surface. Hence, to create lit objects you need not only provide the position of the vertices but also their normals. For this four additional functions are available to define the vertices of primitives (for the basic shapes that you can draw the normals are automatically set correctly):

  1. d3d_vertex_normal
  2. d3d_vertex_normal_colour
  3. d3d_vertex_normal_texture
  4. d3d_vertex_normal_texture_colour

The above functions are used to define a primitive in the same was as that outlined in the section 3D Drawing.

Back: Working With 3D
Next: 3D Models

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_light_define_ambient

Set the colour for the ambient lighting of a 3D scene.

Syntax:

d3d_light_define_ambient(colour)

Argument | Description
colour | The colour of the ambient light.

Returns: N/A

Description

This function is used to control the ambient light of a scene, which is the light that you have in a scene even without having defined any point or directional light sources. It is effectively the overall colour and brightness (or darkness) of a scene, and the default colour is c_black.

Example:

d3d_light_define_ambient(c_white);

The above code will define the ambient lighting as being white.

Back: 3D Drawing
Next: d3d_vertex_normal

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_light_define_direction

Defines a directed light.

Syntax:

d3d_light_define_direction(ind, dx, dy, dz, col)

Argument | Description
ind | The index number of the light.
dx | The x component of the light vector.
dy | The y component of the light vector.
dz | The z component of the light vector.
col | The colour of the light.

Returns: N/A

Description

To use lighting you obviously need to define lights. In GameMaker: Studio two different lights exist: directional lights (like the sun), and positional lights. This function is for a directional light, and the direction and intensity are set by the values input for the x,y and z unit vector (meaning that they must be between -1 and 1, where 1 or -1 is full intensity, and 0 is no intensity). The lights can also be given a colour, which will also affect the perceived intensity of the light as certain colours appear "darker" than others. You must also give the light an index number which what will be used in other functions to reference it.

Note: There are only 8 hardware lights available, so you should use these functions to define and manage "active" lights, not all lights in the scene.

Example:

d3d_set_lighting(true);
d3d_light_define_direction(1, 0, 1, 0, c_white);
d3d_light_enable(1, true);

The above code will enable lighting for the whole scene, then define a white light and finally turn that light on.

Back: 3D Drawing
Next: d3d_light_define_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_light_define_point

Defines a point light.

Syntax:

d3d_light_define_point(ind, x, y, z, range, col)

Argument | Description
ind | The index number of the light.
x | The x position of the light.
y | The y position of the light.
z | The z position of the light.
range | The light range.
col | The colour of the light.

Returns: N/A

Description

To use lighting you obviously need to define lights. In GameMaker: Studio two different lights exist: directional lights (like the sun), and positional lights. This function is for a positional light, where you can define the x, y and z position of the light, the light range and the colour of the light (which will also affect the perceived intensity of the light as certain colours appear "darker" than others). You must also give the light an index number which what will be used in other functions to reference it.

Note: There are only 8 hardware lights available, so you should use these functions to define and manage "active" lights, not all lights in the scene.

Example:

d3d_set_lighting(true);
d3d_light_define_point(1, 200, 123, 50, 2000, c_white);
d3d_light_enable(1, true);

The above code will enable lighting for the whole scene, then define a white light at a specific point in the room space, and finally turn that light on.

Back: 3D Drawing
Next: d3d_light_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_light_enable

Switches on or off the indexed light.

Syntax:

d3d_light_enable(ind, enable)

Argument | Description
ind | The index number of the light.
enable | Switches on (true) or off (false) the indexed light.

Returns: N/A

Description

This function is used to enable a defined light. When you define a positional or a directional light you must assign it an index number which is then used by this function to switch the light on or off.

Example:

d3d_set_lighting(true);
d3d_light_define_point(1, 200, 123, 50, c_white);
d3d_light_enable(1, true);

The above code will enable lighting for the whole scene, then define a white light at a specific point in the room space, and finally turn that light on.

Back: 3D Drawing
Next: d3d_light_define_ambient

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_fog

Enables or disables the use of fog.

Syntax:

d3d_set_fog(enable, colour, start, end)

Argument | Description
enable | Turn fog on (true) or off (false).
colour | The fog colour.
start | The distance where polygons start to be blended with the fog colour.
end | The distance at which fog is maximal and nothing can be seen anymore.

Returns: N/A

Description

Fog can be used in 3D games to make objects in the distance look blurred or even disappear, which helps in creating atmosphere and it also masks the fact that you are not drawing objects that are far away. Note that The fog start indicates the radius relative to the viewpoint where the fog starts, and the fog end indicates at which radius (also relative) objects will be completely invisible.

Example:

d3d_set_fog(true, c_white, 1000, 2000);

The above code sets the fog for a 3D game.

Back: 3D Drawing
Next: d3d_set_lighting

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_lighting

Enables or disables the use of lighting.

Syntax:

d3d_set_lighting(enable)

Argument | Description
enable | Turn lighting on (true) or off (false).

Returns: N/A

Description

This function tells GameMaker: Studio to enable lighting. When lighting is enabled, you will need to add lights to the world, otherwise, all the primitives will be black.

Example:

d3d_set_lighting(true);

The above code switches on lighting for the 3D scene.

Back: 3D Drawing
Next: d3d_set_shading

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_shading

Set whether to use smooth shading or not.

Syntax:

d3d_set_shading(smooth)

Argument | Description
enable | Turn smooth shading on (default: true) or off (false).

Returns: N/A

Description

When using lighting, for each vertex of a polygon the colour is determined, then the colour of internal pixels is based on the colour of these vertexes. There are two ways this can be done: Either the whole polygon gets the same colour, or the colour is smoothly interpolated over the polygon. By default smooth shading is used, but that behaviour can be changed using this function.

NOTE: This is a Windows only function, and should not be used on any other target platform.

Example:

d3d_set_shading(true);

The above code switches off smooth shading for the 3D scene.

Back: 3D Drawing
Next: d3d_light_define_direction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_vertex_normal

Defines a vertex for a primitive in 3D along with its corresponding normal.

Syntax:

d3d_vertex_normal(x, y, z, nx, ny, nz)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xn | The x component of the normal vector.
yn | The y component of the normal vector.
zn | The z component of the normal vector.

Returns: N/A

Description

This function defines the position of a vertex for a primitive, and assigns a normal to that vertex for the purposes of lighting. The final look of the primitive will depend on the primitive type chosen to draw, the order with which you add the vertexes to it, and the normal that you define for it as well as the lighting. See d3d_primitive_begin for more information on primitives. To end and draw the primitive you must call d3d_primitive_end.

Example:

d3d_primitive_begin(pr_trianglelist);
d3d_vertex_normal(-128, 0, -48, 0, 0.5, -0.5);
d3d_vertex_normal(-128, 96, 48, 0, 0.5, -0.5);
d3d_vertex_normal(128, 0, -48, 0, 0.5, -0.5);
d3d_vertex_normal(128, 0, -48, 0, 0.5, -0.5);
d3d_vertex_normal(-128, 96, 48, 0, 0.5, -0.5);
d3d_vertex_normal(128, 96, 48, 0, 0.5, -0.5);
d3d_primitive_end();

The above code will draw a sloped rectangle with the correct normal vectors for lighting.

Back: 3D Drawing
Next: d3d_vertex_normal_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_vertex_normal_colour

Defines a vertex for a primitive in 3D along with its corresponding normal, colour blending and alpha.

Syntax:

d3d_vertex_normal(x, y, z, nx, ny, nz, col, alpha)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xn | The x component of the normal vector.
yn | The y component of the normal vector.
zn | The z component of the normal vector.
col | The colour to blend with the vertex (c_white or -1 is no blend).
alpha | The alpha of the vertex (0 - 1).

Returns: N/A

Description

This function defines the position of a vertex for a primitive, assigns a normal to that vertex for the purposes of lighting, and permits you to set a blend colour and an alpha value too. The final look of the primitive will depend on the primitive type chosen to draw, the order with which you add the vertexes to it, and the normal that you define for it as well as the lighting. See d3d_primitive_begin for more information on primitives. To end and draw the primitive you must call d3d_primitive_end.

Example:

d3d_primitive_begin(pr_trianglelist);
d3d_vertex_normal_colour(-128, 0, -48, 0, 0.5, -0.5, c_red, 0.5);
d3d_vertex_normal_colour(-128, 96, 48, 0, 0.5, -0.5, c_red, 0.5);
d3d_vertex_normal_colour(128, 0, -48, 0, 0.5, -0.5, c_red, 0.5);
d3d_vertex_normal_colour(128, 0, -48, 0, 0.5, -0.5, c_red, 0.5);
d3d_vertex_normal_colour(-128, 96, 48, 0, 0.5, -0.5, c_red, 0.5);
d3d_vertex_normal_colour(128, 96, 48, 0, 0.5, -0.5, c_red, 0.5);
d3d_primitive_end();

The above code will draw a sloped rectangle with the correct normal vectors for lighting, blended with the colour red and made semi-transparent with an alpha value of 0.5.

Back: 3D Drawing
Next: d3d_vertex_normal_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_vertex_normal_texture

Defines a vertex for a textured primitive in 3D along with its corresponding normal.

Syntax:

d3d_vertex_normal_texture(x, y, z, nx, ny, nz, xtex, ytex)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xn | The x component of the normal vector.
yn | The y component of the normal vector.
zn | The z component of the normal vector.
xtex | Starting x coordinate within the texture (0 - 1).
ytex | Starting y coordinate within the texture (0 - 1).

Returns: N/A

Description

This function defines the position of a vertex for a primitive, assigns a normal to that vertex for the purposes of lighting and then assigns a texture. The final look of the primitive will depend on the primitive type chosen to draw, the order with which you add the vertexes to it, and the normal that you define for it as well as the lighting. See d3d_primitive_begin for more information on primitives. To end and draw the primitive you must call d3d_primitive_end.

Example:

var tex;
tex = background_get_texture(bck_Floor);
d3d_primitive_begin_texture(pr_trianglelist, tex);
d3d_vertex_normal_texture(-128, 0, -48, 0, 0.5, -0.5, 0, 0);
d3d_vertex_normal_texture(-128, 96, 48, 0, 0.5, -0.5, 1, 0);
d3d_vertex_normal_texture(128, 0, -48, 0, 0.5, -0.5, 0, 0.5);
d3d_vertex_normal_texture(128, 0, -48, 0, 0.5, -0.5, 1, 0.5);
d3d_vertex_normal_texture(-128, 96, 48, 0, 0.5, -0.5, 0, 1);
d3d_vertex_normal_texture(128, 96, 48, 0, 0.5, -0.5, 1, 1);
d3d_primitive_end();

The above code will draw a textured, sloped rectangle with the correct normal vectors for lighting.

Back: 3D Drawing
Next: d3d_vertex_normal_texture_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_vertex_normal_texture_colour

Defines a vertex for a textured primitive in 3D along with its corresponding normal, colour blending and alpha.

Syntax:

d3d_vertex_normal_texture_colour(x, y, z, nx, ny, nz, xtex, ytex, col, alpha)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xn | The x component of the normal vector.
yn | The y component of the normal vector.
zn | The z component of the normal vector.
xtex | Starting x coordinate within the texture (0 - 1).
ytex | Starting y coordinate within the texture (0 - 1).
col | The colour to blend with the vertex (c_white or -1 is no blend).
alpha | The alpha of the vertex (0 - 1).

Returns: N/A

Description

This function defines the position of a vertex for a primitive, assigns a normal to that vertex for the purposes of lighting and then assigns a texture as well as a blend colour and alpha transparency. The final look of the primitive will depend on the primitive type chosen to draw, the order with which you add the vertexes to it, and the normal that you define for it as well as the lighting. See d3d_primitive_begin for more information on primitives. To end and draw the primitive you must call d3d_primitive_end.

Example:

var tex;
tex = background_get_texture(bck_Floor);
d3d_primitive_begin_texture(pr_trianglelist, tex);
d3d_vertex_normal_texture_colour(-128, 0, -48, 0, 0.5, -0.5, 0, 0, c_lime, 0.5);
d3d_vertex_normal_texture_colour(-128, 96, 48, 0, 0.5, -0.5, 1, 0, c_lime, 0.5);
d3d_vertex_normal_texture_colour(128, 0, -48, 0, 0.5, -0.5, 0, 0.5, c_lime, 0.5);
d3d_vertex_normal_texture_colour(128, 0, -48, 0, 0.5, -0.5, 1, 0.5, c_lime, 0.5);
d3d_vertex_normal_texture_colour(-128, 96, 48, 0, 0.5, -0.5, 0, 1, c_lime, 0.5);
d3d_vertex_normal_texture_colour(128, 96, 48, 0, 0.5, -0.5, 1, 1, c_lime, 0.5);
d3d_primitive_end();

The above code will draw a textured, sloped rectangle with the correct normal vectors for lighting, blended green and with a semi-transparent alpha.

Back: 3D Drawing
Next: d3d_set_fog

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


3D Models

This section details all the functions available to you for using and creating 3D models.

When you need to draw large models it is rather expensive to call all the different drawing functions again and again in every step, so to avoid this you can create models. A model consists of a number of primitives and shapes that are all drawn together as a whole. Once a model is created you can draw it at different places with just one function call, models can also be loaded or saved to a file. Using models can considerable speed up the graphics in your 3D games and you should use them whenever you can.

Before giving the different functions available there is one important point: the handling of textures. Textures are taken from sprites and backgrounds using the functions found in the section on 2D Primitives. The indices of the textures can be different at different moments, and as a result models do not contain any texture information. This means that only when you draw a model do you provide the texture, so you can only use one texture in a model. If you need more textures you must either combine them in one (and carefully deal with the texture coordinates) or you must use multiple models. The advantage of this is that you can draw the same model easily with different textures.

For creating, loading, saving, and drawing models, the following functions exist:

  1. d3d_model_create
  2. d3d_model_destroy
  3. d3d_model_clear
  4. d3d_model_save
  5. d3d_model_load
  6. d3d_model_draw

For each primitive function there is an equivalent to add it to a model. The functions have the same arguments as the 2D primitive functions, or the 3D normal equivalents, except that each has as a first argument the index of the model, and no texture information is provided.

  1. d3d_model_primitive_begin
  2. d3d_model_vertex
  3. d3d_model_vertex_colour
  4. d3d_model_vertex_texture
  5. d3d_model_vertex_texture_colour
  6. d3d_model_vertex_normal
  7. d3d_model_vertex_normal_colour
  8. d3d_model_vertex_normal_texture
  9. d3d_model_vertex_normal_texture_colour
  10. d3d_model_primitive_end

Besides primitives you can also add basic shapes to the models. Again the functions look almost the same as the drawing functions found in the 3D drawing section, but with a model index and without texture information:

  1. d3d_model_block
  2. d3d_model_cylinder
  3. d3d_model_cone
  4. d3d_model_ellipsoid
  5. d3d_model_wall
  6. d3d_model_floor

Back: Working With 3D

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_block

Adds a block shape to the model.

Syntax:

d3d_model_block(ind, x1, y1, z1, x2, y2, z2, hrepeat, vrepeat)

Argument | Description
ind | The model index to add the block to.
x1 | The initial x coordinate of the block.
y1 | The initial y coordinate of the block.
z1 | The initial z coordinate of the block.
x2 | The opposite x coordinate of the block.
y2 | The opposite y coordinate of the block.
z2 | The opposite z coordinate of the block.
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.

Returns: N/A

Description

This function will add a block of the specified size to the chosen model. Please note that the x1, y1 and z1 parameters should be smaller than the x2, y2 and z2 to get the correct shape. There may be occasions where you want the box to be inverted though (for example if you want the camera to be inside the block) in which case swapping the two sets of coordinates will achieve this.

Example:

model[0] = d3d_model_create();
d3d_model_block(model[0], -10, -10, -10, 10, 10, 50, 1, 1);

The above code creates a model and adds a block to it.

Back: 3D Models
Next: d3d_model_cylinder

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_clear

Clears the model with the given index, removing all its primitives.

Syntax:

d3d_model_clear(ind)

Argument | Description
ind | The index of the model to be cleared.

Returns: N/A

Description

With this function you can clear all the primitives that have been added to a model. In this way you can keep the same model index, while changing the actual design of the model.

Example:

d3d_model_clear(model[2])

Clears the model indexed in the variable "model[2]", thus removing all its primitives

Back: 3D Models
Next: d3d_model_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_cone

Adds a cone shape to the model.

Syntax:

d3d_model_cone(ind, x1, y1, z1, x2, y2, z2, hrepeat, vrepeat, closed, steps)

Argument | Description
ind | The model index to add the cone to.
x1 | The model index to add the cone to.
y1 | The initial y coordinate of the cone.
z1 | The initial z coordinate of the cone.
x2 | The opposite x coordinate of the cone.
y2 | The opposite y coordinate of the cone.
z2 | The opposite z coordinate of the cone.
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.
closed | Sets whether to close (true) the bottom of the cone or not (false).
steps | How many steps are used to make the cone "round" (typically 24)

Returns: N/A

Description

This function will add a cone of the specified size to the chosen model.

Example:

model[0] = d3d_model_create();
d3d_model_cone(model[0], -10, -10, -10, 10, 10, 50, 1, 1, true, 24);

The above code creates a model and adds a cone to it.

Back: 3D Models
Next: d3d_model_ellipsoid

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_create

Creates a new model and returns its index.

Syntax:

d3d_model_create()

Returns: real

Description

This function must be called before you can define a new model, and it returns the index of that model which must be stored in a variable and referenced in all further functions that you wish to use with that model. As with most created resources, when you no longer need the model you should remove it from memory by using the d3d_model_destroy function or else you will have a memory leak that will slow down and eventually crash your game.

Example:

model[2] = d3d_model_create();
d3d_model_primitive_begin(model[2], pr_trianglestrip);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_primitive_end(model[2]);

The above code will define a tetrahedron and add it to the model indexed by the variable "model[2]".

Back: 3D Models
Next: d3d_model_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_cylinder

Adds a cylinder shape to the model.

Syntax:

d3d_model_cylinder(ind, x1, y1, z1, x2, y2, z2, hrepeat, vrepeat, closed, steps)

Argument | Description
ind | The model index to add the cylinder to.
x1 | The model index to add the cylinder to.
y1 | The initial y coordinate of the cylinder.
z1 | The initial z coordinate of the cylinder.
x2 | The opposite x coordinate of the cylinder.
y2 | The opposite y coordinate of the cylinder.
z2 | The opposite z coordinate of the cylinder.
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.
closed | Sets whether to close (true) the bottom and top of the cylinder or not (false).
steps | How many steps are used to make the cylinder "round" (typically 24)

Returns: N/A

Description

This function will add a cylinder of the specified size to the chosen model.

Example:

model[0] = d3d_model_create();
d3d_model_cylinder(model[0], -10, -10, -10, 10, 10, 50, 1, 1, true, 24);

The above code creates a model and adds a cylinder to it.

Back: 3D Models
Next: d3d_model_cone

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_destroy

Destroys the model with the given index, freeing its memory.

Syntax:

d3d_model_destroy(ind)

Argument | Description
ind | The index of the model to be destroyed.

Returns: N/A

Description

This function must be called when you no longer need the specified model to remove it from memory. If you fail to remove models when they are no longer needed, or if you use the same variable to index a new model without destroying that which was previously indexed, you may run into problems with slow down and the eventual crashing of your game.

Example:

d3d_model_destroy(model[2])

The above code will remove the model indexed by the variable "model[2]"from memory.

Back: 3D Models
Next: d3d_model_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_draw

Draws the model at position (x, y, z).

Syntax:

d3d_model_draw(ind, x, y, z, texid)

Argument | Description
ind | The index of the model to be drawn.
x | The x position to draw the model.
y | The y position to draw the model.
z | The z position to draw the model.
texid | The texture to use for drawing the model (use -1 to use no texture).

Returns: N/A

Description

This function draws the model at position (x, y, z) in the room. The texid is the texture that must be used, unless you have specified a value of -1 which means no texture, and this id can be gotten from the functions sprite_get_texture and background_get_texture. If you want to rotate or scale the model you can use the transformation routines.

Example:

d3d_model_draw(model[2], 0, -100, 0, sprite_get_texture(spr_Wall))

Draws the model with a texture at the given position.

Back: 3D Models
Next: d3d_model_primitive_begin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_ellipsoid

Adds an ellipsoid shape to the model.

Syntax:

d3d_model_ellipsoid(ind, x1, y1, z1, x2, y2, z2, hrepeat, vrepeat, steps)

Argument | Description
ind | The model index to add the ellipsoid to.
x1 | The initial x coordinate of the ellipsoid.
y1 | The initial y coordinate of the ellipsoid.
z1 | The initial z coordinate of the ellipsoid.
x2 | The opposite x coordinate of the ellipsoid.
y2 | The opposite y coordinate of the ellipsoid.
z2 | The opposite z coordinate of the ellipsoid.
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.
steps | How many steps are used to make the ellipsoid "round" (typically 24)

Returns: N/A

Description

This function will add an ellipsoid of the specified size to the chosen model.

Example:

model[0] = d3d_model_create();
d3d_model_ellipsoid(model[0], -10, -10, -10, 10, 10, 50, 1, 1, 24);

The above code creates a model and adds an ellipsoid to it.

Back: 3D Models
Next: d3d_model_wall

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_floor

Adds a floor shape to the model.

Syntax:

d3d_model_floor(ind, x1, y1, z1, x2, y2, z2, hrepeat, vrepeat)

Argument | Description
ind | The model index to add the floor to.
x1 | The initial x coordinate of the floor.
y1 | The initial y coordinate of the floor.
z1 | The initial z coordinate of the floor.
x2 | The opposite x coordinate of the floor.
y2 | The opposite y coordinate of the floor.
z2 | The opposite z coordinate of the floor.
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.

Returns: N/A

Description

This function will add a floor of the specified size to the chosen model.

Example:

model[1] = d3d_model_create();
d3d_model_floor(model[1], 0, 0, 0, 500, 500, 0, 10, 10);

The above code creates a model and adds a floor to it.

Back: 3D Models

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_load

Loads the model from the indicated file name.

Syntax:

d3d_model_load(ind, fname)

Argument | Description
ind | The index of the model to be loaded.
fname | The name of the file to load the model from.

Returns: N/A

Description

With this function you can load a saved model into the indexed model from a text file previously created with the d3d_model_save() function. If a model was previously defined for this index then that model information will be over-written by the loaded one.

Example:

model[2] = d3d_model_create();
d3d_model_load(model[2], "Terrain_Model.txt")

Loads the model stored previously in a text file into the model indexed in the variable "model[2]".

Back: 3D Models
Next: d3d_model_draw

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_primitive_begin

Begins the process of defining a primitive that is to be added to a model in 3D.

Syntax:

d3d_model_primitive_begin(ind, kind)

Argument | Description
ind | The index of the model to add the primitive to.
kind | The kind of primitive you are going to draw.

Returns: N/A

Description

This function must be called before you can define any primitives for a model. There are 6 types of primitives you can define with the following constants:

  • pr_pointlist
  • pr_linelist
  • pr_linestrip
  • pr_trianglelist
  • pr_trianglestrip
  • pr_trianglefan - (This is not available on the HTML5 target platform and may not work correctly on some devices for other platforms)

The following image illustrates basically how these should look and also the order in which you should define the vertexes:

Example:

model[2] = d3d_model_create();
d3d_model_primitive_begin(model[2], pr_trianglestrip);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_primitive_end(model[2]);

The above code will define a tetrahedron and add it to the model.

Back: 3D Models
Next: d3d_model_vertex

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_primitive_end

Ends the process of adding primitives to a model in 3D.

Syntax:

d3d_model_primitive_end(ind)

Argument | Description
ind | The index of the model to end the addition of primitives to.

Returns: N/A

Description

This function must be called when you have finished adding primitives to a previously defined 3D model.

Example:

model[2] = d3d_model_create();
d3d_model_primitive_begin(model[2], pr_trianglestrip);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_primitive_end(model[2]);

The above code will define a tetrahedron and add it to the model.

Back: 3D Drawing
Next: d3d_model_block

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_save

Saves the model to the indicated file name.

Syntax:

d3d_model_save(ind, fname)

Argument | Description
ind | The index of the model to be saved.
fname | The name of the file to save the model to.

Returns: N/A

Description

With this function you can save the indexed model to a text file, which can then be loaded in again using the d3d_model_load() function. You should note that you can actually use almost any format file you like use as long as the name is the same for loading.

Example:

d3d_model_save(model[2], "Terrain_Model.txt")

Saves the model indexed in the variable "model[2]" to a text file.

Back: 3D Models
Next: d3d_model_load

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_vertex

Add vertex (x,y,z) to the model.

Syntax:

d3d_model_vertex(ind, x, y, z)

Argument | Description
ind | The index of the model to add the primitive to.
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.

Returns: N/A

Description

This function defines the position of a vertex of a primitive which is part of a model. The final look of the primitive will depend on the primitive type chosen to draw and the order with which you add the vertexes to it. See d3d_model_primitive_begin for more information. To end and draw the primitive you must call d3d_model_primitive_end.

Example:

model[2] = d3d_model_create();
d3d_model_primitive_begin(model[2], pr_trianglestrip);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 150, 150, 200);
d3d_model_vertex(model[2], 100, 100, 0);
d3d_model_vertex(model[2], 100, 200, 0);
d3d_model_vertex(model[2], 200, 200, 0);
d3d_model_primitive_end();

The above code will define a tetrahedron and add it to the model.

Back: 3D Models
Next: d3d_model_vertex_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_vertex_colour

Add vertex (x,y,z) to the model with colour values.

Syntax:

d3d_model_vertex_colour(ind, x, y, z, col, alpha)

Argument | Description
ind | The index of the model to add the primitive to.
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
col | The colour to blend with vertex.
alpha | The alpha value of the vertex.

Returns: N/A

Description

This function defines the position of a vertex of a primitive which is part of a model, and blends the specified colour and alpha with it. The final look of the primitive will depend on the primitive type chosen to draw and the order with which you add the vertexes to it. See d3d_model_primitive_begin for more information. To end and draw the primitive you must call d3d_model_primitive_end.

Example:

model[2] = d3d_model_create();
d3d_model_primitive_begin(model[2], pr_trianglestrip);
d3d_model_vertex_colour(model[2], 100, 100, 0, c_red, 1);
d3d_model_vertex_colour(model[2], 100, 200, 0, c_red, 1);
d3d_model_vertex_colour(model[2], 150, 150, 200, blue, 1);
d3d_model_vertex_colour(model[2], 100, 200, 0, c_red, 1);
d3d_model_vertex_colour(model[2], 200, 200, 0, c_red, 1);
d3d_model_vertex_colour(model[2], 150, 150, 200, blue, 1);
d3d_model_vertex_colour(model[2], 200, 200, 0, c_red, 1);
d3d_model_vertex_colour(model[2], 100, 100, 0, c_red, 1);
d3d_model_vertex_colour(model[2], 150, 150, 200, blue, 1);
d3d_model_vertex_colour(model[2], 100, 100, 0, c_red, 1);
d3d_model_vertex_colour(model[2], 100, 200, 0, c_red, 1);
d3d_model_vertex_colour(model[2], 200, 200, 0, c_red, 1);
d3d_model_primitive_end(model[2]);

The above code will define a coloured tetrahedron and add it to the model.

Back: 3D Models
Next: d3d_model_vertex_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_vertex_normal

Defines a vertex for a primitive in 3D along with its corresponding normal.

Syntax:

d3d_model_vertex_normal(ind, x, y, z, nx, ny, nz)

Argument | Description
ind | The index of the model to add the primitive to.
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xn | The x component of the normal vector.
yn | The y component of the normal vector.
zn | The z component of the normal vector.

Returns: N/A

Description

This function defines the position of a primitive vertex for a model, and assigns a normal to that vertex for the purposes of lighting. The final look of the model will depend on the primitive type chosen to draw, the order with which you add the vertexes to it, and the normal that you define for it as well as the lighting. See d3d_model_primitive_begin for more information on primitives. To end and draw the primitive you must call d3d_model_primitive_end.

Example:

m = d3d_model_create();
d3d_model_primitive_begin(m, pr_trianglelist);
d3d_model_vertex_normal(m, -128, 0, -48, 0, 0.5, -0.5);
d3d_model_vertex_normal(m, -128, 96, 48, 0, 0.5, -0.5);
d3d_model_vertex_normal(m, 128, 0, -48, 0, 0.5, -0.5);
d3d_model_vertex_normal(m, 128, 0, -48, 0, 0.5, -0.5);
d3d_model_vertex_normal(m, -128, 96, 48, 0, 0.5, -0.5);
d3d_model_vertex_normal(m, 128, 96, 48, 0, 0.5, -0.5);
d3d_model_primitive_end(m);

The above code will add a sloped rectangle with the correct normal vectors for lighting to the selected model.

Back: 3D Drawing
Next: d3d_model_vertex_normal_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_vertex_normal_colour

Defines a primitive vertex for a model in 3D along with its corresponding normal, colour blending and alpha.

Syntax:

d3d_model_vertex_normal_colour(x, y, z, nx, ny, nz, col, alpha)

Argument | Description
ind | The index of the model to add the primitive to.
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xn | The x component of the normal vector.
yn | The y component of the normal vector.
zn | The z component of the normal vector.
col | The colour to blend with the vertex (c_white or -1 is no blend).
zn | The alpha of the vertex (0 - 1).

Returns: N/A

Description

This function defines the position of a primitive vertex for a model, assigns a normal to that vertex for the purposes of lighting, and permits you to set a blend colour and an alpha value too. The final look of the model will depend on the primitive type chosen to draw, the order with which you add the vertexes to it, and the normal that you define for it as well as the lighting. See d3d_model_primitive_begin for more information on primitives. To end and draw the primitive you must call d3d_model_primitive_end.

Example:

m = d3d_model_create();
d3d_model_primitive_begin(m, pr_trianglelist);
d3d_model_vertex_normal_colour(m, -128, 0, -48, 0, 0.5, -0.5, c_red, 0.5);
d3d_model_vertex_normal_colour(m, -128, 96, 48, 0, 0.5, -0.5, c_red, 0.5);
d3d_model_vertex_normal_colour(m, 128, 0, -48, 0, 0.5, -0.5, c_red, 0.5);
d3d_model_vertex_normal_colour(m, 128, 0, -48, 0, 0.5, -0.5, c_red, 0.5);
d3d_model_vertex_normal_colour(m, -128, 96, 48, 0, 0.5, -0.5, c_red, 0.5);
d3d_model_vertex_normal_colour(m, 128, 96, 48, 0, 0.5, -0.5, c_red, 0.5);
d3d_model_primitive_end(m);

The above code will add a sloped rectangle with the correct normal vectors for lighting, blended with the colour red and made semi-transparent with an alpha value of 0.5 to the selected model.

Back: 3D Drawing
Next: d3d_model_vertex_normal_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_vertex_normal_texture

Defines a primitive vertex for a textured model in 3D along with its corresponding normal.

Syntax:

d3d_model_vertex_normal_texture(ind, x, y, z, nx, ny, nz, xtex, ytex)

Argument | Description
ind | The index of the model to add the primitive to.
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xn | The x component of the normal vector.
yn | The y component of the normal vector.
zn | The z component of the normal vector.
xtex | Starting x coordinate within the texture (0 - 1).
zn | Starting y coordinate within the texture (0 - 1).

Returns: N/A

Description

This function defines the position of a primitive vertex for a model, assigns a normal to that vertex for the purposes of lighting and then assigns a texture. The final look of the model will depend on the primitive type chosen to draw, the order with which you add the vertexes to it, and the normal that you define for it as well as the lighting. See d3d_model_primitive_begin for more information on primitives. To end and draw the primitive you must call d3d_model_primitive_end.

Example:

m = d3d_model_create();
d3d_model_primitive_begin(m, pr_trianglelist);
d3d_model_vertex_normal_texture(m, -128, 0, -48, 0, 0.5, -0.5, 0, 0);
d3d_model_vertex_normal_texture(m, -128, 96, 48, 0, 0.5, -0.5, 1, 0);
d3d_model_vertex_normal_texture(m, 128, 0, -48, 0, 0.5, -0.5, 0, 0.5);
d3d_model_vertex_normal_texture(m, 128, 0, -48, 0, 0.5, -0.5, 1, 0.5);
d3d_model_vertex_normal_texture(m, -128, 96, 48, 0, 0.5, -0.5, 0, 1);
d3d_model_vertex_normal_texture(m, 128, 96, 48, 0, 0.5, -0.5, 1, 1);
d3d_model_primitive_end(m);

The above code will add a textured, sloped rectangle with the correct normal vectors for lighting to the selected model.

Back: 3D Drawing
Next: d3d_model_vertex_normal_texture_colour


d3d_model_vertex_normal_texture_colour

Defines a primitive vertex for a textured model in 3D along with its corresponding normal, colour blending and alpha.

Syntax:

d3d_model_vertex_normal_texture_colour(ind, x, y, z, nx, ny, nz, xtex, ytex, col, alpha)

Argument | Description
ind | The index of the model to add the primitive to.
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xn | The x component of the normal vector.
yn | The y component of the normal vector.
zn | The z component of the normal vector.
xtex | Starting x coordinate within the texture (0 - 1).
ytex | Starting y coordinate within the texture (0 - 1).
col | The colour to blend with the vertex (c_white or -1 is no blend).
alpha | The alpha of the vertex (0 - 1).

Returns: N/A

Description

This function defines the position of a primitive vertex for a model, assigns a normal to that vertex for the purposes of lighting and then assigns a texture as well as a blend colour and alpha transparency. The final look of the model will depend on the primitive type chosen to draw, the order with which you add the vertexes to it, and the normal that you define for it as well as the lighting. See d3d_model_primitive_begin for more information on primitives. To end and draw the primitive you must call d3d_model_primitive_end.

Example:

m = d3d_model_create();
d3d_model_primitive_begin(m, pr_trianglelist);
d3d_model_vertex_normal_texture_colour(-128, 0, -48, 0, 0.5, -0.5, 0, 0, c_lime, 0.5);
d3d_model_vertex_normal_texture_colour(-128, 96, 48, 0, 0.5, -0.5, 1, 0, c_lime, 0.5);
d3d_model_vertex_normal_texture_colour(128, 0, -48, 0, 0.5, -0.5, 0, 0.5, c_lime, 0.5);
d3d_model_vertex_normal_texture_colour(128, 0, -48, 0, 0.5, -0.5, 1, 0.5, c_lime, 0.5);
d3d_model_vertex_normal_texture_colour(-128, 96, 48, 0, 0.5, -0.5, 0, 1, c_lime, 0.5);
d3d_model_vertex_normal_texture_colour(128, 96, 48, 0, 0.5, -0.5, 1, 1, c_lime, 0.5);
d3d_model_primitive_end(m);

The above code will add a textured, sloped rectangle with the correct normal vectors for lighting, blended green and with a semi-transparent alpha to the selected model.

Back: 3D Drawing
Next: d3d_model_block

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_vertex_texture

Add vertex (x,y,z) to the model with texture values.

Syntax:

d3d_model_vertex_texture(ind, x, y, z, xtex, ytex)

Argument | Description
ind | The index of the model to add the primitive to.
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xtex | Starting x coordinate within the texture.
ytex | Starting y coordinate within the texture.

Returns: N/A

Description

This function defines the position of a textured vertex for a primitive in a model. The final look of the primitive will depend on the primitive type chosen to draw (See d3d_model_primitive_begin for more information), the order with which you add the vertexes to it and the position of the start point you set for the texture. To end and draw the primitive you must call d3d_model_primitive_end.

Example:

model = d3d_model_create();
d3d_model_primitive_begin(model, pr_trianglestrip);
d3d_model_vertex_texture(model, 0, 480, 0, 0, 0);
d3d_model_vertex_texture(model, 640, 480, 0, 1, 0);
d3d_model_vertex_texture(model, 640, 480, 1000, 1, 1);
d3d_model_vertex_texture(model, 0, 480, 1000, 0, 1);
d3d_model_primitive_end(model);

The above code will draw a 4 vertex triangle strip textured with the texture held in the "tex" variable.

Back: 3D Models
Next: d3d_model_vertex_texture_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_vertex_texture_colour

Add vertex (x,y,z) to the model with texture and colour values.

Syntax:

d3d_model_vertex_texture_colour(ind, x, y, z, xtex, ytex)

Argument | Description
ind | The index of the model to add the primitive to.
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
z | The z coordinate of the vertex.
xtex | Starting x coordinate within the texture.
ytex | Starting y coordinate within the texture.
col | The colour to blend with vertex.
alpha | The alpha value of the vertex.

Returns: N/A

Description

This function defines the position of a textured vertex for a primitive in a model, with the vertex blended with the specified colour and alpha values. The final look of the primitive will depend on the primitive type chosen to draw (See d3d_model_primitive_begin for more information), the order with which you add the vertexes to it and the position of the start point you set for the texture. To end and draw the primitive you must call d3d_model_primitive_end.

Example:

model = d3d_model_create();
d3d_model_primitive_begin(model, pr_trianglestrip);
d3d_model_vertex_texture_colour(model, 0, 480, 0, 0, 0, c_lime, 1);
d3d_model_vertex_texture_colour(model, 640, 480, 0, 1, 0, c_lime, 1);
d3d_model_vertex_texture_colour(model, 640, 480, 1000, 1, 1, c_lime, 1);
d3d_model_vertex_texture_colour(model, 0, 480, 1000, 0, 1, c_lime, 1);
d3d_model_primitive_end(model);

The above code will add a 4 vertex, textured triangle strip to the model, with the colour c_lime blended in and an alpha of 1.

Back: 3D Models
Next: d3d_model_vertex_normal

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_model_wall

Adds a wall shape to the model.

Syntax:

d3d_model_wall(ind, x1, y1, z1, x2, y2, z2, hrepeat, vrepeat)

Argument | Description
ind | The model index to add the wall to.
x1 | The initial x coordinate of the wall.
y1 | The initial y coordinate of the wall.
z1 | The initial z coordinate of the wall.
x2 | The opposite x coordinate of the wall.
y2 | The opposite y coordinate of the wall.
z2 | The opposite z coordinate of the wall.
hrepeat | Amount of horizontal repetitions for the texture.
vrepeat | Amount of vertical repetitions for the texture.

Returns: N/A

Description

This function will add a wall of the specified size to the chosen model.

Example:

model[1] = d3d_model_create();
d3d_model_wall(model[1], 0, 0, 200, 500, 500, 200, 10, 10);

The above code creates a model and adds a wall to it.

Back: 3D Models
Next: d3d_model_floor

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


3D Projections

This section deals with the 3D projection functions.

Often in 3D games you want to change how you look at the world. For example, in a first person shooter you probably want to have the camera look from a position a bit above the xy-plane along the xy-plane, which, in graphics terms, involves setting the correct projection. This projection should be set in an instance that is created before all other instances (you can set this from the Instance Order window in the Room Editor), and it should be at a very low depth so that is drawn before all other instances in your room, otherwise you will get issues when drawing. NOTE When GameMaker starts drawing a room it will set the view point back to the default position, so the first thing you must do when drawing the scene is set is to the projection you want. This must be done in the draw event of an instance!

To change the way you look at the 3D world the following functions exist:

  1. d3d_set_projection
  2. d3d_set_projection_ext
  3. d3d_set_projection_ortho
  4. d3d_set_projection_perspective

Back: Working With 3D
Next: 3D Transformations

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_projection

This function can be used to modify the view matrix.

Syntax:

d3d_set_projection(xfrom, yfrom, zfrom, xto, yto, zto, xup, yup, zup)

Argument | Description
xfrom | The x coordinate of the position to look from.
yfrom | The y coordinate of the position to look from.
zfrom | The z coordinate of the position to look from.
xto | The x coordinate of the position to look to.
yto | The x coordinate of the position to look to.
zto | The x coordinate of the position to look to.
xup | The x coordinate of the "up" vector.
yup | The y coordinate of the "up" vector.
zup | The z coordinate of the "up" vector.

Returns: N/A

Description

Although this function is called d3d_set_projection it is really used to modify the view matrix, not the projection matrix. As such, you should first initialize the projection matrix using the other projection function d3d_set_projection_ext, then use this function to move the view (camera) around within the projection.

To set the view you first need to define the position you look from, which is indicated by the parameters (xfrom, yfrom, zfrom). Next you must specify the direction you look in and this is done by giving a second point to look towards with the arguments (xto, yto, zto). Finally, you can still rotate the camera around the line from the viewpoint to the looking point, and to specify this we must give an "up" vector, that is, the direction that is upwards in the camera. This is given by the last three arguments (xup, yup, zup).

Example:

d3d_set_projection(100, 100, 10, 200, 100, 10, 0, 0, 1);

The above code creates a typical first person shooter view.

Back: 3D Projections
Next: d3d_set_projection_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_projection_ext

This function can be used to set very precise 3D projections.

Syntax:

d3d_set_projection_ext(xfrom, yfrom, zfrom, xto, yto, zto, xup, yup, zup, angle, aspect, znear, zfar)

Argument | Description
xfrom | The x coordinate of the position to look from.
yfrom | The y coordinate of the position to look from.
zfrom | The z coordinate of the position to look from.
xto | The x coordinate of the position to look to.
yto | The x coordinate of the position to look to.
zto | The x coordinate of the position to look to.
xup | The x coordinate of the "up" vector.
yup | The y coordinate of the "up" vector.
zup | The z coordinate of the "up" vector.
angle | The field of view angle.
aspect | Aspect ratio between horizontal and vertical size of the view.
znear | The near clipping plane.
zfar | The far clipping plane.

Returns: N/A

Description

This function sets up the initial projection matrix as well as the view matrix for a 3D game, where (basically) the view matrix controls where the camera is and the projection matrix controls how the world is projected onto a 2D screen. If you just wish to move the view (camera) around, you should be using the function d3d_set_projection.

To set the view into the world you first need the position you look from , which is indicated by the parameters (xfrom, yfrom, zfrom). Next you must specify the direction you look in and this is done by giving a second point to look towards with the arguments (xto, yto, zto). Finally, you can still rotate the camera around the line from the viewpoint to the looking point, and to specify this we must give an "up" vector, that is, the direction that is upwards in the camera and this is given by the three arguments (xup, yup, zup).

Once you specify the camera position, point to look at, and up vector, you can still change how wide the lens of the camera is (called the field of view) by setting the (angle) argument to a chosen value, with a reasonable value being somewhere between 40 and 45 degrees. Next you can specify the aspect ratio between the horizontal and vertical projection. Now, normally you want to use the same as the aspect ratio of the room or view, e.g. 640/480, but in special circumstances you may wish to change this. Finally you can indicate the clipping planes. Objects that are closer than znear to the camera are not drawn, and similarly, objects that are further than zfar will not be drawn. It can be important to set these parameters to reasonable values because they also influence the precision of the z-comparisons and if you make the range too large then the precision gets worse. The default values are 1 and 32000, and znear must be larger than 0.

Example:

with (obj_camera)
{
var xx, yy, r;
xx = x + cos(direction * pi / 180);
yy = y - sin(direction * pi / 180);
r = view_wview[0] / view_hview[0];
d3d_set_projection_ext(x, y, 10, xx, yy, 10, 0, 0, 1, 60, r, 1, 16000);
}

The above code creates a typical first person shooter projection, rotated using the current camera object direction, and with a custom field of view of 60 degrees and a low far clipping distance.

Back: 3D Projections
Next: d3d_set_projection_ortho

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_projection_ortho

This function can be used to set an orthographic projection.

Syntax:

d3d_set_projection_ortho(x, y, w, h, angle)

Argument | Description
x | The x coordinate in the room to look from.
y | The y coordinate in the room to look from.
w | The width of the projection.
h | The height of the projection.
angle | The rotation angle of the projection.

Returns: N/A

Description

Sometimes you temporarily need a normal orthographic projection (this is what is used when there is no 3D active), or you want to return to the default perspective projection, which is what this function is for. It is typically used to draw an overlay, for example, to show the score or other aspects as this gives a "flat" view of the elements drawn (ie: no perspective). See the image below to get an idea of the difference between orthographic and perspective views.

Note: You may also need to temporarily switch off hidden surface removal if you want the information to be drawn regardless of the current depth value.

Example:

draw_set_colour(c_black);
d3d_set_projection_ortho(0, 0, room_width, room_height, 0);
d3d_set_hidden(false);
draw_text(10, 10, 'Score: ' + string(score));
d3d_set_hidden(true);

Back: 3D Projections
Next: d3d_set_projection_perspective

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_projection_perspective

This function can be used to set a perspective projection.

Syntax:

d3d_set_projection_perspective(x, y, w, h, angle)

Argument | Description
x | The x coordinate in the room to look from.
y | The y coordinate in the room to look from.
w | The width of the projection.
h | The height of the projection.
angle | The rotation angle of the projection.

Returns: N/A

Description

You can use this type of projection to create a "top down" view of your room, where all the elements are given perspective and depth (ie: the higher the depth, the smaller and further away they appear from the player). See the image below to get an idea of the difference between orthographic and perspective views.

Example:

d3d_set_projection_perspective(0, 0, room_width, room_height, 0);

The above code sets up a basic 3D perspective projection.

Back: 3D Projections
Next: d3d_set_projection

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


3D Setup

This section details all the functions used to initialize 3D drawing.

If you want to use 3D mode you first need to set GameMaker: Studio to draw in 3D mode (you can later switch back to 2D mode if you want) as well as set up certain details about how you want things in the 3D environment to be rendered.

The following functions exist for setting up the 3D environment:

  1. d3d_start
  2. d3d_end
  3. d3d_set_hidden
  4. d3d_set_perspective
  5. d3d_set_depth
  6. d3d_set_culling
  7. d3d_set_zwriteenable

Back: Working With 3D
Next: 3D Drawing

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_end

Tells GameMaker: Studio that 3D mode is to be switched off.

Syntax:

d3d_end()

Returns: N/A

Description

This function should be called whenever you wish to tell GameMaker: Studio to stop drawing in 3D mode, and resume normal drawing.

Example:

d3d_end();

This code has been called in a destroy event to end all 3D drawing, for example, after the main game has finished and you wish to return the player to a 2D menu screen.

Back: 3D Setup
Next: d3d_set_hidden

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_culling

Sets whether back face culling should be enabled or disabled.

Syntax:

d3d_set_culling(enable)

Argument | Description
enable | Switches on (true) or off (false) back-face culling

Returns: N/A

Description

A 3D triangle has a front and a back side. The front side is said to be the side where the vertices are defined in counter-clockwise order. Now, normally both sides are drawn, but if you make a closed shape then this is a waste of processing power because the back side of the triangle can never be seen. It's in these cases that you can switch on backface culling. This saves about half the amount of drawing time but it means you have the task of defining your polygons in the correct way to prevent issues.

Example:

d3d_set_culling(true);
d3d_primitive_begin(pr_trianglelist);
d3d_vertex(100, 100, 0);
d3d_vertex(100, 200, 0);
d3d_vertex(150, 150, 200);
d3d_vertex(100, 200, 0);
d3d_vertex(200, 200, 0);
d3d_vertex(150, 150, 200);
d3d_vertex(200, 200, 0);
d3d_vertex(100, 100, 0);
d3d_vertex(150, 150, 200);
d3d_vertex(100, 100, 0);
d3d_vertex(100, 200, 0);
d3d_vertex(200, 200, 0);
d3d_primitive_end();

The above code will draw a pyramid with the back faces (interior faces) being culled (not drawn).

Back: 3D Setup
Next: d3d_set_zwriteenable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_depth

Sets the depth used for drawing.

Syntax:

d3d_set_depth(depth)

Argument | Description
depth | The new depth used for drawing

Returns: N/A

Description

Once 3D mode has been switched on you can use GameMaker: Studio as you are used to it, with the exception of certain things (see Working With 3D), only now objects will appear in different sizes based on their depth setting. However, if you draw a number of things in a single piece of code you might want to change the depth value between the primitives you draw, and this can be achieved using this function.

Example:

var tex;
tex = background_get_texture(back);
d3d_primitive_begin_texture(pr_trianglestrip, tex);
d3d_vertex_texture(0, 48, 0, 0, 0);
d3d_vertex_texture(64, 48,0,1,0);
d3d_vertex_texture(64, 48, 1000, 1, 1);
d3d_vertex_texture(0, 48, 1000, 0, 1);
d3d_primitive_end();
d3d_set_depth(500);
d3d_primitive_begin_texture(pr_trianglestrip, tex);
d3d_vertex_texture(80, 220, 0, 0, 0);
d3d_vertex_texture(140, 220,0,1,0);
d3d_vertex_texture(140, 220, 1000, 1, 1);
d3d_vertex_texture(80, 220, 1000, 0, 1);
d3d_primitive_end();

The above code will draw two textured primitives with a change of draw depth between them.

Back: 3D Setup
Next: d3d_set_culling

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_hidden

This function is used to enable or disable depth testing.

Syntax:

d3d_set_hidden(enable)

Argument | Description
enable | Enables (true) or disables (false) depth testing

Returns: N/A

Description

When enabled this function performs depth tests on all surfaces and removes those that are hidden in the current projection.

Example:

d3d_set_hidden(true);

The above code switches on hidden surface removal.

Back: 3D Setup
Next: d3d_set_perspective

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_perspective

Switches on or off perspective projection.

Syntax:

d3d_set_perspective(enable)

Argument | Description
enable | Enables (true) or disables (false) perspective projection

Returns: N/A

Description

This turns on (or off) perspective projection. With a perspective projection instances that have a greater depth will appear smaller, so when the depth is 0 it is equal to the original size and the viewpoint for the camera is placed at a distance above the room. This default distance is equal to the width of the room as that gives a reasonable starting projection, and only instances in front of the camera are drawn. Don't use instances with a depth smaller than 0 (or at least not smaller than -w where w is the width of the room or the view).

Example:

d3d_set_perspective(true)

The above code switches on perspective projection.

Back: 3D Setup
Next: d3d_set_depth

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_set_zwriteenable

Enables or disables the z-buffer.

Syntax:

d3d_set_zwriteenable(enable)

Argument | Description
enable | Switches on (true) or off (false) the z-buffer.

Returns: N/A

Description

This function can be used to toggle on (true) and off (false) depth ordering using the z-buffer in 3D mode. The default value is that z-buffering is enabled.

When drawing in 3D, you normally want things to be drawn with depth along the z axis, so that an object "close" to the player is drawn over an object that is "further" away. When an object is rendered, the depth of a generated pixel (its z coordinate) is stored in the z-buffer, then, if another object of the scene must be rendered in the same pixel, the two depths are compared the one closer to the observer is then saved to the z-buffer, replacing the old one. However, this is not always what you wish to happen and there are moments when you may want something to be drawn over everything else, no matter what its z value is. In those cases you can use this function to switch off writing to the z-buffer and so force whatever is being drawn to be drawn over everything else.

Example:

d3d_set_zwriteenable(false);

The above code will switch off the z-buffer for all further drawing.

Back: 3D Setup
Next: d3d_start

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_start

Tells GameMaker: Studio that all further drawing is to be done in 3D mode.

Syntax:

d3d_start()

Returns: Real

Description

With this function you can tell GameMaker: Studio that all further drawing should be done in 3D mode. This function can be called in any event, but will affect all drawing done after, so if your game is not completely done in 3D you may need to switch it off using d3d_end to draw certain parts (and then use this function again to switch 3D mode back on).

Starting 3D mode will result in the following changes:

  • First of all depth testing (also known as Z Buffering) is switched on (using a 24-bit z-buffer). This means that for each pixel on the screen only the drawing with the smallest z-value (= depth value) is drawn. If instances have the same depth then you will get what is known as Z-fighting. This occurs as the 2 instances attempt to draw at the same level, and inaccuracies in the rendering due to very close Z value cause ugly effects. To avoid this, try and make sure instances that might overlap do not have the same depth value!

  • Secondly, the normal orthographic projection is replaced by a perspective one. This means the following. Normally the size of instances on the screen is independent on its depth. With a perspective projection instances that have a greater depth will appear smaller. When the depth is 0 it is equal to the old size (unless you change the projection). The viewpoint for the camera is placed at a distance above the room. (This distance is equal to the width of the room; that gives a reasonable default projection.) Only instances in front of the camera are drawn. So don't use instances with a depth smaller than 0 (or at least not smaller than -w where w is the width of the room or the view).

  • Thirdly, the vertical y-coordinate is reversed. While normally the (0,0) position is at the top-left of the view, in 3D mode the (0,0) position is at the bottom-left position, as is normal for 3-dimensional views.

Example:

d3d_start();

This code has been placed in the create event of an instance to tell GameMaker: Studio that all further drawing should be done in 3D mode.

Back: 3D Setup
Next: d3d_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


3D Transformations

This section deals with the 3D transformation functions.

Transformation allow you to change the place where things are drawn in the world. For example, the function to draw blocks can only draw axis-parallel blocks, but by first setting a rotation transformation you can create rotated blocks. Also sprites are always drawn parallel to the xy-plane, but by setting a transformation you can change this. There are two types of functions, functions that set the transformation and functions that add transformations, and they are listed below:

  1. d3d_transform_set_identity
  2. d3d_transform_set_translation
  3. d3d_transform_set_scaling
  4. d3d_transform_set_rotation_x
  5. d3d_transform_set_rotation_y
  6. d3d_transform_set_rotation_z
  7. d3d_transform_set_rotation_axis
  8. d3d_transform_add_translation
  9. d3d_transform_add_scaling
  10. d3d_transform_add_rotation_x
  11. d3d_transform_add_rotation_y
  12. d3d_transform_add_rotation_z
  13. d3d_transform_add_rotation_axis

Sometimes you temporarily want to save the current transformation, for example to add an additional transformation and then restore the old one (this often happens when drawing hierarchical models). To this end you can push the current transformation on a stack and later pop it from the stack to make it the current transformation again. The following functions exist for this:

  1. d3d_transform_stack_clear
  2. d3d_transform_stack_empty
  3. d3d_transform_stack_push
  4. d3d_transform_stack_pop
  5. d3d_transform_stack_top
  6. d3d_transform_stack_discard

Finally, you have a function that can be used to get the x, y, and z values for the transformed vertex:

  1. d3d_transform_vertex

Matrix Functions

An alternative way to create transforms (and for multiple transforms this is far more efficient) is to use the matrix functions. These permit you to get the values of different matrices (view, projection and world), as well as create your own then multiply them or change their values and apply them again. The available matrix functions are listed below:

  1. matrix_get
  2. matrix_set
  3. matrix_build
  4. matrix_multiply
  5. is_matrix

Back: Working With 3D
Next: 3D Lighting and Fog

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_add_rotation_axis

Sets the transformation to a rotation around the axis indicated by the vector with the indicated amount.

Syntax:

d3d_transform_add_rotation_axis(xa, ya, za, angle)

Argument | Description
xa | The x component of the transform vector.
ya | The y component of the transform vector.
za | The z component of the transform vector.
angle | The angle to rotate the transform through the vector.

Returns: N/A

Description

With this function you can get GameMaker: Studio to add the defined angle rotation about the chosen vector to any previously set transforms.

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_add_rotation_axis(0, 1, 1, 90);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to rotate the object through the vector formed by (0,1,1) by an amount of 90 degrees.

Back: 3D Drawing
Next: d3d_transform_stack_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_add_rotation_x

Adds a rotation around the x-axis with the indicated amount.

Syntax:

d3d_transform_add_rotation_x(angle)

Argument | Description
angle | The angle to rotate around the x-axis.

Returns: N/A

Description

This function will rotate the object around the x-axis by the specified amount (in degrees), relative to any previously performed transforms.

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_add_rotation_x(90);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to rotate the block 90 degrees along the x-axis (in addition to any previous transforms) before drawing it.

Back: 3D Drawing
Next: d3d_transform_add_rotation_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_add_rotation_y

Adds a rotation around the y-axis with the indicated amount.

Syntax:

d3d_transform_add_rotation_y(angle)

Argument | Description
angle | The angle to rotate around the y-axis.

Returns: N/A

Description

This function will rotate the object around the y-axis by the specified amount (in degrees), relative to any previously performed transforms.

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_add_rotation_y(90);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to rotate the block 90 degrees along the y-axis (in addition to any previous transforms) before drawing it.

Back: 3D Drawing
Next: d3d_transform_add_rotation_z

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_add_rotation_z

Adds a rotation around the z-axis with the indicated amount.

Syntax:

d3d_transform_add_rotation_z(angle)

Argument | Description
angle | The angle to rotate around the z-axis.

Returns: N/A

Description

This function will rotate the object around the z-axis by the specified amount (in degrees), relative to any previously performed transforms.

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_add_rotation_z(90);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to rotate the block 90 degrees along the z-axis (in addition to any previous transforms) before drawing it.

Back: 3D Drawing
Next: d3d_transform_add_rotation_axis

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_add_scaling

Sets the transformation to a scaling with the indicated amounts.

Syntax:

d3d_transform_add_scaling(xs, ys, zs)

Argument | Description
xs | The x scale amount.
ys | The y scale amount.
zs | The z scale amount.

Returns: N/A

Description

This transform can be used to scale the object currently being drawn, with the amount being scaled relative to any previous transforms rather than absolute (as would be the case with d3d_transform_set_scaling).

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_add_scaling(2, 2, 2);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to draw the block and then scale it twice as much over any previous transforms.

Back: 3D Drawing
Next: d3d_transform_add_rotation_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_add_translation

Add a translation over the indicated vector to the transform.

Syntax:

d3d_transform_add_translation(xt, yt, zt)

Argument | Description
xt | The x component of the transform vector.
yt | The y component of the transform vector.
zt | The z component of the transform vector.

Returns: N/A

Description

As the name implies, this does not set an absolute translation value to the object, but rather adds the amount of the vector onto the current transform (unlike d3d_transform_set_translation which sets an absolute position).

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_add_translation(0, 200, 400);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to first go to (0,0,0) then add the translate vector (0,200,400) to the object in the game world, and then draw the block.

Back: 3D Drawing
Next: d3d_transform_add_scaling

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_set_identity

Sets the transformation to the identity (no transformation).

Syntax:

d3d_transform_set_identity()

Returns: N/A

Description

This will set the origin of the 3D world to location 0,0,0 (which is the center of the world). This means that you can define an object at this point and then perform transforms on it to change its angle, scale, or position without worrying about the actual room coordinates. It is important to end transformation afterwards, using the same command.

Example:

d3d_transform_set_translation(100, 100, 10);
draw_sprite(spr, 0 ,0 ,0);
d3d_transform_set_identity();

The above code will draw a sprite translated to the position (100, 100, 0).

Back: 3D Drawing
Next: d3d_transform_set_translation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_set_rotation_axis

Sets the transformation to a rotation around the axis indicated by the vector with the indicated amount.

Syntax:

d3d_transform_set_rotation_axis(xa, ya, za, angle)

Argument | Description
xa | The x component of the transform vector.
ya | The y component of the transform vector.
za | The z component of the transform vector.
angle | The angle to rotate the transform through the vector.

Returns: N/A

Description

With this function you can define a vector and then have GameMaker: Studio transform the angle of the object by the amount specified through that vector.

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_set_rotation_axis(0, 1, 1, 90);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to rotate the object through the vector formed by (0,1,1) by an amount of 90�.

Back: 3D Drawing
Next: d3d_transform_add_translation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_set_rotation_x

Sets the transformation to a rotation around the x-axis with the indicated amount.

Syntax:

d3d_transform_set_rotation_x(angle)

Argument | Description
angle | The angle to rotate around the x-axis.

Returns: N/A

Description

This function will rotate the object around the x-axis by the specified amount (in degrees).

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_set_rotation_x(90);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to rotate the block 90 degrees along the x-axis before drawing it.

Back: 3D Drawing
Next: d3d_transform_set_rotation_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_set_rotation_y

Sets the transformation to a rotation around the y-axis with the indicated amount.

Syntax:

d3d_transform_set_rotation_y(angle)

Argument | Description
angle | The angle to rotate around the y-axis.

Returns: N/A

Description

This function will rotate the object around the y-axis by the specified amount (in degrees).

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_set_rotation_y(90);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to rotate the block 90 degrees along the y-axis before drawing it.

Back: 3D Drawing
Next: d3d_transform_set_rotation_z

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_set_rotation_z

Sets the transformation to a rotation around the z-axis with the indicated amount.

Syntax:

d3d_transform_set_rotation_z(angle)

Argument | Description
angle | The angle to rotate around the z-axis.

Returns: N/A

Description

This function will rotate the object around the z-axis by the specified amount (in degrees).

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_set_rotation_z(90);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to rotate the block 90 degrees along the z-axis before drawing it.

Back: 3D Drawing
Next: d3d_transform_set_rotation_axis

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_set_scaling

Sets the transformation to a scaling with the indicated amounts.

Syntax:

d3d_transform_set_scaling(xs, ys, zs)

Argument | Description
xs | The x scale amount.
ys | The y scale amount.
zs | The z scale amount.

Returns: N/A

Description

A scaling transform will squash and expand the vertices of an object about the various axis. For example, a transform of d3d_transform_set_scaling( 1, 2, 0) will keep the same x coordinates, double the y coordinates and will all have the z coordinate of 0. This function sets an absolute scale and will wipe any previous transforms (unlike d3d_transform_add_scaling which will add to previous transforms).

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_set_scaling(2, 2, 2);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to draw the block scaled to twice the size.

Back: 3D Drawing
Next: d3d_transform_set_rotation_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_set_translation

Sets the transformation to a translation over the indicated vector.

Syntax:

d3d_transform_set_translation(xt, yt, zt)

Argument | Description
xt | The x component of the transform vector.
yt | The y component of the transform vector.
zt | The z component of the transform vector.

Returns: N/A

Description

A translation transform will take the vertices used for drawing and simply set them to be drawn at whatever coordinates you want to them. The effect you get will effectively look like you took the object and simply moved it. The fundamental difference between this transform and d3d_transform_add_translation is that this will clear all transforms that have been previously done.

Example:

var tex = background_get_texture(bck_Wall);
d3d_transform_set_identity();
d3d_transform_set_translation(0, 200, 400);
d3d_draw_block(-50, -50, -50, 50, 50, 50, tex, 100, 100);
d3d_transform_set_identity();

The above code tells GameMaker: Studio to first go to (0,0,0) then translate to (0,200,400) in the game world, and then draw a block.

Back: 3D Drawing
Next: d3d_transform_set_scaling

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_stack_clear

Clears the stack of transformations.

Syntax:

d3d_transform_stack_clear()

Returns: N/A

Description

This will clear the stack of all transforms. In GameMaker: Studio there is only one, global, transform stack and it is used by all instances for all transforms. This means you should be careful to clear the stack when finished for each instance with this command otherwise you will get a stack overflow error.

Example:

d3d_transform_stack_clear();

The above code will clear the transformation stack.

Back: 3D Drawing
Next: d3d_transform_stack_empty

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_stack_discard

Removes the top transformation from the stack.

Syntax:

d3d_transform_stack_discard()

Returns: Boolean

Description

Removes the top transformation from the stack but does not make it the current one. Returns whether there was a transformation on the stack.

Example:

d3d_transform_stack_top();
d3d_transform_add_rotation_axis(1, 0, 0, 5);
d3d_transform_stack_discard();
d3d_transform_set_identity();

The above code will apply the transformation from the top of the stack, add a rotation over the x axis to it, and then discard the transform from the stack at the end.

Back: 3D Transformations
Next: d3d_transform_vertex

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_stack_empty

Returns whether the transformation stack is empty.

Syntax:

d3d_transform_stack_empty()

Returns: Boolean

Description

You can use this function to check and see if the transformation stack is empty of transforms or not.

Example:

if !d3d_transform_stack_empty() d3d_transform_stack_clear();

The above code will check the transformation stack and if it is not empty it clears it.

Back: 3D Drawing
Next: d3d_transform_stack_push

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_stack_pop

Pops the top transformation from the stack and makes it the current one.

Syntax:

d3d_transform_stack_pop()

Returns: Boolean

Description

Pops the top transformation from the stack and makes it the current one. Returns whether there was a transformation on the stack.

Example:

d3d_transform_stack_pop();
d3d_transform_add_rotation_axis(1, 0, 0, 5);
d3d_transform_stack_push();
d3d_transform_set_identity();

The above code will pop the previous transformation from the stack, then add a rotation over the x axis, before finally pushing the final transform back onto the stack again.

Back: 3D Drawing
Next: d3d_transform_stack_top

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_stack_push

Pushes the current transformation onto the stack.

Syntax:

d3d_transform_stack_push()

Returns: Boolean

Description

Pushes the current transformation onto the stack, and returns whether there was room on the stack (true) to push it there or not (false).

Note: If you forget to "pop" transformations you will at some moment run out of room on the stack.

Example:

d3d_transform_stack_pop();
d3d_transform_add_rotation_axis(1, 0, 0, 5);
d3d_transform_stack_push();
d3d_transform_set_identity();

The above code will pop the previous transformation from the stack, then add a rotation over the x axis, before finally pushing the final transform back onto the stack again.

Back: 3D Drawing
Next: d3d_transform_stack_pop

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_stack_top

Makes the top transformation the current one.

Syntax:

d3d_transform_stack_top()

Returns: Boolean

Description

Makes the top transformation the current one, but does not remove it from the stack. Returns whether there was a transformation on the stack.

Example:

d3d_transform_stack_top();
d3d_transform_add_rotation_axis(1, 0, 0, 5);
d3d_transform_stack_discard();
d3d_transform_set_identity();

The above code will apply the transformation from the top of the stack, add a rotation over the x axis to it, and then discard the transform from the stack at the end.

Back: 3D Drawing
Next: d3d_transform_stack_discard

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


d3d_transform_vertex

Get the x, y and z values of a transformed vertex.

Syntax:

d3d_transform_vertex(x, y, z)

Argument | Description
x | The x component of the transform vertex.
y | The y component of the transform vertex.
z | The z component of the transform vertex.

Returns: Array

Description

This function returns an array of 3 values, with each one corresponding to the x, y, and z values of the transformed vertex with the current matrix.

Example:

a = d3d_transform_vertex(x, y, z);

The above code will get the "x", "y" and "z" values for the vertex using the current transform matrix, such that a[0] = x, a[1] = y, a[2] = z.

Back: 3D Transformations
Next: matrix_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


matrix_build

Build a 4x4 matrix from the given input values.

Syntax:

matrix_build(x, y, z, xrotation, yrotation, zrotation, xscale, yscale, zscale)

Argument | Description
x | The x component of the translation vector.
y | The y component of the translation vector.
z | The z component of the translation vector.
xrotation | The angle to rotate around the x-axis.
yrotation | The angle to rotate around the y-axis.
xzotation | The angle to rotate around the z-axis.
xscale | The x scale amount.
yscale | The y scale amount.
zscale | The z scale amount.

Returns: Array

Description

This function can be used to create your own custom matrix and will return an index value for this new matrix which should be stored in a variable for future reference and use. The matrix itself is created as 16 value 1D array where the first values are column 1, second 4 values are column2 etc... of a 4x4 matrix.

NOTE: When you build a new matrix in this way the order of operation is YXZ.

Example:

m_array = matrix_build(x, y, 0, 0, 90, 0, 1, 2, 1);

The above code will build a new matrix transform and store the resulting array in the variable "m_array".

Back: 3D Transformations
Next: matrix_multiply

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


matrix_get

Get the current values of the given matrix type.

Syntax:

matrix_get(type)

Argument | Description
type | The type of matrix to get the values of (see the constants listed below).

Returns: Array

Description

This function returns a 1D array of 16 values, corresponding to the given 4x4 matrix type. The available matrices are view, projection and world, for which you would use one of the following constants:

Constant | Description
matrix_view | The current view matrix
matrix_projection | The current projection matrix
matrix_world | The current world matrix

Example:

v_array = matrix_get(matrix_view);

The above code will get the values of the current view matrix and populate the array "v_array" with them.

Back: 3D Transformations
Next: matrix_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


matrix_multiply

Multiply two matrix arrays together.

Syntax:

matrix_multiply(matrix1, matrix2)

Argument | Description
matrix1 | The first matrix (as an array) to use.
matrix2 | The second matrix (as an array) to use.

Returns: Array

Description

With this function you can multiply two matrix arrays together to create a new transform matrix. The function will return the new matrix (again, as an array) which should be stored in a variable for future use.

NOTE: You can't use a matrix constant as an argument with this function, so if you wish to multiply the (for example) view matrix with a custom matrix that you have built, you must first call matrix_get(type) and assign the view matrix values to an array variable, then multiply it by your custom matrix, and then set the chosen matrix (view, projection or world).

Example:

var v_matrix = matrix_get(matrix_view);
var new_matrix = matrix_multiply(v_matrix, my_matrix);
matrix_set(matrix_view, new_matrix);

The above code will get the current view matrix, then multiply that with a custom matrix and then use the resulting matrix array to set the view matrix again.

Back: 3D Transformations
Next: d3d_transform_set_identity

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


matrix_set

Set the given matrix type to the values stored in a (previously created) matrix array.

Syntax:

matrix_set(type, matrix)

Argument | Description
type | The type of matrix to set the values of (see the constants listed below).
matrix | The matrix array to use for setting the given matrix.

Returns: N/A

Description

This function takes a 16 value 1D array (which you can create using the matrix_build or matrix_get functions) and uses it to set one of the following three matrix types:

Constant | Description
matrix_view | The current view matrix
matrix_projection | The current projection matrix
matrix_world | The current world matrix

Example:

matrix_set(matrix_world, m_array);

The above code will set the values of the current world matrix to those stored in the array matrix "m_array".

Back: 3D Transformations
Next: matrix_build

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Drawing Basic Forms

This section shows the functions available for drawing basic shapes and forms.

GameMaker: Studio has a whole collection of functions available for drawing different forms and shapes. These functions should only ever be used in the draw event of an instance (you can use them elsewhere but you won't see anything!) and create purely graphic effects, which means that they do not generate collision events as those can only be done through the sprite or collision mask that has been assigned to an instance. All these functions are affected by the current draw colour, alpha and blend mode (see colour And Blending).

Drawing Shapes

The following drawing functions exist that can be used to draw basic shapes:

  1. draw_arrow
  2. draw_circle
  3. draw_circle_colour
  4. draw_ellipse
  5. draw_ellipse_colour
  6. draw_line
  7. draw_line_colour
  8. draw_line_width
  9. draw_line_width_colour
  10. draw_point
  11. draw_point_colour
  12. draw_rectangle
  13. draw_rectangle_colour
  14. draw_roundrect
  15. draw_roundrect_colour
  16. draw_roundrect_ext
  17. draw_roundrect_colour_ext
  18. draw_triangle
  19. draw_triangle_colour

Further Drawing Functions

The following functions are also included in GameMaker: Studio to help better control what you draw on the screen:

  1. draw_set_circle_precision
  2. draw_button
  3. draw_healthbar
  4. draw_path

Back: Drawing

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_arrow

Draws an arrow, with a one pixel wide stem and the point defined by the user.

Syntax:

draw_arrow(x1, y1, x2, y2, size);

Argument | Description
x1 | The x coordinate of the start of the line.
y1 | The y coordinate of the start of the line.
x2 | The x coordinate of the end of the line (where the arrowhead ends).
y2 | The y coordinate of the end of the line (where the arrowhead ends).
size | The length of the arrow in pixels.

Returns: N/A

Description

This function will draw an arrow from point (x1,y1) to point (x2,y2). The stem of the arrow is drawn along these points with the actual arrow head being drawn at the end, where the size of the arrowhead is defined by the argument "size" and is calculated as being part of the stem so that the end point is always aligned with the position defined by x2,y2. The width of the arrow head is calculated automatically in proportion to the length.

Example:

draw_arrow(x, y, mouse_x, mouse_y, 10);

The above code will draw an arrow from the position of the instance to the position of the mouse, with the arrow head being 10 pixels long.

Back: Drawing Basic Forms
Next: draw_circle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_button

Draws a simple button of any size, either pressed or unpressed.

Syntax:

draw_button(x1, y1, x2, y2, up);

Argument | Description
x1 | The x coordinate of the left of the button
y1 | The y coordinate of the top of the button
x2 | The x coordinate of the right of the button
y2 | The y coordinate of the bottom of the button
up | Whether the button is up (true) or down (false)

Returns: N/A

Description

This function will draw a very simple, rectangular "button" using the currently selected draw colour and alpha where the up argument defines how the bevelled edge effect looks, as shown in the image below:

Example:

draw_button(100, 100, 200, 150, !mouse_check_button(mb_left));

This will draw a button which will appear pressed if the left mouse button is held down.

Back: Drawing Basic Forms
Next: draw_healthbar

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_circle

Draws a circle.

Syntax:

draw_circle(x, y, r, outline);

Argument | Description
x | The x coordinate of the center of the circle.
y | The y coordinate of the center of the circle.
r | The circle's radius (length from its center to its edge)
outline | Whether the circle is drawn filled (false) or as a one pixel wide outline (true).

Returns: N/A

Description

With this function you can draw either an outline of a circle or a filled circle. You can define how precise the drawing is with the function draw_set_circle_precision.

Example:

draw_set_colour(c_white);
draw_circle(100, 100, 50, true);

This will draw a one pixel wide white circle outline with a radius of 50 pixels.

Back: Drawing Basic Forms
Next: draw_circle_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_circle_colour

Draws a circle of a given size with a two-colour radial gradient.

Syntax:

draw_circle_colour(x, y, r, col1, col2, outline);

Argument | Description
x | The x coordinate of the center of the circle.
y | The y coordinate of the center of the circle.
r | The radius (distance from center to edge) of the circle in pixels.
col1 | The colour at the center of the circle.
col2 | The colour at the edge of the circle.
outline | Whether the circle is an outline (true) or not (false). If true, col1 is irrelevant.

Returns: N/A

Description

With this function you can draw either an outline of a circle or a filled circle, and if it is filled you can define the interior and exterior fill colours. If these colours are not the same, you will get a gradient effect from one to the other and the colour settings will over-ride the base colour set with the function draw_set_colour. You can define how precise the drawing is with the function draw_set_circle_precision.

Example:

draw_circle_colour(x, y, 100, c_white, c_black, false);

This would draw a filled circle with its center at the executing instance's x and y position, with a radius of 100 pixels, from white in the center to black at the outside.

Back: Drawing Basic Forms
Next: draw_ellipse

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_ellipse

Draws an ellipse.

Syntax:

draw_ellipse(x1, y1, x2, y2, outline);

Argument | Description
x1 | The x coordinate of the left of the ellipse.
y1 | The y coordinate of the top of the ellipse.
x2 | The x coordinate of the right of the ellipse.
y2 | The y coordinate of the bottom of the ellipse.
outline | Whether the ellipse is drawn filled (false) or as a one pixel wide outline (true).

Returns: N/A

Description

With this function you can draw either an outline of an ellipse or a filled ellipse by defining a rectangular area that will then have the ellipse created to fit. You can define how precise the drawing is with the function draw_set_circle_precision.

Example:

draw_set_colour(c_white);
draw_ellipse(100, 100, 300, 200, false);

This will draw a filled ellipse within the defined rectangular area.

Back: Drawing Basic Forms
Next: draw_ellipse_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_ellipse_colour

Draws an ellipse with a two-colour radial gradient.

Syntax:

draw_ellipse_colour(x1, y1, x2, y2, col1, col2, outline);

Argument | Description
x1 | The x coordinate of the left of the ellipse.
y1 | The y coordinate of the top of the ellipse.
x2 | The x coordinate of the right of the ellipse.
y2 | The y coordinate of the bottom of the ellipse.
col1 | The colour of the center.
col2 | The colour of the edge.
outline | Whether the ellipse is an outline (true) or filled in (false).

Returns: N/A

Description

With this function you can draw either an outline of an ellipse or a filled ellipse by defining a rectangular area that will then have the ellipse created to fit. If it is filled you can define the interior and exterior fill colours. If these colours are not the same, you will get a gradient effect from one to the other (the colour settings will over-ride the base colour set with the function draw_set_colour). You can define how precise the drawing is with the function draw_set_circle_precision.

Example:

draw_ellipse_colour(50, 50, 200, 100, c_black, c_white, false);

This would draw a filled-in, horizontally-stretched ellipse with a black center and white edge.

Back: Drawing Basic Forms
Next: draw_line

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_healthbar

Draws a custom healthbar.

Syntax:

draw_healthbar(x1, y1, x2, y2, amount, backcol, mincol, maxcol, direction, showback, showborder);

Argument | Description
x1 | The x coordinate of the left of the healthbar
y1 | The y coordinate of the top of the healthbar
x2 | The x coordinate of the right of the healthbar
y2 | The y coordinate of the bottom of the healthbar
amount | The variable which defines total health (between 0 and 100)
backcol | The colour of the background for the bar
mincol | The colour of the bar when at no health (0)
maxcol | The colour of the bar when at full health (100)
direction | Where the bar is 'anchored' (0 = left, 1 = right, 2 = top, 3 = bottom)
showback | Whether the bar's background is drawn (true) or not (false). If false, the backcol argument is disregarded.
showborder | Whether the bar's elements have a 1px wide black border (true) or not (false).

Returns: N/A

Description

With this function you can draw a coloured bar to show a constant value. Although the function uses the word "healthbar" you can use this to display anything you wish as long as the amount to be displayed is a percentage value between 0 and 100 (a percentage of any value can be calculated with the formula (CURRENT_Value / MAXIMUM_value) * 100), so, for example, you can use this to display power, health, mana, time or anything else that would benefit from a bar display.

You can set various different things that change the visual aspect of the bar and these are illustrated in the image below (note that the colours used here are c_green for the maximum value and c_red for the minimum value, but you can use the colours that you wish):

Example:

var pc;
pc = (hp / max_hp) * 100;
draw_healthbar(100, 100, 500, 200, pc, c_black, c_red, c_lime, 0, true, true)

The above code uses the percentage value that you get from the variables "hp" and "hp_max" to draw a standard red/green healthbar.

Back: Drawing Basic Forms
Next: draw_path

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_line

Draws a line one pixel wide.

Syntax:

draw_line(x1, y1, x2, y2);

Argument | Description
x1 | The x coordinate of the start of the line.
y1 | The y coordinate of the start of the line.
x2 | The x coordinate of the end of the line.
y2 | The y coordinate of the end of the line.

Returns: N/A

Description

With this function you can draw a 1 pixel wide line between any two points in the game room.

Example:

draw_set_colour(c_lime);
draw_line(50,50,150,50);

This will draw a light green horizontal line from point (50,50) to point (150,50).

Back: Drawing Basic Forms
Next: draw_line_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_line_colour

Draws a line one pixel wide with a colour gradient.

Syntax:

draw_line_colour(x1, y1, x2, y2, col1, col2);

Argument | Description
x1 | The x coordinate of the start of the line.
y1 | The y coordinate of the start of the line.
x2 | The x coordinate of the end of the line.
y2 | The y coordinate of the end of the line.
col1 | The colour of the start of the line.
col2 | The colour of the end of the line.

Returns: N/A

Description

With this function you can draw a 1 pixel wide line with the colour blended between colour 1 at the first point and colour 2 at the second point. The colour settings will over-ride the base colour set with the function draw_set_colour.

Example:

draw_line_colour(50, 50, 300, 50, c_red, c_blue);

This would draw a horizontal line from (50,50) to (300,50) with a smooth red to blue gradient.

Back: Drawing Basic Forms
Next: draw_line_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_line_width

Draws a line a defined number of pixels wide.

Syntax:

draw_line_width(x1, y1, x2, y2, w);

Argument | Description
x1 | The x coordinate of the start of the line.
y1 | The y coordinate of the start of the line.
x2 | The x coordinate of the end of the line.
y2 | The y coordinate of the end of the line.
w | The width of the line in pixels.

Returns: N/A

Description

With this function you can draw a line of a specified width between any two points in the game room.

Example:

draw_set_colour(c_red);
draw_line_width(100, 100, 200, 200, 6);

This will draw a red diagonal line, 6 pixels wide, from point (100,100) to point (200,200).

Back: Drawing Basic Forms
Next: draw_line_width_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_line_width_colour

Draws a line any number of pixels wide with a gradient colour.

Syntax:

draw_line_width_colour(x1, y1, x2, y2, w, col1, col2);

Argument | Description
x1 | The x coordinate of the start of the line.
y1 | The y coordinate of the start of the line.
x2 | The x coordinate of the end of the line.
y2 | The y coordinate of the end of the line.
w | The width in pixels of the line.
col1 | The colour of the start of the line.
col2 | The colour of the end of the line.

Returns: N/A

Description

With this function you can draw a line of a specific width with the colour blended between colour 1 at the first point and colour 2 at the second point. The colour settings will over-ride the base colour set with the function draw_set_colour.

Example:

draw_line_width_colour(50, 50, 300, 50, 4, c_red, c_blue);

This would draw a horizontal line from (50,50) to (300,50), four pixels wide, with a smooth red to blue gradient.

Back: Drawing Basic Forms
Next: draw_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_path

Draws a path resource.

Syntax:

draw_path(path, x, y, absolute);

Argument | Description
path | The path to draw
x | The x coordinate of where the path is drawn
y | The y coordinate of where the path is drawn
absolute | Whether the path is drawn at the absolute position (true) or the relative position (false)

Returns: N/A

Description

With this function you can get GameMaker: Studio to draw a path to the screen. The path will be drawn as a simple line, and can be either relative to the calling instance or at the absolute position it was created at in the path editor or through code. This function is extremely useful when debugging dynamic paths (for example, those created for instances with the mp_grid_path function).

Example:

if mp_grid_path(grid, path, x, y, obj_Player.x, obj_Player.y, 1)
{
draw_path(path, x, y, false);
}

the above code will use the mp_grid_path function to generate a path and store it in the variable "path". If the path is successfully created, it is then drawn on the screen at a position relative to the instance running the code.

Back: Drawing Basic Forms
Next: draw_set_circle_precision

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_point

Draws a single pixel.

Syntax:

draw_point(x, y);

Argument | Description
x | The x coordinate of the point to be drawn.
y | The y coordinate of the point to be drawn.

Returns: N/A

Description

With this function you can draw a single pixel anywhere on the screen.

Example:

draw_set_colour(c_yellow);
draw_point(100,100);

This will draw a yellow pixel at position (100,100).

Back: Drawing Basic Forms
Next: draw_point_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_point_colour

Draws a single pixel in a given colour.

Syntax:

draw_point_colour(x, y, col1);

Argument | Description
x | The x coordinate of the point.
y | The y coordinate of the point.
col1 | The colour of the point.

Returns: N/A

Description

With this function you can draw a single pixel anywhere on the screen with a colour that you define. The colour settings will over-ride the base colour set with the function draw_set_colour.

Example:

draw_point_colour(50, 50, c_red);

This would draw a red pixel at (50,50).

Back: Drawing Basic Forms
Next: draw_rectangle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_rectangle

Draws a rectangle.

Syntax:

draw_rectangle(x1, y1, x2, y2, outline);

Argument | Description
x1 | The x coordinate of the top left corner of the rectangle.
y1 | The y coordinate of the top left corner of the rectangle.
x2 | The x coordinate of the bottom right corner of the rectangle.
y2 | The y coordinate of the bottom right corner of the rectangle.
outline | Whether the rectangle is drawn filled (false) or as a one pixel wide outline (true).

Returns: N/A

Description

With this function you can draw either an outline of a rectangle or a filled rectangle where the (x1,y1) position is the top left corner and the (x2,y2) position is the bottom right corner.

Example:

draw_set_colour(c_yellow);
draw_rectangle(100, 100, 300, 200, true);

This will draw a rectangle outline, with its top left corner at (100,100) and its bottom right corner at (300,200).

Back: Drawing Basic Forms
Next: draw_rectangle_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_rectangle_colour

Draws a rectangle, either as a one pixel outline or filled-in, with each of the four corners a separate colour (creating a gradient across the shape).

Syntax:

draw_rectangle_colour(x1, y1, x2, y2, col1, col2, col3, col4, outline);

Argument | Description
x1 | The x coordinate of the left of the rectangle.
y1 | The y coordinate of the top of the rectangle.
x2 | The x coordinate of the right of the rectangle.
y2 | The y coordinate of the bottom of the rectangle.
col1 | The colour of the top left corner.
col2 | The colour of the top right corner.
col3 | The colour of the bottom right corner.
col4 | The colour of the bottom left corner.
outline | Whether the rectangle is an outline (true) or filled in (false).

Returns: N/A

Description

With this function you can draw either an outline of a rectangle or a filled rectangle by defining an area where the (x1,y1) position is the top left corner and the (x2,y2) position is the bottom right corner. If it is filled you can define the individual colours for each corner point and if these colours are not the same, you will get a gradient effect from one to the other (the colour settings will over-ride the base colour set with the function draw_set_colour).

Example:

draw_rectangle_colour(50, 50, 200, 200, c_black, c_white, c_black, c_white, false);

This would draw a filled-in square with a smooth black/white gradient between the corners.

Back: Drawing Basic Forms
Next: draw_roundrect

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_roundrect

Draws a rectangle with rounded corners of a fixed radius.

Syntax:

draw_roundrect(x1, y1, x2, y2, outline);

Argument | Description
x1 | The x coordinate of the top left corner of the rounded rectangle (as if it were a normal rectangle).
y1 | The y coordinate of the top left corner of the rounded rectangle (as if it were a normal rectangle).
x2 | The x coordinate of the bottom right corner of the rounded rectangle (as if it were a normal rectangle).
y2 | The y coordinate of the bottom right corner of the rounded rectangle (as if it were a normal rectangle).
outline | Whether the rounded rectangle is drawn filled (false) or as a one pixel wide outline (true).

Returns: N/A

Description

With this function you can draw either an outline of a rounded rectangle or a filled rounded rectangle where the (x1,y1) position is the top left corner and the (x2,y2) position is the bottom right corner. You can define how precise the drawing of the corners is with the function draw_set_circle_precision, but this function uses a fixed radius for them (should you need to change the corner radius, use the function draw_roundrect_ext()).

Example:

draw_set_colour(c_lime);
draw_roundrect(50, 100, 250, 200, 0);

This will draw a filled rounded rectangle, with its theoretical (before being curved) top left corner at (50,100) and its theoretical bottom right corner at (250,200).

Back: Drawing Basic Forms
Next: draw_roundrect_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_roundrect_colour

Draws a rectangle with rounded corners of a fixed radius, colouring it with a gradient of two colours.

Syntax:

draw_roundrect_colour(x1, y1, x2, y2, col1, col2, outline);

Argument | Description
x1 | The x coordinate of the left of the rounded rectangle.
y1 | The y coordinate of the top of the rounded rectangle.
x2 | The x coordinate of the right of the rounded rectangle.
y2 | The y coordinate of the bottom of the rounded rectangle.
col1 | The center colour.
col2 | The outside edge colour.
outline | Whether the rectangle is an outline (true) or filled in (false).

Returns: N/A

Description

With this function you can draw either an outline of a rounded rectangle or a filled rounded rectangle where the (x1,y1) position is the top left corner and the (x2,y2) position is the bottom right corner. If it is filled you can define the individual colours for the centre and the edges, and if these colours are not the same, you will get a gradient effect from one to the other (the colour settings will over-ride the base colour set with the function draw_set_colour).You can define how precise the drawing of the corners is with the function draw_set_circle_precision, but the corners are always drawn with a fixed radius. Should you need to change the corner radius you should use the function draw_roundrect_colour_ext().

Example:

draw_roundrect_colour(50, 50, 200, 200, c_black, c_white, false);

This would draw a filled-in square with rounded corners and with a smooth black/white gradient from the center to the edges.

Back: Drawing Basic Forms
Next: draw_roundrect_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_roundrect_colour_ext

Draws a rectangle with rounded corners of the given radius, colouring it with a gradient of two colours.

Syntax:

draw_roundrect_colour_ext(x1, y1, x2, y2, xrad, yrad, col1, col2, outline);

Argument | Description
x1 | The x coordinate of the left of the rounded rectangle.
y1 | The y coordinate of the top of the rounded rectangle.
x2 | The x coordinate of the right of the rounded rectangle.
y2 | The y coordinate of the bottom of the rounded rectangle.
xrad | The radius of the curve along the x axis from the rectangle corners.
yrad | The radius of the curve along the y axis from the rectangle corners.
col1 | The center colour.
col2 | The outside edge colour.
outline | Whether the rectangle is an outline (true) or filled in (false).

Returns: N/A

Description

With this function you can draw either an outline of a rounded rectangle or a filled rounded rectangle where the (x1,y1) position is the top left corner and the (x2,y2) position is the bottom right corner. If the rectangle is filled, then the colour arguments will be used to generate a colour gradient from the centre to the edges, where colour 1 is the centre colour and colour 2 the edge colour. You must also supply radius values for the x and y axis (in pixels) and the corners will be rounded by these amounts. You can define how precise the drawing of the corners is with the function draw_set_circle_precision.

Example:

var dist = point_distance(x, y, mouse_x, mouse_y) / 10;
var col = make_colour_hsv(clamp(dist, 0, 255), 255, 255);
draw_roundrect_colour_ext(x - 50, y - 50, x + 50, y + 50, dist, dist, col, c_white, 0);

This would draw a filled-in square with rounded corners, the radius of which is defined by the distance from the instance doing the drawing to the mouse. This value is also used to calculate the centre blend colour.

Back: Drawing Basic Forms
Next: draw_triangle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_roundrect_ext

Draws a rectangle with rounded corners of the given radius.

Syntax:

draw_roundrect_ext(x1, y1, x2, y2, xrad, yrad, outline);

Argument | Description
x1 | The x coordinate of the top left corner of the rounded rectangle (as if it were a normal rectangle).
y1 | The y coordinate of the top left corner of the rounded rectangle (as if it were a normal rectangle).
x2 | The x coordinate of the bottom right corner of the rounded rectangle (as if it were a normal rectangle).
y2 | The y coordinate of the bottom right corner of the rounded rectangle (as if it were a normal rectangle).
xrad | The radius of the curve along the x axis from the rectangle corners.
yrad | The radius of the curve along the y axis from the rectangle corners.
outline | Whether the rounded rectangle is drawn filled (false) or as a one pixel wide outline (true).

Returns: N/A

Description

With this function you can draw either an outline of a rounded rectangle or a filled rounded rectangle where the (x1,y1) position is the top left corner and the (x2,y2) position is the bottom right corner. You must also supply radius values for the x and y axis (in pixels) and the corners will be rounded by these amounts. You can define how precise the drawing of the corners is with the function draw_set_circle_precision.

Example:

var dist = point_distance(x, y, mouse_x, mouse_y) / 10;
draw_set_colour(c_lime);
draw_roundrect_ext(x - 50, y - 50, x + 50, y + 50, dist, dist, 0);

This will draw a filled rounded rectangle with the corners being rounded by an amount based on the mouse position relative to the instance doing the drawing.

Back: Drawing Basic Forms
Next: draw_roundrect_colour_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_circle_precision

Sets the precision for drawing a circle or ellipse.

Syntax:

draw_set_circle_precision(precision);

Argument | Description
precision | The precision of all circles drawn after this function is called.

Returns: N/A

Description

To optimise performance when drawing circles, GameMaker: Studio basically draws a polygon shape with enough sides to make it appear circular. However, depending on how big or small you need your circles to be, you may find that changing this value can help increase the performance of your game, or make the circles look better. The precision value that you can input into this function is the number of sides the circle polygon has, and this number can be anything between 4 and 64, but must be a number divisible by 4, with a default value of 24.

Example:

draw_set_circle_precision(12);

The above code will draw all circles using a 12 sided polygon.

Back: Drawing Basic Forms
Next: draw_button

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_triangle

Draws a triangle using three defined points.

Syntax:

draw_triangle(x1, y1, x2, y2, x3, y3, outline);

Argument | Description
x1 | The x coordinate of the triangle's first corner.
y1 | The y coordinate of the triangle's first corner.
x2 | The x coordinate of the triangle's second corner.
y2 | The y coordinate of the triangle's second corner.
x3 | The x coordinate of the triangle's third corner.
y3 | The y coordinate of the triangle's third corner.
outline | Whether the triangle is drawn filled (false) or as a one pixel wide outline (true).

Returns: N/A

Description

With this function you can draw either an outline of a triangle or a filled triangle.

Example:

draw_set_colour(c_aqua);
draw_triangle(50, 50, 200, 50, 50, 200, 0);

This will draw a filled aquamarine-coloured isosceles right-angled triangle, with its first corner at (50,50), its second at (200,50) and its third at (50,200).

Back: Drawing Basic Forms
Next: draw_triangle_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_triangle_colour

Draws a triangle of any shape and size, with separate colours assigned to each of its three corners.

Syntax:

draw_triangle_colour(x1, y1, x2, y2, x3, y3, col1, col2, col3, outline);

Argument | Description
x1 | The x coordinate of the triangle's first corner.
y1 | The y coordinate of the triangle's first corner.
x2 | The x coordinate of the triangle's second corner.
y2 | The y coordinate of the triangle's second corner.
x3 | The x coordinate of the triangle's third corner.
y3 | The y coordinate of the triangle's third corner.
col1 | The colour of the first corner.
col2 | The colour of the second corner.
col3 | The colour of the third corner.
outline | Whether the triangle is an outline (true) or filled in (false).

Returns: N/A

Description

With this function you can draw either an outline of a triangle or a filled triangle. If it is filled you can define the individual colours for each corner point and if these colours are not the same, you will get a gradient effect from one to the other (the colour settings will over-ride the base colour set with the function draw_set_colour).

Example:

draw_triangle_colour(200, 200, 300, 200, 200, 300, c_red, c_blue, c_blue, false);

This would draw a filled isosceles right-angled triangle with red at the right angle, blue on the other two corners.

Back: Drawing Basic Forms
Next: draw_arrow

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


2D Primitives

This section has the functions necessary for drawing 2D primitives.

A primitive is a type of drawing done using points to define what is shown on the screen. They can be made up of single points, lines, or triangles and can be coloured, have alpha blending and even be given a texture, which means that they can be used to create some very exciting effects in a 2D game! For example, you can create a rectangle using multiple triangle primitives, then texture it with a flag sprite and in the draw event of an instance have that flag "wave" in the wind and distort the sprite you used by simply modifying the points that form the primitive.

NOTE: These functions do not work with the HTML5 module unless you have enabled OpenGL in the Global Game Settings.

Information on primitives can be found in the following pages:

  1. draw_primitive_begin
  2. draw_primitive_begin_texture
  3. draw_primitive_end
  4. draw_vertex
  5. draw_vertex_colour
  6. draw_vertex_texture
  7. draw_vertex_texture_colour

Back: Reference
Next: Drawing Surfaces

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_primitive_begin

Starts a primitive of the indicated kind

Syntax:

draw_primitive_begin(kind)

Argument | Description
kind | The kind of primitive you are going to draw.

Returns: N/A

Description

This function must be called before you can define any primitives. There are 6 types of primitives you can define with the following constants:

  • pr_pointlist
  • pr_linelist
  • pr_linestrip
  • pr_trianglelist
  • pr_trianglestrip
  • pr_trianglefan (This is not available on the HTML5 target platform and may not work correctly on some devices for other platforms)

The following image illustrates basically how these should look and also the order in which you should define the vertexes:

Example:

var i, steps, xx, yy, radius;
steps=20;
xx=50;
yy=50;
radius=30;
draw_primitive_begin(pr_trianglefan);
draw_vertex(xx, yy);
for(i = 0; i <= steps; i += 1)
{
draw_vertex(xx + lengthdir_x(radius, 270 * i / steps), yy + lengthdir_y(radius, 270 * i / steps));
}
draw_primitive_end();

The above code will draw three quarters of a circle made from primitives.

Back: 2D Primitives
Next: draw_primitive_begin_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_primitive_begin_texture

Begins the process of defining a textured primitive.

Syntax:

draw_primitive_begin_texture(kind, tex)

Argument | Description
kind | The kind of primitive you are going to draw.
tex | The texture to use with the primitive.

Returns: N/A

Description

This function must be called before you define the vertices of a textured primitive. You must give the kind of primitive to use (see draw_primitive_begin for more information) and the id of a texture to use, which can be a sprite or background image asset. This asset id can be gotten from the functions sprite_get_texture and background_get_texture (use -1 for no texture).

NOTE: For a texture to repeat it must be a power of two in size, ie: 32x32, 128x128, etc...

Example:

draw_set_colour(c_white);
var tex = background_get_texture(background0);
draw_primitive_begin_texture(pr_trianglestrip, tex);
draw_vertex_texture(0, 0, 0, 0);
draw_vertex_texture(640, 0, 1, 0);
draw_vertex_texture(640, 480, 1, 1);
draw_vertex_texture(0, 480, 0, 1);
draw_primitive_end();

The above code will draw a 4 vertex triangle strip (making a rectangle) textured with the texture held in the "tex" variable, and the whole texture will be used to cover the completed primitive.

Back: 2D Primitives
Next: draw_primitive_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_primitive_end

Ends the process of defining a primitive and draws it.

Syntax:

draw_primitive_end()

Returns: N/A

Description

This function must be called when you have finished defining the points of your primitive. If you do not call this function, nothing will be drawn as this effectively tells GameMaker: Studio that you have finished and that it can now draw the defined primitive.

Example:

var tex;
tex = background_get_texture(back);
draw_primitive_begin_texture(pr_trianglestrip, tex);
draw_vertex_texture(0, 480, 0, 0);
draw_vertex_texture(640, 480, 1, 0);
draw_vertex_texture(640, 480, 1, 1);
draw_vertex_texture(0, 480, 0, 1);
draw_primitive_end();

The above code will draw a 4 vertex triangle strip textured with the texture held in the "tex" variable.

Back: 2D Primitives
Next: draw_vertex

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_vertex

Defines a vertex for a primitive.

Syntax:

draw_vertex(x, y)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.

Returns: N/A

Description

This function defines the position of a vertex for a primitive. The final look of the primitive will depend on the primitive type chosen to draw and the order with which you add the vertexes to it. See draw_primitive_begin for more information. To end and draw the primitive you must call draw_primitive_end.

Example:

draw_primitive_begin(pr_trianglelist);
draw_vertex(100, 100);
draw_vertex(100, 200);
draw_vertex(150, 150);
draw_primitive_end();

The above code will draw a simple triangle primitive.

Back: 2D Primitives
Next: draw_vertex_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_vertex_colour

Defines a primitive vertex with colour and alpha blending.

Syntax:

draw_vertex_colour(x, y, col, alpha)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
col | The colour to draw this vertex with.
alpha | The alpha to draw this vertex with (0-1).

Returns: N/A

Description

This function defines the position of a vertex for a primitive, with its own colour and alpha setting. The final look of the primitive will depend on the primitive type chosen to draw and the order with which you add the vertexes to it (see draw_primitive_begin for more information) and the vertexes with different colours and alphas will blend smoothly from one to the other. To end and draw the primitive you must call draw_primitive_end.

Example:

draw_primitive_begin(pr_trianglelist);
draw_vertex_colour(100, 100, c_blue, 0.1);
draw_vertex_colour(100, 200, c_red, 0.1);
draw_vertex_colour(150, 150, c_green, 1);
draw_primitive_end();

The above code will draw a semi-transparent triangle with each vertex coloured a different colour.

Back: 2D Primitives
Next: draw_vertex_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_vertex_texture

Defines a vertex for a textured primitive.

Syntax:

draw_vertex_texture(x, y, xtex, ytex)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
xtex | The width of the texture sample to use.
ytex | The height of the texture sample to use.

Returns: N/A

Description

This function defines the position of a textured vertex for a primitive. The final look of the primitive will depend on the primitive type chosen to draw (See draw_primitive_begin for more information), the order with which you add the vertexes to it and the position of the start point you set for the texture. To end and draw the primitive you must call draw_primitive_end.

You can also choose to draw only part of the texture over the surface of the primitive by setting the appropriate xtex/ytex position to sample to (these coordinates are also known as the UV points). This point is defined by a value between 0 and 1 with the top left corner of the image to use being the (0,0) point and the bottom right corner being the (1,1) point. In this way you can texture a primitive with only a part of the source image asset.

When drawing a textured primitive, the texture will be blended with the colour set by draw_set_colour. This means that to draw the texture with no blending this should be set to c_white, as shown in the example below.

NOTE: For a texture to repeat it must be a power of two in size, ie: 32x32, 128x128, etc...

Example:

draw_set_colour(c_white);
var tex = background_get_texture(background0);
draw_primitive_begin_texture(pr_trianglestrip, tex);
draw_vertex_texture(0, 480, 0, 1);
draw_vertex_texture(0, 0, 0, 0);
draw_vertex_texture(640, 480, 1, 1);
draw_vertex_texture(640, 0, 1, 0);
draw_primitive_end();

The above code will draw a 4 vertex triangle strip (making a rectangle) textured with the texture held in the "tex" variable, and the whole texture will be used to cover the completed primitive.

Back: 2D Primitives
Next: draw_vertex_texture_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_vertex_texture_colour

Defines a vertex for a textured primitive in 3D, giving a blend colour and alpha.

Syntax:

draw_vertex_texture_colour(x, y, xtex, ytex, col, alpha)

Argument | Description
x | The x coordinate of the vertex.
y | The y coordinate of the vertex.
xtex | The x coordinate within the texture.
ytex | The y coordinate within the texture.
col | The colour to blend with the texture at this vertex (-1 or c_white for no blending).
alpha | The alpha to draw this vertex with (0-1).

Returns: N/A

Description

This function defines the position of a textured vertex for a primitive. The final look of the primitive will depend on the primitive type chosen to draw (See draw_primitive_begin for more information), the order with which you add the vertices to it, the position of the start and end points that you give for the texture sample and the colour and alpha values that you have set. To maintain the texture appearance while changing only the alpha, a value of -1 (or c_white) may be used for the colour argument. To end and draw the primitive you must call draw_primitive_end.

NOTE: For a texture to repeat it must be a power of two in size, ie: 32x32, 128x128, etc...

Example:

draw_set_colour(c_white);
var tex = background_get_texture(back);
draw_primitive_begin_texture(pr_trianglestrip, tex);
draw_vertex_texture_colour(0, 480, 0, 1, c_green, 1);
draw_vertex_texture_colour(0, 0, 0, 0, c_fuchsia, 1);
draw_vertex_texture_colour(640, 480, 1, 1, c_red, 1);
draw_vertex_texture_colour(640, 0, 1, 0, c_blue, 1);
draw_primitive_end();

The above code will draw a 4 vertex triangle strip (making a rectangle) textured with the texture held in the "tex" variable, and the whole texture will be used to cover the completed primitive, and it will be blended with four different colours.

Back: 2D Primitives

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Drawing Sprites And Backgrounds

This section contains all the functions available for drawing the graphics assets.

Even though you can set up backgrounds in the room editor and you can assign sprites to instances, often this is not flexible enough for the game you are making. For example, if you have an instance that has to draw a menu, you may want to display various button sprites at a time, or if you have a game with scrolling parallax backgrounds you will need to be able to set them through code in a controller instance of some type. In these situations you should be using the following functions which can draw sprite and background assets anywhere in the room with some of the functions also permitting you to manipulate the shape, size, colour and alpha of the sprite to achieve special effects.

Sprites

You can assign a sprite to an instance and by default GameMaker: Studio will draw it with the properties given by the various sprite variables, however if you add anything into the draw event, you are "taking control" and must tell GameMaker: Studio exactly what to draw. This means that if you must use the following functions to define exactly what it is the instance is to draw and where about in the room it is to draw it:

  1. draw_self
  2. draw_sprite
  3. draw_sprite_ext
  4. draw_sprite_general
  5. draw_sprite_part
  6. draw_sprite_part_ext
  7. draw_sprite_stretched
  8. draw_sprite_stretched_ext
  9. draw_sprite_pos
  10. draw_sprite_tiled
  11. draw_sprite_tiled_ext

If you are using SWF format sprites, then there are also additional options for controlling the anti-aliasing used when drawing (see Importing Vector Images for more information on these types of sprites). Note that these functions work on a global level and will set the AA on all vector SWF sprites drawn after they have been called.

  1. draw_enable_swf_aa
  2. draw_set_swf_aa_level
  3. draw_get_swf_aa_level

Apart from those functions listed above, there are also two special functions designed for use with skeletal animations (see Importing Skeletal Animations for more information on these types of sprites, and the section Skeletal Animations for specific functions related to these types of sprites):

  1. draw_skeleton
  2. draw_skeleton_collision
  3. draw_skeleton_time

Backgrounds

Although the Room Editor Backgrounds Tab has a number of options for setting up backgrounds, it is often more useful to draw them using code. To that end, GameMaker: Studio has the following functions that permit you to draw background assets in a number of different ways:

NOTE: Don't forget that adding any code into the draw event of an instance will switch off the automatic drawing of the sprite for that instance, so if you need to draw the sprite and a background you should use the functions above in combination with those listed here.

  1. draw_background
  2. draw_background_ext
  3. draw_background_part
  4. draw_background_part_ext
  5. draw_background_stretched
  6. draw_background_stretched_ext
  7. draw_background_tiled
  8. draw_background_tiled_ext
  9. draw_background_general

Back: Drawing

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_background

Draw a background without colour blending or transparency

Syntax:

draw_background(back, x, y);

Argument | Description
back | The index of the background to draw.
x | The x coordinate of where to draw the background.
y | The y coordinate of where to draw the background.

Returns: N/A

Description

With this function you can draw any of the game's background assets at a given position within the room, with the top left corner of the image being drawn at the specified x/y position.

Example:

draw_background(bck_Sky, view_xview[0], view_yview[0]);

The above code draws the background indexed in "bck_Sky" at same position as view[0].

Back: Drawing Sprites And Backgrounds
Next: draw_background_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_background_ext

Draws a background at a given position, with customizable scaling, rotation, blend and alpha.

Syntax:

draw_background_ext(back, x, y, xscale, yscale, rot, colour, alpha);

Argument | Description
back | The index of the background to draw.
x | The x coordinate of where to draw the background.
y | The y coordinate of where to draw the background.
xscale | The horizontal scaling of the background.
yscale | The vertical scaling of the background.
rot | The rotation of the background.
colour | The colour with which to blend the background (use -1 or c_white to display it normally).
alpha | The alpha of the background (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function will draw the given background as in the function draw_background but with additional options to change the scale, blending, rotation and alpha of the background being drawn. Changing these values does not modify the resource in any way (only how it is drawn), and you can use any of the available background variables instead of direct values for all the arguments in the function.

NOTE: Colour blending is only recommended for the HTML5 target when WebGL is enabled, although you can still set the blending colour if it is not enabled and it will blend the sprite as normal. However all blending in this way creates a duplicate sprite which is then stored in the cache and used when required. This is far from optimal and if you use multiple colour changes it will slow down your games performance unless you activate WebGL. If you do not wish to use WebGL, and still require blended images, then you should consider using sprites and setting the sprite cache to help limit performance issues - see sprite_set_cache_size.

Example:

draw_background_ext(bck_Sky, 0, 0, background_xscale[0], background_yscale[0], 0, c_red, 0.5);

The above code will draw a background at the (0,0) position in the room, with the same scale as the background indexed in background[0], blended red and semi transparent.

Back: Drawing Sprites And Backgrounds
Next: draw_background_part

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_background_general

Draws part of a background at a given position with scaling, rotating, four-corner blending and alpha options.

Syntax:

draw_background_general(back, left, top, width, height, x, y, xscale, yscale, rot, c1, c2, c3, c4, alpha);

Argument | Description
back | The index of the background to draw.
left | The x position on the background of the top left corner of the area to draw.
top | The y position on the background of the top left corner of the area to draw.
width | The width of the area to draw.
height | The height of the area to draw.
x | The x coordinate of where to draw the background.
y | The y coordinate of where to draw the background.
xscale | The horizontal scaling of the background.
yscale | The vertical scaling of the background.
rot | The rotation of the background.
c1 | The colour with which to blend the top left area of the background.
c2 | The colour with which to blend the top right area of the background.
c3 | The colour with which to blend the bottom right area of the background.
colour | The colour with which to blend the bottom left area of the background.
alpha | The alpha of the background (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function combines the function draw_background_ext with the function draw_background_part, adding in some additional blending options so that each corner of the final background part can be blended with an individual colour.

NOTE: Colour blending is only recommended for the HTML5 target when WebGL is enabled, although you can still set the blending colour if it is not enabled and it will blend the sprite as normal. However all blending in this way creates a duplicate sprite which is then stored in the cache and used when required. This is far from optimal and if you use multiple colour changes it will slow down your games performance unless you activate WebGL. If you do not wish to use WebGL, and still require blended images, then you should consider using sprites and setting the sprite cache to help limit performance issues - see sprite_set_cache_size.

Example:

draw_background_general(bck_Sky, 8, 8, 32, 32, x, y, 2, 0.5, 180, c_white, c_white, c_black, c_black, 1);

This will draw a 32x32 pixel area from 8x8 pixels into bck_Sky. It will be stretched to double its usual width but half its usual height. It will be opaque, and upside down. The top area of the background will be blended white and hence normal, but the bottom area will be black, meaning the background will go from normal to silhouette downwards in a smooth gradient.

Back: Drawing Sprites And Backgrounds
Next: draw_background

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_background_part

Draws part of a background at a given position.

Syntax:

draw_background_part(back, left, top, width, height, x, y);

Argument | Description
back | The index of the background to draw.
left | The x position on the background of the top left corner of the area to draw.
top | The y position on the background of the top left corner of the area to draw.
width | The width of the area to draw.
height | The height of the area to draw.
x | The x coordinate of where to draw the background.
y | The y coordinate of where to draw the background.

Returns: N/A

Description

With this function you can draw part of any background at a given position within the room. As with draw_background you can specify a background, but you then need to specify the relative coordinates within the background of an area to select for drawing. This means that a left position of 0 and a top position of 0 would be the top left corner of the background and all further coordinates should be taken from that position.

Example:

draw_background_part(bck_Sky, 8, 8, 32, 32, x, y);

This will draw a 32x32 area 8px by 8px in from the top left of the background indexed in "bck_Sky", at the instances (x,y) position.

Back: Drawing Sprites And Backgrounds
Next: draw_background_part_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_background_part_ext

Draws part of a background at a given position with scaling, blending and alpha options.

Syntax:

draw_background_part_ext(back, left, top, width, height, x, y, xscale, yscale, colour, alpha);

Argument | Description
back | The index of the background to draw.
left | The x position on the background of the top left corner of the area to draw.
top | The y position on the background of the top left corner of the area to draw.
width | The width of the area to draw.
height | The height of the area to draw.
x | The x coordinate of where to draw the background.
y | The y coordinate of where to draw the background.
xscale | The horizontal scaling of the background.
yscale | The vertical scaling of the background.
colour | The colour with which to blend the background (use -1 or c_white to display it normally).
alpha | The alpha of the background (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function will draw a part of the chosen background at the given position following the same rules as per draw_background_part, only now you can scale the part, blend a colour with it, or change its alpha when drawing it to the screen (the same as when drawing a background with draw_background_ext).

NOTE: Colour blending is only recommended for the HTML5 target when WebGL is enabled, although you can still set the blending colour if it is not enabled and it will blend the sprite as normal. However all blending in this way creates a duplicate sprite which is then stored in the cache and used when required. This is far from optimal and if you use multiple colour changes it will slow down your games performance unless you activate WebGL. If you do not wish to use WebGL, and still require blended images, then you should consider using sprites and setting the sprite cache to help limit performance issues - see sprite_set_cache_size.

Example:

draw_background_part_ext(bck_Sky, 8, 8, 32, 32, x, y, 2, 0.5, c_black, 1);

This will draw a 32x32 pixel area from 8x8 pixels into bck_Sky. It will be stretched to double its usual width but half its usual height. It will be opaque and it will be blended with black (turning it into a silhouette).

Back: Drawing Sprites And Backgrounds
Next: draw_background_stretched

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_background_stretched

Draws a background at a given position, stretched.

Syntax:

draw_background_stretched(back, x, y, w, h);

Argument | Description
back | The index of the background to draw.
x | The x coordinate of where to draw the background.
y | The y coordinate of where to draw the background.
w | The width of the area the stretched background will occupy.
h | The height of the area the stretched background will occupy.

Returns: N/A

Description

This function simply takes a background resource and stretches it over the given width and height so that it occupies the area. As with draw_background you can specify a background and then the x / y position in the room for the background to be drawn at and finally a width and a height (which must be pixel values).

Example:

draw_background_stretched(bck_Sky, 10, 10, 100, 100);

This will draw background0 with its left corner at (10,10). Its width and height are both set to 100, which is how much space it will occupy regardless of the background's actual width and height.

Back: Drawing Sprites And Backgrounds
Next: draw_background_stretched_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_background_stretched_ext

Draws a background at a given position, stretched, and allows for a custom blend and alpha.

Syntax:

draw_background_stretched_ext(back, x, y, w, h, colour, alpha);

Argument | Description
back | The index of the background to draw.
x | The x coordinate of where to draw the background.
y | The y coordinate of where to draw the background.
w | The width of the area the stretched background will occupy.
h | The height of the area the stretched background will occupy.
colour | The colour with which to blend the background (use -1 or c_white to display it normally).
alpha | The alpha of the background (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function does exactly the same as the draw_background_stretched function with the added ability to set the colour blending and alpha value for the background when it is drawn (similar to the function draw_background_ext).

NOTE: Blending is not available for the HTML5 target unless WebGL is enabled.

Example:

draw_background_stretched_ext(bck_Sky, x, y, 200, 200, c_white, 0.5);

This will draw the given background with its left corner at the instances x/y position and it will be stretched to occupy an area of 200x200 pixels with no blending, but partial transparency.

Back: Drawing Sprites And Backgrounds
Next: draw_background_tiled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_background_tiled

Draws a background at a given position, and tiles it to fill the entire view.

Syntax:

draw_background_tiled(back, x, y);

Argument | Description
back | The index of the background to draw.
x | The x coordinate of where to draw the background.
y | The y coordinate of where to draw the background.

Returns: N/A

Description

This function will take a background and then repeatedly tile it across the whole view (or room if no view is defined), starting from the coordinates that you give in the function.

Example:

draw_background_tiled(bck_Sky, x, y);

This will draw the background indexed in "bck_Sky" at the instances own x and y position, and tiled in every direction in the view.

Back: Drawing Sprites And Backgrounds
Next: draw_background_tiled_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_background_tiled_ext

Draws a background at a given position with scaling, blending and alpha, and tiles it to fill the entire view.

Syntax:

draw_background_tiled_ext(back, x, y, xscale, yscale, colour, alpha);

Argument | Description
back | The index of the background to draw.
x | The x coordinate of where to draw the background.
y | The y coordinate of where to draw the background.
xscale | The horizontal scaling of the background.
yscale | The vertical scaling of the background.
colour | The colour with which to blend the background (use -1 or c_white to display it normally).
alpha | The alpha of the background (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function will take a background and then repeatedly tile it across the whole view (or room if no view is defined), starting from the coordinates that you give in the function and with each tile scaled, colour blended and with the alpha that you define (these properties are the same as those used in draw_background_ext).

NOTE: Colour blending is only recommended for the HTML5 target when WebGL is enabled, although you can still set the blending colour if it is not enabled and it will blend the sprite as normal. However all blending in this way creates a duplicate sprite which is then stored in the cache and used when required. This is far from optimal and if you use multiple colour changes it will slow down your games performance unless you activate WebGL. If you do not wish to use WebGL, and still require blended images, then you should consider using sprites and setting the sprite cache to help limit performance issues - see sprite_set_cache_size.

Example:

draw_background_tiled_ext(bck_Sky, x, y, 2, 2, c_red, 0.5);

This will draw the background indexed in "bck_Sky" at the instances own x and y position, double its stored size and tiled in every direction in the room, as well as blended with the colour red and partially transparent.

Back: Drawing Sprites And Backgrounds
Next: draw_background_general

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_enable_swf_aa

Enable or disable anti-aliasing for SWF format vector sprites.

Syntax:

draw_enable_swf_aa(enable);

Argument | Description
enable | Enable (true) or disable (false) AA for all SWF sprites.

Returns: N/A

Description

With this function you can enable or disable anti-aliasing (AA) for SWF format vector sprites. AA simply smooths the edges of vector images to give them a nicer look. The amount of AA used will depend on the value set using the function draw_set_swf_aa_level(). By default this is disabled.

Example:

if draw_get_swf_aa_level() == 0
{
draw_enable_swf_aa(true);
draw_set_swf_aa_level(0.5);
}

The above code will check the AA value for SWF format sprites, and if it is 0 it enables AA and sets the value to 0.5.

Back: Drawing Sprites And Backgrounds
Next: draw_set_swf_aa_level

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_get_swf_aa_level

Get the current anti-aliasing level for SWF format vector sprites.

Syntax:

draw_get_swf_aa_level();

Returns: Real

Description

This function can be used to get the anti-aliasing (AA) level for SWF format vector sprites. The return value will between 0 and 1 and shows how "smooth" the edges of these sprites will be drawn. You can set the AA level using the function draw_set_swf_aa_level().

Example:

if draw_get_swf_aa_level() == 0
{
draw_enable_swf_aa(true);
draw_set_swf_aa_level(0.5);
}

The above code will check the AA value for SWF format sprites, and if it is 0 it enables AA and sets the value to 0.5.

Back: Drawing Sprites And Backgrounds
Next: draw_skeleton

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_self

This draws the instance sprite the same as the default draw.

Syntax:

draw_self();

Returns: N/A

Description

This function draws the sprite assigned to the instance exactly as it would be drawn if the draw event held no code or actions, and will reflect and changes that have been made to the sprite variables in other events.

NOTE: If the instance has no sprite assigned to it, this function will throw an error!

Example:

draw_self();

This makes the instance draw itself with the properties defined by the in built sprite variables.

Back: Drawing Sprites And Backgrounds
Next: draw_sprite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_swf_aa_level

Set the anti-aliasing level for SWF format vector sprites.

Syntax:

draw_set_swf_aa_level(AA);

Argument | Description
AA | The anti-aliasing value to use from 0 to 1.

Returns: N/A

Description

This function can be used to set the anti-aliasing (AA) level for SWF format vector sprites. This can be a real value from 0 to 1 and will "smooth" the edges of these sprites. Note that to see this effect, you must first have enabled AA using the function draw_enable_swf_aa().

Example:

if draw_get_swf_aa_level() == 0
{
draw_enable_swf_aa(true);
draw_set_swf_aa_level(0.5);
}

The above code will check the AA value for SWF format sprites, and if it is 0 it enables AA and sets the value to 0.5.

Back: Drawing Sprites And Backgrounds
Next: draw_get_swf_aa_level

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_skeleton

Draws a frame from a given skeletal animation using sprite transforms.

Syntax:

draw_skeleton(sprite, animname, skinname, frame, x, y, xscale, yscale, rot, colour, alpha);

Argument | Description
sprite | The index of the sprite to draw.
animname | The name of the animation to get the frame from (a string).
skinname | The name of the skin to use (a string).
frame | The animation frame to draw (from 0 to image_number - 1).
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.
xscale | The horizontal scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
yscale | The vertical scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
rot | The rotation of the sprite. 0=normal, 90=turned 90 degrees counter-clockwise etc.
colour | The colour with which to blend the sprite.
alpha | The alpha of the sprite (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function is only for use with sprites that have been created using a skeletal animation program like Spine. While you can draw these sprites using the normal draw functions (like draw_self()), there are times when you may want to draw a single frame or show a change of skin texture without actually changing the sprite properties. In these cases you can draw the sprite with this function, where you give the sprite index and then the name of the animation to get the frame from (a string, as set within the program used to make the sprite). Next you give the name of the skin to use (again, as set when the sprite was made), and a frame value. The frame value is for telling GameMaker: Studio what part of the animation to show and is a value between 0 and the image_number. The rest of the arguments are the same as those used for normal sprite drawing and will change the scale, angle, blend colour and alpha of the final animation frame being drawn.

WARNING! Because of the way skeletal animations are interpolated between various "key" frames, there is an additional overhead associated with this call and therefore it is recommended that you avoid drawing skeleton based sprites using this method unless absolutely necessary.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

draw_skeleton(spr_Jump, "jump", "skin1", 0, x, y, image_xscale, image_yscale, image_angle, c_white, 0.5);

The above code will draw the first frame of the given skeletal animation sprite, using the "jump" animation set, the skin defined as "skin1" and at the same scale and position as the instance properties define, but with an alpha of 0.5.

Back: Drawing Sprites And Backgrounds
Next: draw_skeleton_collision

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_skeleton_collision

Draws the collision masks for a given frame of a skeletal animation with transforms.

Syntax:

draw_skeleton_collision(sprite, animname, frame, x, y, xscale, yscale, rot, colour)

Argument | Description
sprite | The index of the sprite to draw.
animname | The name of the animation to get the frame from (a string).
frame | The animation frame to draw (from 0 to image_number - 1).
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.
xscale | The horizontal scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
yscale | The vertical scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
rot | The rotation of the sprite. 0=normal, 90=turned 90 degrees counter-clockwise etc.
colour | The colour with which to blend the sprite.

Returns: N/A

Description

This function will draw the collision masks associated with the given skeletal animation. You supply the base sprite, the animation set to use and the frame to get the information from, and you can also set the transform properties to suit.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

draw_skeleton_collision(sprite_index, "jump", image_index, x, y, image_xscale, image_yscale, image_angle, c_white);

The above code will draw the collision mask data for the current sprite, using the current transforms, for the animation set "jump".

Back: Drawing Sprites And Backgrounds
Next: draw_skeleton_time

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_skeleton_time

Draws the skeletal animation sprite at a specific time-frame.

Syntax:

draw_skeleton_time(sprite, animname, skinname, time, x, y, xscale, yscale, rot, colour)

Argument | Description
sprite | The index of the sprite to draw.
animname | The name of the animation to get the frame from (a string).
skinname | The name of the skin to use for drawing (a string).
time | The time-frame to draw the animation at (from 0 to the end duration, in seconds).
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.
xscale | The horizontal scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
yscale | The vertical scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
rot | The rotation of the sprite. 0=normal, 90=turned 90 degrees counter-clockwise etc.
colour | The colour with which to blend the sprite.

Returns: N/A

Description

This function will draw the given animation using the given skin at a specific time in the animation. The time value should be between 0 (the beginning) and the end duration of the animation, which you can find using the function skeleton_animation_get_duration(). You can set the time value to values higher than the total duration of the animation and the animation will loop back to the beginning, but you run the risk of losing floating point accuracy as the accumulated time gets larger.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var time += delta_time / 1000000;
var d = skeleton_animation_get_duration("walk");
if time > d time -= d;
draw_skeleton_time(sprite_index, "walk", "skin1", time, x, y, image_xscale, image_yscale, image_angle, c_white);

The above code will draw the given skeletal animation sprite using delta-time to set the frame being drawn.

Back: Drawing Sprites And Backgrounds
Next: draw_self

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite

Draws a sprite at a given position.

Syntax:

draw_sprite(sprite, subimg, x, y);

Argument | Description
sprite | The index of the sprite to draw.
subimg | The sub-image (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.

Returns: N/A

Description

This function draws the given sprite and sub-image at a position within the game room. For the sprite you can use the instance variable sprite_index to get the current sprite that is assigned to the instance running the code, or you can use any other sprite asset. The same goes for the sub-image, as this can also be set to the instance variable image_index which will set the sub-image to that selected for the current instance sprite (note, that you can draw a different sprite and still use the sub-image value for the current instance), or you can use any other value for this to draw a specific sub-image of the chosen sprite. If the value is larger than the number of sub-images, then GameMaker: Studio will automatically loop the number to select the corresponding image (for example, if the sprite being drawn has 5 sub-images numbered 0 to 4 and we set the index value to 7, then the function will draw sub-image 3, numbered 0). Finally, the x and y position is the position within the room that the sprite will be drawn, and it is centered on the sprite x offset and y offset.

Example:

draw_sprite(sprite_index, image_index, x, y);
draw_sprite(spr_Halo, 0, x, y-32);

This will draw the instances assigned sprite (sprite_index) with the current sub-image at the x and y position of the instance within the room. It will then draw the first frame of the sprite indexed by "spr_Halo" at the same x and y position but 32 pixels 'above'.

Back: Drawing Sprites And Backgrounds
Next: draw_sprite_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite_ext

Draws a sprite at a given position, with customizable scaling, rotation, blend and alpha.

Syntax:

draw_sprite_ext( sprite, subimg, x, y, xscale, yscale, rot, colour, alpha );

Argument | Description
sprite | The index of the sprite to draw.
subimg | The subimg (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.
xscale | The horizontal scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
yscale | The vertical scaling of the sprite as a multiplier: 1 = normal scaling, 0.5 is half etc...
rot | The rotation of the sprite. 0=right way up, 90=rotated 90 degrees counter-clockwise etc...
colour | The colour with which to blend the sprite. c_white is to display it normally.
alpha | The alpha of the sprite (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function will draw the given sprite as in the function draw_sprite but with additional options to change the scale, blending, rotation and alpha of the sprite being drawn. Changing these values does not modify the resource in any way (only how it is drawn), and you can use any of the available sprite variables instead of direct values for all the arguments in the function. The image below illustrates how different values affect the drawing of the sprite:

NOTE: Colour blending is only recommended for the HTML5 target when WebGL is enabled, although you can still set the blending colour if it is not enabled and it will blend the sprite as normal. However all blending in this way creates a duplicate sprite which is then stored in the cache and used when required. This is far from optimal and if you use multiple colour changes it will slow down your games performance unless you activate WebGL. if you do not wish to use WebGL, then you can set the font cache size to try and limit this should it be necessary using the function sprite_set_cache_size.

Example:

draw_sprite_ext(sprite_index, image_index, x, y, image_xscale, image_yscale, image_angle, image_blend, image_alpha);

This will draw the instances assigned sprite with all its default values (essentially the same as using draw_self).

Back: Drawing Sprites And Backgrounds
Next: draw_sprite_general

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite_general

Draws a part of a given sprite with options for scaling, blending and rotation.

Syntax:

draw_sprite_general(sprite, subimg, left, top, width, height, x, y, xscale, yscale, rot, c1, c2, c3, c4, alpha);

Argument | Description
sprite | The index of the sprite to draw.
subimg | The subimg (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
left | The x position on the sprite of the top left corner of the area to draw.
top | The y position on the sprite of the top left corner of the area to draw.
width | The width of the area to draw.
height | The height of the area to draw.
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.
xscale | The horizontal scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
yscale | The vertical scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
rot | The rotation of the sprite. 0=normal, 90=turned 90 degrees counter-clockwise etc.
c1 | The colour with which to blend the top left area of the sprite.
c2 | The colour with which to blend the top right area of the sprite.
c3 | The colour with which to blend the bottom right area of the sprite.
c4 | The colour with which to blend the bottom left area of the sprite.
alpha | The alpha of the sprite (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function combines the function draw_sprite_ext with the function draw_sprite_part, adding in some additional blending options so that each corner of the final sprite part can be blended with an individual colour.

NOTE: Colour blending is only recommended for the HTML5 target when WebGL is enabled, although you can still set the blending colour if it is not enabled and it will blend the sprite as normal. However all blending in this way creates a duplicate sprite which is then stored in the cache and used when required. This is far from optimal and if you use multiple colour changes it will slow down your games performance unless you activate WebGL. if you do not wish to use WebGL, then you can set the font cache size to try and limit this should it be necessary using the function sprite_set_cache_size.

Example:

draw_sprite_general(sprite_index, image_index, 8, 8, sprite_width-16, sprite_height-16, x, y, 2, 0.5, 180, c_white, c_white, c_black, c_black, 1);

This will draw the instances assigned sprite (sprite_index) and its current frame of animation (image_index), however it will shave an 8px margin off all four sides of the sprite. It will be stretched to double its usual width but half its usual height. It will be opaque, and upside down. The top area of the sprite will be blended white and hence normal, but the bottom area will be black, meaning the sprite will go from normal to a silhouette downwards in a smooth gradient.

Back: Drawing Sprites And Backgrounds
Next: draw_sprite_part

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite_part

Draws part of a sprite at a given position.

Syntax:

draw_sprite_part(sprite, subimg, left, top, width, height, x, y);

Argument | Description
sprite | The index of the sprite to draw.
subimg | The subimg (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
left | The x position on the sprite of the top left corner of the area to draw.
top | The y position on the sprite of the top left corner of the area to draw.
width | The width of the area to draw.
height | The height of the area to draw.
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.

Returns: N/A

Description

With this function you can draw part of any sprite at a given position within the room. As with draw_sprite you can specify a sprite and a sub-image for drawing, then you must give the relative coordinates within the sprite of the area to select for drawing. This means that a left position of 0 and a top position of 0 would be the top left corner of the sprite and all further coordinates should be taken from that position. The image below shows an example of how this works:

You should note that if the texture page permits automatic cropping then this function may not work as expected, since the extra "empty" space around the sprite will have been removed for creating the texture page. To resolve this issue, you will need to set the texture page settings (in the Global Game Settings) to no cropping.

NOTE: When drawing with this function, the sprite x offset and y offset are ignored and the sprite part will be drawn with the top left corner at the specified x / y position in the room.

NOTE: This function is only useful for bitmap sprites and will not work with SWF or JSON (Spine) sprites.

Example:

draw_sprite_part(sprite_index, image_index, 4, 0, sprite_width-16, sprite_height-16, x, y );

This will draw the instances assigned sprite (sprite_index) and its current frame of animation (image_index), however it will shave a 4px margin off the width on both sides, and an 8 pixel margin off the height from the bottom of the original 24x24 pixel sprite.

Back: Drawing Sprites And Backgrounds
Next: draw_sprite_part_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite_part_ext

Draws part of a sprite at a given position with scaling, blending and alpha options.

Syntax:

draw_sprite_part_ext(sprite, subimg, left, top, width, height, x, y, xscale, yscale, colour, alpha);

Argument | Description
sprite | The index of the sprite to draw.
subimg | The subimg (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
left | The x position on the sprite of the top left corner of the area to draw.
top | The y position on the sprite of the top left corner of the area to draw.
width | The width of the area to draw.
height | The height of the area to draw.
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.
xscale | The horizontal scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
yscale | The vertical scaling of the sprite, as a multiplier: 1 = normal scaling, 0.5 is half etc...
colour | The colour with which to blend the sprite. c_white is to display it normally.
alpha | The alpha of the sprite (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function will draw a part of the chosen sprite at the given position following the same rules as per draw_sprite_part, only now you can scale the part, blend a colour with it, or change its alpha when drawing it to the screen (the same as when drawing a sprite with draw_sprite_ext). You should note that if the texture page permits automatic cropping then this function may not work as expected, since the extra "empty" space around the sprite will have been removed for creating the texture page. To resolve this issue, you will need to set the texture page settings (in the Global Game Settings) to no cropping.

NOTE: When drawing with this function, the sprite x offset and y offset are ignored and the sprite part will be drawn with the top left corner at the specified x / y position in the room.

NOTE: Colour blending is only recommended for the HTML5 target when WebGL is enabled, although you can still set the blending colour if it is not enabled and it will blend the sprite as normal. However all blending in this way creates a duplicate sprite which is then stored in the cache and used when required. This is far from optimal and if you use multiple colour changes it will slow down your games performance unless you activate WebGL. if you do not wish to use WebGL, then you can set the font cache size to try and limit this should it be necessary using the function sprite_set_cache_size.

NOTE: This function is only useful for bitmap sprites and will not work with SWF or JSON (Spine) sprites.

Example:

draw_sprite_part_ext(sprite_index, image_index, 8, 8, sprite_width-16, sprite_height-16, x, y, 2, 0.5, c_black, 1);

This will draw the instances assigned sprite (sprite_index) and its current frame of animation (image_index), however it will shave an 8px margin off all four sides of the sprite. It will then be stretched to double its usual width but half its usual height, and although the alpha is still 1, it will be blended with black (turning it into a silhouette).

Back: Drawing Sprites And Backgrounds
Next: draw_sprite_pos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite_pos

Draws a sprite stretched between four given points and with an alpha blend.

Syntax:

draw_sprite_pos(sprite, subimg, x1, y1, x2, y2, x3, y3, x4, y4, alpha);

Argument | Description
sprite | The index of the sprite to draw.
subimg | The subimg (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
x1 | The first x coordinate.
y1 | The first y coordinate.
x2 | The second x coordinate.
y2 | The second y coordinate.
x3 | The third x coordinate.
y3 | The third y coordinate.
x4 | The fourth x coordinate.
y4 | The fourth y coordinate.
alpha | The alpha of the sprite (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

With this function you can draw a sprite distorted over the area defined by the four corner coordinates. The first two arguments are the sprite to draw and the sub-image of the sprite (the same as in the function draw_sprite) but the next ones are those that define the position of each of the four corners of the bounding box of the given sprite. These should be given in clockwise order, so the first coordinate is the top left, then the top right, then bottom right and finally the bottom left. You can also set a value for the alpha of the sprite to draw it with transparency. The image below illustrates how this function works:

WARNING: The image above is only for illustrative purposes, and if you use this function on a sprite, you will get different results and may experience texture "shearing" due to the way that a sprite is constructed from a quad of primitives.

NOTE: This function is only useful for bitmap sprites and will not work with SWF or JSON (Spine) sprites.

Example:

draw_sprite_pos(sprite_index, image_index, x - 100, y - 50, x - 50, y +150, x + 100, y + 200, x + 100, y, 1);

The above code will draw the sprite associated with the instance running the code distorted around the x / y position of the instance and with a fully opaque alpha.

Back: Drawing Sprites And Backgrounds
Next: draw_sprite_stretched

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite_stretched

Draws a sprite at a given position, stretched.

Syntax:

draw_sprite_stretched(sprite, subimg, x, y, w, h);

Argument | Description
sprite | The index of the sprite to draw.
subimg | The subimg (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.
w | The width of the area the stretched sprite will occupy.
h | The height of the area the stretched sprite will occupy.

Returns: N/A

Description

This function simply takes a sprite resource and stretches it over the given width and height so that it occupies the area. As with draw_sprite you can specify a sprite and a sub-image for drawing, then the x / y position in the room for the sprite to be drawn at and finally a width and a height (which must be pixel values). The image below illustrates how this function works:

NOTE: When drawing with this function, the sprite x offset and y offset are ignored and the sprite will be drawn with the top left corner at the specified x / y position in the room.

Example:

draw_sprite_stretched(sprite_index, image_index, x, y, sprite_width / 2, sprite_height / 2);

This will draw the instances assigned sprite and its sub-image with the left corner at the instance x /y position. Its width is set to the same as the sprite, and the height is the sprite height divided by two.

Back: Drawing Sprites And Backgrounds
Next: draw_sprite_stretched_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite_stretched_ext

Draws a sprite at a given position, stretched, and allows for a custom blend and alpha. This function ignores the sprite's origin.

Syntax:

draw_sprite_stretched_ext(sprite, subimg, x, y, w, h, colour, alpha);

Argument | Description
sprite | The index of the sprite to draw.
subimg | The subimg (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.
w | The width of the area the stretched sprite will occupy.
h | The height of the area the stretched sprite will occupy.
colour | The colour with which to blend the sprite. c_white is to display it normally.
alpha | The alpha of the sprite (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function does exactly the same as the draw_sprite_stretched function with the added ability to set the colour blending and alpha value for the sprite when it is drawn (similar to the function draw_sprite_ext).

NOTE: Colour blending is only recommended for the HTML5 target when WebGL is enabled, although you can still set the blending colour if it is not enabled and it will blend the sprite as normal. However all blending in this way creates a duplicate sprite which is then stored in the cache and used when required. This is far from optimal and if you use multiple colour changes it will slow down your games performance unless you activate WebGL. if you do not wish to use WebGL, then you can set the font cache size to try and limit this should it be necessary using the function sprite_set_cache_size.

Example:

draw_sprite_stretched_ext(sprite_index, image_index, x, y, sprite_width / 2, sprite_height / 2, c_white, 0.5);

This will draw the instances assigned sprite and its sub-image with the left corner at the instance x /y position. Its width is set to the same as the sprite, and the height is the sprite height divided by two. It will also be blended normally but have a partially transparent alpha value.

Back: Drawing Sprites And Backgrounds
Next: draw_sprite_tiled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite_tiled

Draws a sprite at a given position, and tiles it to fill the entire view.

Syntax:

draw_sprite_tiled(sprite, subimg, x, y);

Argument | Description
sprite | The index of the sprite to draw.
subimg | The subimg (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.

Returns: N/A

Description

This function will take a sprite and then repeatedly tile it across the whole view (or room if no view is defined), starting from the coordinates that you give in the function. Tiling is based on the width and height of the sprite as defined by the sprite variables of the instance running the code.

Example:

draw_sprite_tiled(sprite_index, image_index, x, y);

This will draw the instances assigned sprite (sprite_index) and its current frame of animation (image_index) at the instances own x and y position, and tiled horizontally and vertically across the view.

Back: Drawing Sprites And Backgrounds
Next: draw_sprite_tiled_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_sprite_tiled_ext

Draws a sprite at a given position with scaling, blending and alpha, and tiles it to fill the entire view.

Syntax:

draw_sprite_tiled_ext(sprite, subimg, x, y, xscale, yscale, colour, alpha);

Argument | Description
sprite | The index of the sprite to draw.
subimg | The subimg (frame) of the sprite to draw (image_index or -1 correlate to the current frame of animation in the object).
x | The x coordinate of where to draw the sprite.
y | The y coordinate of where to draw the sprite.
xscale | The horizontal scaling of the sprite. A multiplier ' 1 = normal scaling, 0.5 is half etc.
yscale | The vertical scaling of the sprite. A multiplier ' 1 = normal scaling, 0.5 is half etc.
colour | The colour with which to blend the sprite. c_white is to display it normally.
alpha | The alpha of the sprite (from 0 to 1 where 0 is transparent and 1 opaque).

Returns: N/A

Description

This function will take a sprite and then repeatedly tile it across the whole view (or room if no view is defined), starting from the coordinates that you give in the function and with each tile scaled, colour blended and with the alpha that you define (these properties are the same as those used in draw_sprite_ext).

NOTE: Colour blending is only recommended for the HTML5 target when WebGL is enabled, although you can still set the blending colour if it is not enabled and it will blend the sprite as normal. However all blending in this way creates a duplicate sprite which is then stored in the cache and used when required. This is far from optimal and if you use multiple colour changes it will slow down your games performance unless you activate WebGL. if you do not wish to use WebGL, then you can set the font cache size to try and limit this should it be necessary using the function sprite_set_cache_size.

Example:

draw_sprite_tiled_ext(sprite_index, image_index, x, y, 2, 2, c_red, 0.5);

This will draw the instances assigned sprite (sprite_index) and its current frame of animation (image_index) at the instances own x and y position, but scaled to twice the normal size, blended red and with half the normal alpha. The sprite will be tiled horizontally and vertically across the view.

Back: Drawing Sprites And Backgrounds
Next: draw_enable_swf_aa

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Drawing Surfaces

This section deals with drawing surfaces

Surfaces are an incredibly powerful graphic tool that GameMaker: Studio provides you for creating special effects and a whole host of other things. They are relatively simple to use as they are basically a canvas that you draw to instead of the display screen, and this canvas can then be manipulated and changed before being drawn with the functions on this page. For more information on how to create surfaces, draw to them, and the drawbacks associated with their use, please see the section on Surfaces.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

The following functions exist to deal with surfaces

  1. draw_surface
  2. draw_surface_ext
  3. draw_surface_part
  4. draw_surface_part_ext
  5. draw_surface_stretched
  6. draw_surface_stretched_ext
  7. draw_surface_tiled
  8. draw_surface_tiled_ext
  9. draw_surface_general

Back: Drawing

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_surface

Draws the surface at a given position.

Syntax:

draw_surface(id, x, y);

Argument | Description
id | The unique id (index) of the surface to draw.
x | The x position of where to draw the surface.
y | The y position of where to draw the surface.

Returns: N/A

Description

With this function you can draw a surface at a given position within the room, with the top left corner of the image being drawn at the specified x/y position.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

draw_surface(surf, view_xview[0], view_yview[0]);

The above code draws the surface indexed in "surf" at same position as view[0].

Back: Drawing Surfaces
Next: draw_surface_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_surface_ext

Draws a surface with custom scaling, rotation, blending and alpha.

Syntax:

draw_surface_ext(id, x, y, xscale, yscale, rot, colour, alpha);

Argument | Description
id | The unique id (index) of the surface to draw.
x | The x position of where to draw the surface.
y | The y position of where to draw the surface.
xscale | The horizontal scale.
yscale | The vertical scale.
rot | The rotation or angle to draw the surface.
colour | The colour with which to blend the surface.
alpha | The alpha transparency for drawing the surface.

Returns: N/A

Description

This function will draw the given surface as in the function draw_surface but with additional options to change the scale, blending, rotation and alpha of the surface being drawn. Changing these values does not modify the resource in any way (only how it is drawn).

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

draw_surface_ext(surf, 0, 0, 2, 2, 0, c_red, 0.5);

The above code will draw a the surface indexed in the variable "surf" at the (0,0) position in the room, with twice the original scale, blended red and semi transparent.

Back: Drawing Surfaces
Next: draw_surface_part


draw_surface_general

Draws part of a surface at a given position with scaling, rotating, four-corner blending and alpha options.

Syntax:

draw_surface_general(id, left, top, w, h, x, y, xscale, yscale, rot, c1, c2, c3, c4, alpha);

Argument | Description
id | The unique id (index) of the surface to draw.
left | The left position in the surface of the part to be drawn.
top | The top position in the surface of the part to be drawn.
w | The width of the part to be draw, from left.
h | The height of the part to be draw, from top.
x | The x position of where to draw the surface.
y | The y position of where to draw the surface.
xscale | The horizontal scaling to draw the surface with.
yscale | The vertical scaling to draw the surface with.
rot | The rotation or angle to draw the surface with.
c1 | The colour of the top left corner of the surface.
c2 | The colour of the top right corner of the surface.
c3 | The colour of the bottom right corner of the surface.
c4 | The colour of the bottom left corner of the surface.
alpha | The alpha transparency to draw the surface with..

Returns: N/A

Description

This function combines the function draw_surface_ext with the function draw_surface_part, adding in some additional blending options so that each corner of the final surface part can be blended with an individual colour.

NOTE: Gradient blending is not available for the HTML5 target unless WebGL is enabled.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

draw_surface_general(surf, 8, 8, 32, 32, x, y, 2, 0.5, 180, c_white, c_white, c_black, c_black, 1);

This will draw a 32x32 pixel area from 8x8 pixels into the surface. It will be stretched to double its usual width but half its usual height. It will be opaque, and upside down. The top area of the surface will be blended white and hence normal, but the bottom area will be black, meaning the surface will go from normal to silhouette downwards in a smooth gradient.

Back: Drawing Surfaces
Next: draw_surface


draw_surface_part

Draws part of a surface.

Syntax:

draw_surface_part(id, left, top, w, h, x, y );

Argument | Description
id | The unique id (index) of the surface to draw.
left | The left position in the surface of the part to be drawn.
top | The top position in the surface of the part to be drawn.
w | The width of the part to be draw, from left.
h | The height of the part to be drawn, from top.
x | The x position of where to draw the surface.
y | The y position of where to draw the surface.

Returns: N/A

Description

With this function you can draw part of any surface at a given position within the room. As with draw_surface you can specify a surface, but you then need to specify the relative coordinates within the surface of an area to select for drawing. This means that a left position of 0 and a top position of 0 would be the top left corner of the surface and all further coordinates should be taken from that position.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

draw_surface_part(surf, 8, 8, 32, 32, x, y);

This will draw a 32x32 area 8px by 8px in from the top left of the surface indexed in "surf", at the instances (x,y) position.

Back: Drawing Surfaces
Next: draw_surface_part_ext


draw_surface_part_ext

Draws part of a surface but now with scale factors, colour blending and transparency settings.

Syntax:

draw_surface_part_ext(id, left, top, w, h, x, y, xscale, yscale, colour, alpha);

Argument | Description
id | The unique id (index) of the surface to draw.
left | The left position in the surface of the part to be drawn.
top | The top position in the surface of the part to be drawn.
w | The width of the part to be draw, from left.
h | The height of the part to be drawn, from top.
x | The x position of where to draw the surface.
y | The y position of where to draw the surface.
xscale | The horizontal scaling the part should be drawn with.
yscale | The vertical scaling the part should be drawn with.
colour | The colour blending the part should be drawn with.
alpha | The alpha transparency the part should be drawn with.

Returns: N/A

Description

This function will draw a part of the chosen surface at the given position following the same rules as per draw_surface_part, only now you can scale the part, blend a colour with it, or change its alpha when drawing it to the screen (the same as when drawing a surface with draw_surface_ext).

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

draw_surface_part_ext(surf, 8, 8, 32, 32, x, y, 2, 0.5, c_black, 1);

This will draw a 32x32 pixel area from 8x8 pixels into the surface indexed in the variable "surf". It will be stretched to double its usual width but half its usual height. It will be opaque and it will be blended with black (turning it into a silhouette).

Back: Drawing Surfaces
Next: draw_surface_stretched


draw_surface_stretched

Draws the surface stretched to an indicated region.

Syntax:

draw_surface_stretched(id, x, y, w, h);

Argument | Description
id | The unique id (index) of the surface to draw.
x | The x position of where to draw the surface.
y | The y position of where to draw the surface.
w | The width at which to draw the surface.
h | The height at which to draw the surface.

Returns: N/A

Description

This function simply takes a surface and stretches it over the given width and height so that it occupies the area. As with draw_surface you can specify a surface and then the x / y position in the room for the surface to be drawn at and finally a width and a height (which must be pixel values).

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

draw_surface_stretched(surf, 10, 10, 100, 100);

This will draw the surface indexed in the variable "surf" with its left corner at (10,10). Its width and height are both set to 100, which is how much space it will occupy regardless of the surface's actual width and height.

Back: Drawing Surfaces
Next: draw_surface_stretched_ext


draw_surface_stretched_ext

Draws the surface stretched to an indicated region with colour and alpha blending.

Syntax:

draw_surface_stretched_ext(id, x, y, w, h, colour, alpha );

Argument | Description
id | The unique id (index) of the surface to draw.
x | The x position of where to draw the surface.
y | The y position of where to draw the surface.
w | The width at which to draw the surface.
h | The height at which to draw the surface.
colour | The colour with which to colour the surface.
alpha | The alpha with which to blend the surface.

Returns: N/A

Description

This function does exactly the same as the draw_surface_stretched function with the added ability to set the colour blending and alpha value for the surface when it is drawn (similar to the function draw_surface_ext).

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

draw_surface_stretched_ext(surf, x, y, 200, 200, c_white, 0.5);

This will draw the given surface with its left corner at the instances x/y position and it will be stretched to occupy an area of 200x200 pixels with no blending, but partial transparency.

Back: Drawing Surfaces
Next: draw_surface_tiled


draw_surface_tiled

Draws a surface tiled so that it fills the entire room.

Syntax:

draw_surface_tiled(id, x, y);

Argument | Description
id | The unique id (index) of the surface to draw.
x | The x position of where to draw the surface.
y | The y position of where to draw the surface.

Returns: N/A

Description

This function will take a surface and then repeatedly tile it across the whole room, starting from the coordinates that you give in the function.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

draw_surface_tiled(surf, x, y);

This will draw the surface indexed in "surf" at the instances own x and y position, and tiled in every direction in the room.

Back: Drawing Surfaces
Next: draw_surface_tiled_ext


draw_surface_tiled_ext

Draws a surface at a given position with scaling, blending and alpha, and tiles it to fill the entire room.

Syntax:

draw_surface_tiled_ext(id, x, y, xscale, yscale, colour, alpha);

Argument | Description
id | The unique id (index) of the surface to draw.
x | The x coordinate of where to draw the surface.
y | The y coordinate of where to draw the surface.
xscale | The horizontal scaling of the surface.
yscale | The vertical scaling of the surface.
h | The height of the area the stretched surface will occupy.
colour | The colour with which to blend the surface.
alpha | The alpha of the surface.

Returns: N/A

Description

This function will take a surface and then repeatedly tile it across the whole room, starting from the coordinates that you give in the function and with each tile scaled, colour blended and with the alpha that you define (these properties are the same as those used in draw_surface_ext).

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

draw_surface_tiled_ext(surf, x, y, 2, 2, c_red, 0.5);

This will draw the surface indexed in "surf" at the instances own x and y position, double its stored size and tiled in every direction in the room, as well as blended with the colour red and partially transparent.

Back: Drawing Surfaces
Next: draw_surface_general


Drawing Text

This section has all the functions for drawing text

There are a number of functions available to you for drawing text in various forms. It should be noted that some of these functions change the text colours and sizes in a dynamic way when being drawn, but when working with HTML5 or devices, these functions can slow down your game or look poor and so it may be better to have various sized font resources rather than use scaled drawing, or have large font resources and then draw them scaled down rather than up. Also, if you need to colour large blocks of text it is better to use the draw_set_colour and draw_set_alpha functions first and use the simple draw_text functions.

The following functions exist for dealing with fonts and text:

  1. draw_set_font
  2. draw_set_halign
  3. draw_set_valign
  4. draw_text
  5. draw_text_ext
  6. draw_text_colour
  7. draw_text_transformed
  8. draw_text_ext_colour
  9. draw_text_ext_transformed
  10. draw_text_transformed_colour
  11. draw_text_ext_transformed_colour
  12. draw_highscore

Back: Drawing

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_highscore

Draws the highscore table string in the room filling the indicated box size using the currently set font and draw colour.

Syntax:

draw_highscore( x1, y1, x2, y2 );

Argument | Description
x1 | The x coordinate of the left of the highscore rectangle.
y1 | The y coordinate of the top of the highscore rectangle.
x2 | The x coordinate of the right of the highscore rectangle.
y2 | The y coordinate of the bottom of the highscore rectangle.

Returns: N/A

Description

This simple function will draw the current list of internally stored high scores using the currently set font, colour and alpha values within the specified rectangle. You provide the coordinates for the upper left corner and lower right corner of the rectangular area to draw the text, and GameMaker: Studio will take care of the rest, with spacing and position being done automatically.

Example:

draw_highscore(100, 100, room_width - 100, room_height - 100);

This would draw the highscore table in a rectangle in the middle of the room with a 100px border.

Back: Drawing Text
Next: draw_set_font

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_font

Sets the font used to draw text.

Syntax:

draw_set_font(font);

Argument | Description
font | The name of the font to use.

Returns: N/A

Description

This function will set the font to be used for all further text drawing. This font must have been added into the font assets of the game or have been created using either the font_add or font_add_sprite. You may also set this to -1 to default to drawing text using a 12point Arial font.

Example:

draw_set_colour(c_blue);
draw_set_font(fnt_Game);
draw_text(200, 200, "Hello World" );

The above code will draw the given text using the font indexed in the variable "fnt_Game" and coloured blue.

Back: Drawing Text
Next: draw_set_halign

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_halign

Aligns any subsequently drawn text horizontally.

Syntax:

draw_set_halign(halign);

Argument | Description
halign | Horizontal alignment.

Returns: N/A

Description

This function is used to align text along the horizontal axis and changing the horizontal alignment will change the position and direction in which all further text is drawn with the default value being fa_left. The following constants are accepted:

Constant | Alignment
fa_left |
fa_center |
fa_right |

Example:

draw_set_halign(fa_left);
draw_text(100, 32, "Score: " + string(score));
draw_set_halign(fa_right);
draw_text(room_width - 100, 32, "Health: " + string(health));

The above code will draw two strings on the same line, with the score being left-hand aligned and the health being right-hand aligned.

Back: Drawing Text
Next: draw_set_valign

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_set_valign

Aligns any subsequently drawn text vertically.

Syntax:

draw_set_valign(valign);

Argument | Description
valign | Vertical alignment.

Returns: N/A

Description

This function is used to align text along the vertical axis and changing the vertical alignment will change the position and direction in which all further text is drawn, with the default value being fa_top. The following constants are accepted:

Constant | Alignment
fa_top |
fa_middle |
fa_bottom |

Example:

draw_set_halign(fa_center);
draw_set_valign(fa_middle);
draw_text(100, 32, "Score: " + string(score));

The above code will draw the score centered around the very center of the text.

Back: Drawing Text
Next: draw_text

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_text

Draw a string at a given position.

Syntax:

draw_text(x, y, string);

Argument | Description
x | The x coordinate of the drawn string.
y | The y coordinate of the drawn string.
string | The string to draw.

Returns: N/A

Description

With this function you can draw any string at any position within the room (for drawing real numbers you should use the string function to convert them into text). To combine strings you can use + (see example below), you can also use # to add a line break to the string (should you need to display the # symbol, then you should precede it with a backslash like this "this will draw a \#") and you can also draw quotations by using inverted commas (for example 'I said "Hello"...'). The colour of the text and the alpha are governed by the current base alpha and colour values as set by draw_set_alpha and draw_set_colour

NOTE: The actual position of the text will be influenced by the alignment values set by draw_set_halign and draw_set_valign.

Example:

draw_text(x, y, "Hello, " + global.Name + "!#I hope you are well!");

The above code will draw a string at the instance x/y position, which will use the string stored in the global variable "Name" and split it over two lines.

Back: Drawing Text
Next: draw_text_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_text_colour

Draw a string at a given position with a colour gradient.

Syntax:

draw_text_colour(x, y, string, c1, c2, c3, c4, alpha);

Argument | Description
x | The x coordinate of the drawn string.
y | The y coordinate of the drawn string.
string | The string to draw.
c1 | The colour for the top left of the drawn text.
c2 | The colour for the top right of the drawn text.
c3 | The colour for the bottom right of the drawn text.
c4 | The colour for the bottom left of the drawn text.
alpha | The alpha for the text.

Returns: N/A

Description

This function will draw text in a similar way to draw_text only now you can choose the colours to use for colouring the text as well as the alpha value, and these new values will be used instead of the base drawing colour and alpha.

NOTE: Gradient blending is not available for the HTML5 target unless WebGL is enabled, although you can still set the blending colours and it will blend the font with the first given colour. However all blending in this way creates a duplicate font which is then stored in the cache and used when required, which is far from optimal and if you use multiple colour changes it will slow down your games performance. You can set the font cache size to try and limit this should it be necessary using the function font_set_cache_size.

Example:

draw_set_colour(c_white);
draw_text(100, 100, "Health");
draw_text_colour(100, 200, string(health), c_lime, c_lime, c_green, c_green, 1);

The above code will draw two sections of text on the same line, with the first text being drawn white (as that is the base drawing colour) and the second text being drawn with a lime green to normal green gradient.

Back: Drawing Text
Next: draw_text_transformed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_text_ext

Draws a string at a given position with a specific spacing and within a limited area.

Syntax:

draw_text_ext(x, y, string, sep, w);

Argument | Description
x | The x coordinate of the drawn string.
y | The y coordinate of the drawn string.
string | The string to draw.
sep | The distance in pixels between lines of text.
w | The maximum width in pixels of the string before a line break.

Returns: N/A

Description

This function will draw text in a similar way to draw_text only now you can set the space between each line of text - should the text occupy more than one line - and limit the width (in pixels) of the string per line so that should any line exceed this value, GameMaker: Studio will automatically split the text to the next line. A value of -1 for the line separation argument will default to a separation based on the height of the "M" character in the chosen font.

Example:

draw_text_ext(100, 50, keyboard_string, 3, 300);

The above code will draw whatever text the user types into the keyboard, splitting it onto new lines every time the string length for that line exceeds 300 pixels. the code will also maintain a separation of 3 pixels between lines should this occur.

Back: Drawing Text
Next: draw_text_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_text_ext_colour

Draws a string with custom spacing and colours.

Syntax:

draw_text_ext_colour(x, y, string, sep, w, c1, c2, c3, c4, alpha);

Argument | Description
x | The x coordinate of the drawn string.
y | The y coordinate of the drawn string.
string | The string to draw.
sep | The distance in pixels between lines of text.
w | The maximum width in pixels of the string before a line break.
c1 | The colour for the top left of the drawn text.
c2 | The colour for the top right of the drawn text.
c3 | The colour for the bottom right of the drawn text.
c4 | The colour for the bottom left of the drawn text.
alpha | The alpha for the text.

Returns: N/A

Description

This function is a combination of the base draw_text function with the draw_text_ext and draw_text_colour functions, permitting you to define gradient colours for text as well as the line spacing and maximum width per line all together.

NOTE: Gradient blending is not available for the HTML5 target unless WebGL is enabled, although you can still set the blending colours and it will blend the font with the first given colour. However all blending in this way creates a duplicate font which is then stored in the cache and used when required, which is far from optimal and if you use multiple colour changes it will slow down your games performance. You can set the font cache size to try and limit this should it be necessary using the function font_set_cache_size.

Example:

draw_text_ext_colour(200, 200, keyboard_string, 5, 300, c_blue, c_blue, c_navy, c_navy, 1);

The above code will draw whatever text the user types into the keyboard, splitting it onto new lines every time the string length for that line exceeds 300 pixels. the code will also maintain a separation of 5 pixels between lines should this occur. Each line of the text will be coloured using a blue gradient, with light blue at the top and dark blue at the bottom.

Back: Drawing Text
Next: draw_text_ext_transformed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_text_ext_transformed

Draws a string with custom spacing and scaling.

Syntax:

draw_text_ext_transformed(x, y, string, sep, w, xscale, yscale, angle);

Argument | Description
x | The x coordinate of the drawn string.
y | The y coordinate of the drawn string.
string | The string to draw.
sep | The distance in pixels between lines of text.
w | The maximum width in pixels of the string before a line break.
xscale | The horizontal scale.
yscale | The vertical scale.
angle | The angle of the text.

Returns: N/A

Description

This function is a combination of the base draw_text function with the draw_text_ext and draw_text_transformed functions, permitting you to scale and rotate text while maintaining a specific line spacing and maximum width per line. Note that the "width" argument is based on a scale of 1, so if the scale is different, this value should be changed proportionally. For example, if the base width for a line break is 300 and you set the scale to 2, then the text will appear wrong, over-running the given width. Instead you should have set the width to 150 to compensate the scaling.

Example:

draw_set_halign(fa_center);
draw_set_valign(fa_middle);
image_angle += 1;
draw_text_ext_transformed(room_width / 2, room_height / 2, keyboard_string, 10, 300, 2, 2, image_angle);

The above code will draw the given text in the middle of the room, with a maximum string length of 300 pixels, a spacing between each line of 10 pixels, spinning round and scaled to twice its original size.

Back: Drawing Text
Next: draw_text_transformed_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_text_ext_transformed_colour

Draws a string with any given colour, scale, angle or spacing attributes that you define.

Syntax:

draw_text_ext_transformed_colour(x, y, string, sep, w, xscale, yscale, angle, c1, c2, c3, c4, alpha);

Argument | Description
x | The x coordinate of the drawn string.
y | The y coordinate of the drawn string.
string | The string to draw.
sep | The distance in pixels between lines of text.
w | The maximum width in pixels of the string before a line break.
xscale | The horizontal scale.
yscale | The vertical scale.
angle | The angle of the text.
c1 | The colour for the top left of the drawn text.
c2 | The colour for the top right of the drawn text.
c3 | The colour for the bottom right of the drawn text.
c4 | The colour for the bottom left of the drawn text.
alpha | The alpha for the text.

Returns: N/A

Description

This function is a combination of the base draw_text function with the draw_text_ext, draw_text_transformed and draw_text_colour functions. As such, this is the most general of all functions for drawing text and gives a large amount of flexibility when drawing. Note that the "width" argument is based on a scale of 1, so if the scale is different, this value should be changed proportionally. For example, if the base width for a line break is 300 and you set the scale to 2, then the text will appear wrong, over-running the given width. Instead you should have set the width to 150 to compensate the scaling.

NOTE: Gradient blending is not available for the HTML5 target unless WebGL is enabled, although you can still set the blending colours and it will blend the font with the first given colour. However all blending in this way creates a duplicate font which is then stored in the cache and used when required, which is far from optimal and if you use multiple colour changes it will slow down your games performance. You can set the font cache size to try and limit this should it be necessary using the function font_set_cache_size.

Example:

draw_set_halign(fa_center);
draw_set_valign(fa_middle);
draw_text_ext_transformed_colour(200, 200, "My name is" + global.name +".", 20, 200, 0.5, 0.5, 180, c_blue, c_blue, c_navy, c_navy, 1);

This will draw the given text with a blue to dark blue downward gradient, at position (200,200) in the room, rotated to be upside down and at half the normal point size of the font. There will be 20 pixels between each line should there be more than one line drawn and each line will have a maximum width of 200 pixels.

Back: Drawing Text
Next: draw_set_font

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_text_transformed

Draws a string with scaling and rotation.

Syntax:

draw_text_transformed(x, y, string, xscale, yscale, angle);

Argument | Description
x | The x coordinate of the drawn string.
y | The y coordinate of the drawn string.
string | The string to draw.
xscale | The horizontal scale (default 1).
yscale | The vertical scale(default 1).
angle | The angle of the text.

Returns: N/A

Description

This function will draw text in a similar way to draw_text only now you can choose to scale the text along the horizontal or vertical axis (effectively stretching or shrinking it) and also have GameMaker: Studio draw it at an angle (where 0 is normal and every degree over 0 rotates the text anti-clockwise).

Example:

draw_set_halign(fa_center);
draw_set_valign(fa_middle);
image_angle += 1;
draw_text_transformed(room_width / 2, room_height / 2, "GAME OVER!", 2, 2, image_angle);

The above code will draw the given text in the middle of the room, spinning round and scaled to twice its original size.

Back: Drawing Text
Next: draw_text_ext_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


draw_text_transformed_colour

Draws a string with scaling and colour.

Syntax:

draw_text_transformed_colour(x, y, string, xscale, yscale, angle, c1, c2, c3, c4, alpha);

Argument | Description
x | The x coordinate of the drawn string.
y | The y coordinate of the drawn string.
string | The string to draw.
xscale | The horizontal scale.
yscale | The vertical scale.
angle | The angle of the text.
c1 | The colour for the top left of the drawn text.
c2 | The colour for the top right of the drawn text.
c3 | The colour for the bottom right of the drawn text.
c4 | The colour for the bottom left of the drawn text.
alpha | The alpha for the text.

Returns: N/A

Description

This function is a combination of the base draw_text function with the draw_text_transformed and draw_text_colour functions, permitting you to scale and rotate text as well as colour it with a gradient fill and change its alpha value, ignoring the base alpha and colour settings for drawing.

NOTE: Gradient blending is not available for the HTML5 target unless WebGL is enabled, although you can still set the blending colours and it will blend the font with the first given colour. However all blending in this way creates a duplicate font which is then stored in the cache and used when required, which is far from optimal and if you use multiple colour changes it will slow down your games performance. You can set the font cache size to try and limit this should it be necessary using the function font_set_cache_size.

Example:

draw_set_halign(fa_center);
draw_set_valign(fa_middle);
image_angle += 1;
draw_text_transformed_colour(room_width / 2, room_height / 2, keyboard_string, 2, 2, image_angle, c_red, c_red, c_yellow, c_yellow, 0.5);

The above code will draw the given text in the middle of the room, spinning round and scaled to twice its original size, with a colour gradient going from yellow to red as well as an alpha of 0.5.

Back: Drawing Text
Next: draw_text_ext_transformed_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


File Handling

This section deals with the different types of functions available for file handling

At some point while creating your game it will be necessary to store information externally and be able to retrieve this information. For example, you may wish to store login details, or hi-scores, or maybe the progression of the player through your levels. Whatever the reason, you will need to know how to use the different file functions that are available to you when working with GameMaker: Studio.

It is very important to realise that GameMaker: Studio is Sandboxed, meaning that there are a number of limits and minor complications when using the file system functions that are available, and it is worth noting too that the file system will work slightly differently depending on the platform you are targeting. For more information this, please see the following section:

  1. File System Limits

If you have been granted permission by Steam to use their dedicated API with your game, you will find that there is also a new set of file functions available to you. These are explained in the Steam API section of this manual.

File Systems

Information on the different file functions can be found in the following pages:

  1. File System Functions
  2. Ini Files
  3. Text Files
  4. Binary files

Directories

Obviously, there will be moments when you need to reference the directory in which files are store and GameMaker: Studio also has some special functions relating to the different possible directories that you may need:

  1. directory_exists
  2. directory_create
  3. directory_destroy
  4. temp_directory
  5. working_directory
  6. program_directory

Encoding

When dealing with external files, there is always the possibility that the end user could open and change the information that they contain, and so change your game. This can result in broken game-play elements or fraudulent scores on-line (for example), and so GameMaker: Studio provides you with some basic encoding functions as well as functions to perform md5 checks on strings and files to make sure that they have maintained their integrity before being used. There are also two functions supplied for encoding and decoding JSON (JavaScript Object Notation) format strings.

  1. base64_encode
  2. base64_decode
  3. json_encode
  4. json_decode
  5. md5_string_utf8
  6. md5_string_unicode
  7. md5_file
  8. sha1_string_utf8
  9. sha1_string_unicode
  10. sha1_file

NOTE: Encoding is NOT encryption! A base64 encoding renders the file unreadable to the naked eye and will require an effort on behalf of the user to decode, but it is not secure from hacking. It is recommended that you mix those functions with your own encryption (there are many forms of encryption and scripts are available on the internet).

Zip Files

GameMaker: Studio permits you to open a zip file and extract its contents to the local storage area for your game, using the following functions (useful should you have downloadable content for your game):

  1. zip_unzip

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


base64_decode

Decode a base64 format string.

Syntax:

base64_decode(string)

Argument | Description
string | The string to decode.

Returns: String

Description

This function will convert a string encoded previously using base64 format, into standard text. Base64 is a commonly used encoding scheme that is often used for any media that needs to be stored or transferred over the internet as text, and renders the output unreadable to the human eye.

Example:

var str, file;
str = base64_encode(game_data);
file = file_text_open_read("save.txt");
str = file_text_read_string(file);
level_data = base64_decode(str);
file_text_close(file);

The above code will open a text file and read a string from it into the local variable "str". This string is then decoded and the result stored in the instance variable "level_data".

Back: File Handling
Next: json_encode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


base64_encode

Encode a string using base64 format.

Syntax:

base64_encode(string)

Argument | Description
string | The string to encode.

Returns: String

Description

This function will convert a string into a base64 format encoded string. This is a commonly used encoding scheme that is often used for any media that needs to be stored or transferred over the internet as text, and renders the output unreadable to the human eye.

Example:

var str, file;
str = base64_encode(game_data);
file = file_text_open_write("save.txt");
file_text_write_string(file, str);
file_text_close(file);

The above code will covert the string stored in "game_data" into a base64 encoded string which is then stored in an external text file.

Back: File Handling
Next: base64_decode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


directory_create

Creates a directory with the given name.

Syntax:

directory_create(dname)

Argument | Description
dname | The name of the directory to create.

Returns: N/A

Description

This function will creates a directory with the given name in the sandboxed local save area.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

if !directory_exists("Games")
{
directory_create("Games");
}

This will check to see if the specified directory exists in the local data folder and, if it does not, it creates it for you.

Back: File Handling
Next: directory_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


directory_destroy

Destroy (delete) a directory with the given name.

Syntax:

directory_destroy(dname)

Argument | Description
dname | The name of the directory to remove.

Returns: N/A

Description

This function will remove a directory with the given name in the sandboxed local save area.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

if directory_exists("DLC")
{
directory_destroy("DLC");
}

This will check to see if the specified directory exists in the local data folder and, if it does, it is removed.

Back: File Handling
Next: temp_directory

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


directory_exists

Returns whether the indicated directory exists.

Syntax:

directory_exists(dname)

Argument | Description
dname | The name of the directory to look for.

Returns: Boolean.

Description

This function will return true if the indicated directory exists or false if it does not. The specified name must include the full path, not a relative path and you cannot access any directories from out-with the game bundle as all games are sandboxed.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

if directory_exists(working_directory + "\Saves\")
{
file = file_find_first(working_directory + "\Saves\*.doc", fa_readonly);
}

This will check to see if the specified directory exists then, if it does, go there and return the first "read only" doc file found.

Back: File Handling
Next: directory_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


File System Limits

Here you can find information on how the file system works and its limits.

When using the file system functions included with GameMaker: Studio it is vitally important to know exactly how everything works and what things are going on behind the scenes. To that end, this section is designed to explain and clarify exactly how things are stored, where they are stored and what possible limits or workarounds there may be to this system.

Sandboxing

The first (and most important) thing to note about the file functions is that they are limited (in general) to the sandbox. What this means is that GameMaker: Studio cannot save or load files from anywhere that is not part of the game bundle or the local storage for the device without explicit input from the user, and even then this input is limited to only Windows and Mac target platforms.

To understand the sandbox first of all you need to understand that there are two distinct areas for files:

  1. The File Bundle - this is where all the files that are packaged with the executable game are stored, including the files that you have added to the Included Files resource list from the GameMaker: Studio IDE (which are the external files that you want packaged with the game).

  2. The Save Area - this is an area of device storage that can be safely written to by the game and the game is guaranteed that this is a writable area.

The following diagram may help you to visualise this better:

NOTE: You can never write to the File Bundle directory.

Using the File Functions

The two target areas (Bundle directory and the local storage area) are available on each target platform, but on each one they work slightly differently. However GameMaker: Studio has abstracted out the main essence of what can and can't be done, making it easier to re-target games to multiple environments.

To start with, you should understand what is meant when we talk of the working_directory. This is a synonym for the two possible save locations (as illustrated by the diagram above) and when you use that directory it will do one of two things depending on whether you are reading or writing, and whether the file you are reading from has been changed or not:

  1. Reading Operations - working_directory will first check the save area to see if the file being accessed is there, and if it is uses that. However if the file does not exists in the save area, it then checks the file bundle area and uses that (if the file being looked for is an included file with your game).
  2. Writing Operations - This can only happen in the save area.

Using these two simple rules we can now see how the following functions work (these are examples to help you to visualise the process for the different functions available):

  • directory_create (and the other directory functions) will only work in the save area.
  • the file system functions will return information on files from both the bundle and the save area, but will only write to the save area.
  • the functions for writing text, binary or ini files will create a new file in the save area if one does not already exist, copying over any information from the original files included with the game bundle should they exist.

Saving And Loading Outside The Sandbox

On the Windows platform there is one way to save and load files from outside of the sandbox and that is using the functions get_open_filename and get_save_filename. Both of these functions will require that the user select an area for loading and saving and the return string can then be used in the rest of the file functions to bypass the sandbox.

Platform Specific Saving/Loading

When working with GameMaker: Studio, you should know that each target platform has its own save area where files and directories can be written to and read from. Below is a list of those areas for each target:

  • Windows - Windows has all files in the %localappdata%\<Game Name> directory (on Windows 7 this is the /Users/<User Name>/AppData/Local/<Game Name> directory).

  • Mac OS - Storage will depend on whether the application is sandboxed or not (following Apples rules, with the path usually being ~/Library/Application Support/<Game Name>).

  • Ubuntu (Linux) - Files are stored in the Home/.config/gamename where "Home" is the users home directory - /home/<username>
  • HTML5 - Everything is done through the local storage.

  • iOS - Storage is the standard location (as viewed through iTunes).

  • Android - Files are in the standard location (which is invisible unless the device is rooted) /data/data/<package name>.

While on some platforms you can use the file name on its own to access included files, it is worth noting that on devices (Android, iOS) you must use the prefix of the working_directory to access stored files as using just the relative path will not work. It is also worth noting that the HTML5 target module has a limit on local storage (which can be between 1MB and 5MB depending on the browser) meaning that you will not be permitted to save large sprites, screenshots etc....

Back: The File System

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


json_decode

This function takes a JSON object string and decode it as a ds_map.

Syntax:

json_decode(string)

Argument | Description
string | The JSON format string that you are passing to the function for decoding

Returns: ds_map id or -1 if it fails

Description

JSON (JavaScript Object Notation) is a lightweight data-interchange format which is easy for to read and write, for both people and machines. It is built on two basic structures:

  • A collection of name/value pairs, called a ds_map in GameMaker: Studio but also known as a "dictionary" or "object".
  • An ordered list of values, called a ds_list in GameMaker: Studio but this can also be called an "array" or "sequence".

With this function, you can decode a piece of JSON and convert it into a ds_map, ready for use in GameMaker: Studio. If the JSON to be decoded requires a hierarchy of lists and maps within the central ds_map, these are decoded too and also created for you, using the following rules (note that these rules apply to the top-level structure only):

  • Json is a single value - returns a ds_map with a single entry "default" that is the value
  • Json is an array of objects or values - returns a ds_map with a single entry "default" that is a ds_list of the objects or values
  • Json is an object - returns a ds_map that has the object entries in it

NOTE: When decoding arrays, there is a map with the key "default" ONLY when an array is the top level structure, and ONLY for that top-level array. Internal lists decode directly to ds_lists without being enclosed in a ds_map.

Normally you would know what keys the JSON decodes to, but if not then you can use the ds_map_size, ds_map_find_first and ds_map_find_next functions to parse the map and get the necessary information.

NOTE: GameMaker: Studio creates the necessary ds_maps and lists from the JSON, and for cleaning up you only need to delete the top level map or list and GameMaker: Studio will automatically delete from memory all the maps and lists underneath.

Example:

var resultMap = json_decode(requestResult);
var list = ds_map_find_value(resultMap, "default");
var size = ds_list_size(list);
for (var n = 0; n < ds_list_size(list); n++;)
{
var map = ds_list_find_value(list, n);
var curr = ds_map_find_first(map);
while (is_string(curr))
{
global.Name[n] = ds_map_find_value(map, "name");
curr = ds_map_find_next(map, curr);
}
ds_map_destroy(map);
}
ds_list_destroy(list);
ds_map_destroy(resultMap);

The above code will decode a JSON string and parse it to generate a global array.

Back: File Handling
Next: md5_string_utf8

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


json_encode

This function encode a ds_map into a JSON format string.

Syntax:

json_encode(map)

Argument | Description
map | a ds_map with the information to encode

Returns: string

Description

JSON (JavaScript Object Notation) is a lightweight data-interchange format which is easy for to read and write, for both people and machines. It is built on two basic structures:

  • A collection of name/value pairs, called a ds_map in GameMaker: Studio but also known as a "dictionary" or "object".
  • An ordered list of values, called a ds_list in GameMaker: Studio but this can also be called an "array" or "sequence".

json_encode takes a ds_map that you have previously created and encoded as a JSON string which you can then use as (for example) part of an http_post_string() call, or so it can be stored externally, written to a file.

NOTE: The hierarchal functionality of JSON is available through special ds_map and ds_list functions, so you are able to encode sub-lists and maps.

Example:

var hiscore_map, i, str;
hiscore_map = ds_map_create();
for (i = 0; i < 10; i ++;)
{
ds_map_add(name[i], score[i]);
}
str = json_encode(hiscore_map);
get[0] = http_post_string("http://www.angusgames.com/game?game_id=" + string(global.game_id), str)
ds_map_destroy(hiscore_map);

The above code creates a ds_map and then loops through the name and score arrays, adding each key/value pair to the new map. Next, this map is encoded using json_encode and stored as a string in the variable "str". This string is then sent to a web server using http_post_string and the ds_map is destroyed to prevent a memory leak as it is no-longer needed.

Back: File Handling
Next: json_decode()


md5_file

Returns an MD5 hash for the given file.

Syntax:

md5_file(filename)

Argument | Description
filename | The file to generate the MD5 hash for.

Returns: String

Description

In cryptography, MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value and has been employed in a wide variety of security applications. It is also commonly used to check the integrity of files and strings. This function will take the given file and generate a unique MD5 for that file which can then be stored for later use.

Example:

hash = md5_file(working_directory + "\game_data.ini")

The above code will generate an MD5 hash for the specified file and store the returned value in the variable "hash".

Back: File Handling
Next: sha1_string_utf8

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


md5_string_unicode

Returns an MD5 of the unicode format input string.

Syntax:

md5_string_unicode(string)

Argument | Description
string | The string to hash.

Returns: String

Description

In cryptography, MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value and has been employed in a wide variety of security applications. It is also commonly used to check the integrity of files and strings. This function will take an input unicode string (which is 16bits for each char) and return the 32-character hexadecimal MD5 hash that is unique to that string. In this way you can generate a secure key which can be stored and used to check the integrity of the information being sent to (or received from) an external server (for example).

NOTE: There are two formats for the MD5 encoding, UTF-8 and unicode. Both are provided to facilitate communication with different server setups, but the most common to use is unicode.

Example:

var hash, str;
str = base64_encode(game_data);
hash = md5_string_unicode(str);
http_get("http://www.MacSweeneyGames.com/CatchTheHaggis/gamedata?hash=" + hash);
http_get("http://www.MacSweeneyGames.com/CatchTheHaggis/gamedata?data=" + str);

The above code will base64 encode a string and then generate an MD5 hash. Finally, both the hash and the encoded string are sent to a server.

Back: File Handling
Next: md5_file

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


md5_string_utf8

Returns an MD5 of the utf8 format input string.

Syntax:

md5_string_utf8(string)

Argument | Description
string | The string to hash.

Returns: String

Description

In cryptography, MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value and has been employed in a wide variety of security applications. It is also commonly used to check the integrity of files and strings. This function will take an input UTF-8 string (which has a variable number of bytes per character) and return the 32-character hexadecimal MD5 hash that is unique to that string. In this way you can generate a secure key which can be stored and used to check the integrity of the information being sent to (or received from) an external server (for example).

NOTE: There are two formats for the MD5 encoding, UTF-8 and unicode. Both are provided to facilitate communication with different server setups, but the most common to use is unicode.

Example:

var hash, str;
str = json_encode(hiscore_map);
hash = md5_string_utf8(str);
ini_open("local.ini");
ini_write_string("info", "0", hash);
ini_close();
get[0] = http_post_string("http://www.MacSweeney Games.com/CatchTheHaggis?game_hiscores=" + string(global.game_id), str)

The above code will encode a ds_map into a JSON string. An MD5 hash is then generated and stored in an ini file so that this can later be used to check the integrity of the JSON should the same information be received later form the server. The JSON is then sent.

Back: File Handling
Next: md5_string_unicode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


program_directory

Directory in which the game executable is stored.

Syntax:

program_directory

Returns: String.

Description

This will return the directory where the game executable is stored. However this may not always be useful, particularly as some devices run the exe from a *.zip file, so this would return the same no matter where the game is actually running from.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

dir = program_directory;

This will store the directory where the executable is stored in a variable.

Back: File Handling
Next: base64_encode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sha1_file

Returns a sha1 hash for the given file.

Syntax:

sha1_file(filename)

Argument | Description
filename | The file to generate the sha1 hash for.

Returns: String

Description

In cryptography, SHA-1 is a cryptographic hash function designed by the United States National Security Agency and is employed in several widely used applications popular Git where it is used to check for file changes, and the protocols TLS and SSL, PGP, SSH, S/MIME, and IPsec. This function will take an input file and return a 160 bit message digest in ASCII format unique to that file to be used for integrity verification at any later date.

Example:

hash = sha1_file(working_directory + "\game_data.ini")

The above code will generate a sha1 hash for the specified file and store the returned value in the variable "hash".

Back: File Handling
Next: base64_encode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sha1_string_unicode

Returns a sha1 hash of the unicode format input string.

Syntax:

sha1_string_unicode(string)

Argument | Description
string | The string to hash.

Returns: String

Description

In cryptography, SHA-1 is a cryptographic hash function designed by the United States National Security Agency and is employed in several widely used applications and protocols like the popular Git where it is used to check for file changes. This function will take an input unicode string and returns a 160 bit message digest in ASCII format, for example:

sha1 input string = "The quick brown fox jumps over the lazy dog"
sha1 output hash = "2fd4e1c6 7a2d28fc ed849ee1 bb76e739 1b93eb12"

In this way you can generate a secure key which can be stored and used to check the integrity of the information being sent to (or received from) an external server (for example).

NOTE: There are two formats for the sha1 encoding, UTF-8 and unicode. Both are provided to facilitate communication with different server setups, but the most common to use is unicode.

Example:

var hash, str;
str = base64_encode(game_data);
hash = sha1_string_unicode(str);
http_get("http://www.MacSweeneyGames.com/CatchTheHaggis/gamedata?hash=" + hash);
http_get("http://www.MacSweeneyGames.com/CatchTheHaggis/gamedata?data=" + str);

The above code will base64 encode a string and then generate a sha1 hash. Finally, both the hash and the encoded string are sent to a server.

Back: File Handling
Next: sha1_file

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sha1_string_utf8

Returns a sha1 hash of the utf8 format input string.

Syntax:

sha1_string_utf8(string)

Argument | Description
string | The string to hash.

Returns: String

Description

In cryptography, SHA-1 is a cryptographic hash function designed by the United States National Security Agency and is employed in several widely used applications and protocols like the popular Git where it is used to check for file changes. This function will take an input UTF-8 string (which has a variable number of bytes per character) and returns a 160 bit message digest in ASCII format, for example:

sha1 input string = "The quick brown fox jumps over the lazy dog"
sha1 output hash = "2fd4e1c6 7a2d28fc ed849ee1 bb76e739 1b93eb12"

In this way you can generate a secure key which can be stored and used to check the integrity of the information being sent to (or received from) an external server (for example).

NOTE: There are two formats for the sha1 encoding, UTF-8 and unicode. Both are provided to facilitate communication with different server setups, but the most common to use is unicode.

Example:

var hash, str;
str = json_encode(hiscore_map);
hash = sha1_string_utf8(str);
ini_open("local.ini");
ini_write_string("info", "0", hash);
ini_close();
get[0] = http_post_string("http://www.MacSweeney Games.com/CatchTheHaggis?game_hiscores=" + string(global.game_id), str)

The above code will encode a ds_map into a JSON string. A sha1 hash is then generated and stored in an ini file so that this can later be used to check the integrity of the JSON should the same information be received later form the server. The JSON is then sent.

Back: File Handling
Next: sha1_string_unicode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


temp_directory

Temporary directory created for the game.

Syntax:

temp_directory

Returns: String.

Description

This can be used to return the temporary directory created for your game each time it is run (the root does not contain the final "\"). This directory will hold files and can be accessed while the game is running, but it will be removed (along with all files that it contains) when the game is closed.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

ini_open(temp_directory + "\temp_ini.ini");

This will open an ini file in the temporary directory of the game (creating it if it does not already exist).

Back: File Handling
Next: working_directory

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


working_directory

The directory where either the included files are stored or you have local storage.

Syntax:

working_directory

Returns: String.

Description

Working_directory can actually return two different values depending on what you are using it for. If you are writing a file to disk, working_directory points to the area of local storage that is reserved for your game on the target device (in windows this is "%LOCALAPPDATA%/gamedir/" where the "gamedir" is the directory with the name of your game). However, when reading from disk, working_directory can be either the local storage or the area where the included files are stored.

NOTE: the working_directory variable wiil return the path including the final backslash.

For example, if you have a default *.txt file included with your game and read it into memory using working_directory, then that file will be taken from the area where the included files are stored. If you then choose to write that information to a text file using working_directory, this will write the file to the target platforms local storage, where it will be read from the next time unless you instruct GameMaker: Studio to delete the file, in which case working_directory will once more point to the area where the included files are stored.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

ini_open(working_directory + "temp_ini.ini");

This will open an ini file from the working directory of the game (creating it if it does not already exist). This could be the local storage, or the area where the included files are depending on whether the file being looked for exists in either place.

Back: File Handling
Next: program_directory

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


zip_unzip

Unzip a given zip file to a specific location.

Syntax:

zip_unzip(zip_file, target_directory)

Argument | Description
zip_file | The zip file to open
target_directory | The target directory to extract the files to

Returns: Real

Description

This function will open a stored zip file and extract its contents to the given directory. Note that if you do not supply a full path to the ZIP directory then the current drive root will be used, and if you want to place it in a relative path to the game bundle working directory then you should use the working_directory variable as part of the path (relative paths using "." or ".." will not work as expected so should be avoided). Note too that the zip must be either part of the game bundle (ie: an Included File) or have been downloaded to the storage area using http_get_file.

The function will return a value indicating the number of files extracted, or it will return 0 or less if the extraction has failed.

Example:

var num = zip_unzip("/downloads/level_data.zip", working_directory + "extracted/");
if num <= 0
{
show_debug_message("Extraction Failed!");
}

The above code will open the zip file stored in the directory "downloads" and extract its contents to the directory "extracted" (creating that directory if it doesn't already exist) and then check to see that the extraction has been correct, showing a debug message should it fail.

Back: File Handling

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Binary Files

This section of the manual deals with the functions for binary files.

In rare situations you might need to read data from binary files.

NOTE: These functions do not work when the target module is HTML5.

The following low-level routines exist for this:

  1. file_bin_open
  2. file_bin_rewrite
  3. file_bin_close
  4. file_bin_size
  5. file_bin_position
  6. file_bin_seek
  7. file_bin_write_byte
  8. file_bin_read_byte

Back: File Handling

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_bin_close

This closes the file indexed in the given file name id.

Syntax:

file_bin_close(binfile);

Argument | Description
binfile | The ID of the file to close.

Returns: N/A

Description

Closes a previously opened binary file. You supply the file ID value, as returned by the function file_bin_open.

NOTE: These functions do not work when the target module is HTML5.

Example:

file = file_bin_open('myfile.bin', 2);
file_bin_rewrite(file);
file_bin_close(file);

This would open a file from the same directory as the game, and assign its index to the variable "file". It would then re-write the file (clearing it of data), and close it again.

Back: Binary Files
Next: file_bin_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_bin_open

Opens the file with the indicated name.

Syntax:

file_bin_open(fname, mode);

Argument | Description
fname | The name of the file to read from.
mode | the indicator of what can be done with the file.

Returns: Real

Description

This function will open the binary file with the indicated name. The mode indicates what can be done with the file:

  • 0 = reading
  • 1 = writing
  • 2 = both reading and writing

When the file does not exist it is created, and the function returns the id of the file that must be used in the other functions. You can open multiple files at the same time (32 max), but don't forget to close them once you are finished with them.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

NOTE: These functions do not work when the target module is HTML5.

Example:

file = file_bin_open('myfile.bin', 2);

This would open a file from the same directory as the game, and assign its index to the variable "file".

Back: Binary Files
Next: file_bin_rewrite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_bin_position

Returns the current position (in bytes; 0 is the first position) of the file with the given file id.

Syntax:

file_bin_position(binfile);

Argument | Description
binfile | The ID of the file to get the position in.

Returns: Real

Description

This function will returns the current position in bytes, where 0 is the first position, of the file with the given file id. You supply the file ID value, as returned by the function file_bin_open.

NOTE: These functions do not work when the target module is HTML5.

Example:

pos = file_bin_position(file);

This would store the current position in the variable "pos".

Back: Binary Files
Next: file_bin_seek

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_bin_read_byte

Reads a byte of data from a binary file.

Syntax:

file_bin_read_byte(binfile);

Argument | Description
binfile | The ID of the file to get the data from.

Returns: Real

Description

This function will return a byte of data from current position within the file with the given file ID. You supply the file ID value, as returned by the function file_bin_open.

NOTE: These functions do not work when the target module is HTML5.

Example:

file = file_bin_open('myfile.bin', 2);
data = file_bin_read_byte(file);
file_bin_close(file);

This would open a file from the same directory as the game, and get a byte of data from it before closing it again.

Back: Binary Files
Next: file_bin_open

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_bin_rewrite

Re-writes the given file.

Syntax:

file_bin_rewrite(binfile);

Argument | Description
binfile | The ID of the file to rewrite.

Returns: N/A

Description

This function takes the filename handle as returned by the function file_bin_open and then rewrites the file, clearing it of all previous data to start writing from the beginning of the file.

NOTE: These functions do not work when the target module is HTML5.

Example:

file = file_bin_open('myfile.bin', 2);
file_bin_rewrite(file);

This would open a file from the same directory as the game, and assign its index to the variable "file". It would then re-write the file (clearing it of data).

Back: Binary Files
Next: file_bin_close

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_bin_seek

Moves the current position of the file to the indicated position.

Syntax:

file_bin_seek(binfile, pos);

Argument | Description
binfile | The ID of the file to read from.
pos | The position in the file to move to.

Returns: N/A.

Description

This function moves the current read position within the file to the indicated position. You supply the file ID value, as returned by the function file_bin_open, and to append a file, move the position to the size of the file before writing.

NOTE: These functions do not work when the target module is HTML5.

Example:

file = file_bin_open('myfile.bin', 2);
size = file_bin_size(file);
file_bin_seek(file, size);

This would open a file from the same directory as the game, and assign its index to the variable "file", then get the size of the file and set the next writing position to that size.

Back: Binary Files
Next: file_bin_write_byte

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_bin_size

Returns the size (in bytes) of the file with the given file id.

Syntax:

file_bin_size(binfile);

Argument | Description
binfile | The ID of the file to get the size of.

Returns: Real

Description

This function will return the size (in bytes) of a file that has been opened for reading and/or writing. The File ID is the value returned by the function file_bin_open().

NOTE: These functions do not work when the target module is HTML5.

Example:

file = file_bin_open('myfile.bin', 2);
size = file_bin_size(file);
file_bin_close(file);

This would open a file from the local directory of the game, and assign its index to the variable "file". It would then get the size of that file and close it again.

Back: Binary Files
Next: file_bin_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_bin_write_byte

Writes a byte of data to the file with the given file id.

Syntax:

file_bin_write_byte(binfile, byte);

Argument | Description
binfile | The ID of the file to write to.
byte | The data to write.

Returns: real.

Description

This function will write a byte of data to the file identified by the file ID at the current write position. You supply the file ID value, as returned by the function file_bin_open and the byte of data to write.

NOTE: These functions do not work when the target module is HTML5.

Example:

file_bin_write_byte(file, data);

This would write a byte to the selected file.

Back: Binary Files
Next: file_bin_read_byte

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


File System Functions

This section of the manual deals with the functions for files in general.

There exists in GameMaker: Studio a number of functions that enable you to manipulate files in different ways:

  1. file_exists
  2. file_delete
  3. file_rename
  4. file_copy
  5. file_find_first
  6. file_find_next
  7. file_find_close
  8. file_attributes

The following functions can be used to change file names:

Note: These functions do not work on the actual files! They only deal with the strings.

  1. filename_name
  2. filename_path
  3. filename_dir
  4. filename_drive
  5. filename_ext
  6. filename_change_ext

Finally there are two special functions for getting filenames that can be used for loading and saving files with file-type filters:

Note: These functions are Windows ONLY.

  1. get_open_filename
  2. get_open_filename_ext
  3. get_save_filename
  4. get_save_filename_ext

WARNING! These functions may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Back: File Handling

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_attributes

Gives you the attributes of a file.

Syntax:

file_attributes(fname, attr);

Argument | Description
fname | The name of the file to check.
attr | The attributes to check for.

Returns: Boolean.

Description

You can use this function to check the attributes of a given file. You can add up the following constants to see the type of files you want:

  • fa_readonly - read-only files
  • fa_hidden - hidden files
  • fa_sysfile - system files
  • fa_volumeid - volume-id files
  • fa_directory - directories
  • fa_archive - archived files

NOTE: This is a Windows only function.

Example:

if !file_attributes(file, fa_hidden) file_delete(file);

This would check a file to see if it is hidden or not, and if not it is deleted.

Back: File System Functions
Next: filename_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_copy

Copy a given file.

Syntax:

file_copy(fname, newname);

Argument | Description
fname | The name of the file to copy.
newname | The name of the new, copied, file.

Returns: N/A

Description

This function will copy the specified file, giving it the new name that you choose. If you are copying a file on Android from within your Included Files area (which will be inside your APK) it will copy into memory first, so, be aware that copying very large files from the APK may cause devices to run out of memory. On JavaScript platforms (HTML5), we use the HTML5 Local Storage API for client side saving, and the functions does not support binary file operations, so assumes you are copying a text file.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

if file_exists("level1.txt")
{
file_copy("level1.txt", "level2.txt");
}

This would check for a file and if it exists it is copied.

Back: File System Functions
Next: file_find_first

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_delete

Deletes a given file.

Syntax:

file_delete(fname);

Argument | Description
fname | The name of the file to delete.

Returns: Boolean

Description

This function will delete the specified file from the system. It should be noted that this function will only delete those files that GameMaker: Studio is able to create and parse: ini files, text files and binary files, or those files made to store game created resources like sprites or surfaces. However, it will not delete any other file. The function will also return true if the file has successfully been removed, or false in any other circumstances.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

if file_exists("level.txt")
{
file_delete("level.txt");
}

This would check for a file and if it exists it is deleted.

Back: File System Functions
Next: file_rename

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_exists

Returns whether a given file exists or not.

Syntax:

file_exists(fname);

Argument | Description
fname | The name of the file to check for.

Returns: Boolean.

Description

This function will return true if the specified file exists and false if it does not.

Example:

if file_exists("level.txt")
{
file = file_text_open_read("level.txt");
}

This would check for a file and if it exists it is opened for reading.

Back: File System Functions
Next: file_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_find_close

Frees memory after file searching.

Syntax:

file_find_close();

Description

Must be called after handling all files to free memory.

Example:

file_find_close();

This will close and free the memory associated with the file functions.

Back: File System Functions
Next: file_attributes

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_find_first

Returns the name of the first file that satisfies the mask and the attributes.

Syntax:

file_find_first(mask, attr);

Argument | Description
mask | The mask to use for searching.
attr | The specific file attribute to look for.

Returns: String

Description

This function will return the name of the first file that satisfies the mask and the attributes. If no such file exists, then an empty string is returned. The mask can contain a path and can contain wildchars, for example 'C:\temp\*.doc'. The attributes give the additional files you want to see, so the normal files are always returned when they satisfy the mask. You can add up the following constants to see the type of files you want (if you do not wish to add any attributes, use 0):

  • fa_readonly - read-only files
  • fa_hidden - hidden files
  • fa_sysfile - system files
  • fa_volumeid - volume-id files
  • fa_directory - directories
  • fa_archive - archived files

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

NOTE: This function will not work at all on the JS target platform (HTML5), and the filter flags will only work on Windows and WinPhone (use 0 for all other platforms).

Example:

if directory_exists("\User Content")
{
file = file_find_first("\User Content\*.doc", fa_readonly);
}

This will check to see if the specified directory exists then, if it does, go there and return the first "read only" doc file found.

Back: File System Functions
Next: file_find_next

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_find_next

Returns the name of the next file that satisfies the mask and the attributes.

Syntax:

file_find_next();

Returns: String

Description

This function returns the name of the next file that satisfies the previously given mask and the attributes (defined by file_find_first). If no such file exists, the empty string is returned.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

NOTE: This function works on all the C++ target platforms (Windows, Mac, iOS, Android and WinPhone), BUT the filter flags only work on Windows and WinPhone.

Example:

file = file_find_next();

This will return the next file that matches the previously given attributes.

Back: File System Functions
Next: file_find_close

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_rename

Renames a given file.

Syntax:

file_rename(oldname, newname);

Argument | Description
oldname | The name of the file to change.
newname | The new name to give the file.

Returns: Boolean

Description

This function will rename the specified file with the specified name. The function will return true if the file has successfully been renamed, or false in any other circumstances.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

if file_exists("level1.txt")
{
file_rename("level1.txt", "level.txt");
}

This would check for a file and if it exists it is renamed.

Back: File System Functions
Next: file_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


filename_change_ext

Returns the indicated file name, changing the extension to a new one.

Syntax:

filename_change_ext(fname, newext);

Argument | Description
fname | The file to use.
newext | The new extension to use.

Returns: String.

Description

This function returns the indicated file name with the extension (including the dot) changed to the new extension. By using an empty string as the new extension you can remove the extension part all together.

Example:

ext = filename_change_ext(file_find_first(working_directory + "\*.*", 0), "");

The above code gets the name of the file (as a string) with the extension part removed.

Back: File System Functions
Next: file_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


filename_dir

Returns the directory part of the indicated file name.

Syntax:

filename_dir(fname);

Argument | Description
fname | The file to use.

Returns: String.

Description

This function returns the directory part of the indicated file name, which normally is the same as the path except for the final backslash.

Example:

dir = filename_dir("Test.ini");

The above code gets the directory (as a string) of the specified file.

Back: File System Functions
Next: filename_drive

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


filename_drive

Returns the drive information of the file.

Syntax:

filename_drive(fname);

Argument | Description
fname | The file to use.

Returns: String.

Description

This function returns the drive information of the filename.

Example:

drive = filename_drive(file_find_first(working_directory + "\*.doc", 0));

The above code gets the drive information (as a string) of the specified file.

Back: File System Functions
Next: filename_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


filename_ext

Returns the extension part of the file.

Syntax:

filename_ext(fname);

Argument | Description
fname | The file to use.

Returns: String.

Description

This function returns the extension part of the indicated file name, including the leading dot.

Example:

ext = filename_ext(file_find_first("*.*", 0));

The above code gets the extension (as a string) of the specified file.

Back: File System Functions
Next: filename_change_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


filename_name

Returns the name part of the indicated file name.

Syntax:

filename_name(fname);

Argument | Description
fname | The file to use.

Returns: String.

Description

Using this function returns the name part of the indicated file, with the extension but without the path

Example:

name = filename_name(file_find_first("C:\Games\*.doc", 0));

The above code gets the name (as a string) of the first "doc" type file found in the specified directory.

Back: File System Functions
Next: filename_path

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


filename_path

Returns the path part of the indicated file path.

Syntax:

filename_path(fname);

Argument | Description
fname | The file name and path to use.

Returns: String

Description

Using this function returns the path part of the indicated file path, including the final backslash.

Example:

path = filename_path(working_directory + "Test.ini");

The above code gets the path (as a string) of the specified file.

Back: File System Functions
Next: filename_dir

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_open_filename

Opens a dialogue to select a file with the given filter.

Syntax:

get_open_filename(filter, fname);

Argument | Description
filter | The file type filter and/or name.
fname | The suggested filename to use.

Returns: String.

Description

This function opens a dialogue and asks the player for a filename to open with the given filter. The filter has the form "name1|mask1|name2|mask2|...", where the mask may contain the different options with a semicolon between them and you can also use a "*" to mean any string. For example: "bitmaps|*.bmp;*.wmf", would ask the user to select the name of a bitmap file from the system, but only those that have the two specified extensions (bmp and png). this function does not open the file itself! It only returns a string with the full name and path of the file. If the user presses "Cancel" an empty string "" is returned.

An important thing to note when using this function is that it grants you certain permissions for that file, for the duration of your game. So, once you get the file path from the user, you can access it again and again without having to ask. However, since this function is for reading a file, the permissions granted are only for reading and saving will not be permitted by the OS. Should you need to read and write to the file, you can get permission using the function get_save_filename.

NOTE: This function is only valid on the Windows and macOS targets.

Example:

var file;
file = get_open_filename("text file|*.txt", "");
if file != ""
{
file_text_open_read(file);
}

The above code will ask the user to select a text file for opening and then check the returned file name and path, and if it exists will open the file for reading.

Back: File System Functions
Next: get_open_filename_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_open_filename_ext

Opens a dialogue to select a file with the given filter, directory and window caption.

Syntax:

get_open_filename_ext(filter, fname, directory, caption);

Argument | Description
filter | The file type filter and/or name.
fname | The suggested filename to use.
directory | The directory to start the search from.
caption | The caption for the window.

Returns: String.

Description

This function opens a dialogue and asks the player for a filename to open with the given filter. The filter has the form "name1|mask1|name2|mask2|...", where the mask may contain the different options with a semicolon between them and you can also use a "*" to mean any string. For example: "bitmaps|*.bmp;*.wmf", would ask the user to select the name of a bitmap file from the system, but only those that have the two specified extensions (bmp and png). this function does not open the file itself! It only returns a string with the full name and path of the file. If the user presses "Cancel" an empty string "" is returned. You may also add in a directory to start the search from, and a caption to be shown at the top of the window instead of the default one.

An important thing to note when using this function is that it grants you certain permissions for that file, for the duration of your game. So, once you get the file path from the user, you can access it again and again without having to ask. However, since this function is for reading a file, the permissions granted are only for reading and saving will not be permitted by the OS. Should you need to read and write to the file, you can get permission using the function get_save_filename.

NOTE: This function is only valid on the Windows and macOS targets.

Example:

var file;
file = get_open_filename_ext("text file|*.txt", "", working_directory, "Open a saved level");
if file != ""
{
file_text_open_read(file);
}

The above code will ask the user to select a text file for opening from the working_directory and then check the returned file name and path, and if it exists will open the file for reading.

Back: File System Functions
Next: get_save_filename

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_save_filename

Opens a dialogue to input a filename with the given filter for saving.

Syntax:

get_save_filename(filter, fname);

Argument | Description
filter | The file type filter and/or name.
fname | The suggested filename to use.

Returns: String.

Description

This function opens a dialogue and asks the player for a filename to save to with the given filter. The filter has the form "name1|mask1|name2|mask2|...", where the mask may contain the different options with a semicolon between them and you can also use a "*" to mean any string. For example: "bitmaps|*.bmp;*.wmf", would ask the user to select the name of a bitmap file from the system, but only those that have the two specified extensions (bmp and png). this function does not save the file itself! It only returns a string with the full name and path of the file. If the user presses "Cancel" an empty string "" is returned.

An important thing to note when using this function is that it grants you certain permissions for that file, for the duration of your game. So, once you get the file path from the user, you can access it again and again without having to ask, and the permission applies to reading and writing equally.

NOTE: This function is only valid on the Windows and macOS targets.

Example:

var file;
file = get_save_filename("screenshot|*.png", "");
if file != ""
{
screen_save(file);
}

The above code will ask the user to select an image file name file for saving then check the returned file name and path, and if it is not an empty string it takes a screen shot and saves it using the given name.

Back: File System Functions
Next: get_save_filename_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


get_save_filename_ext

Opens a dialogue to input a filename with the given filter for saving.

Syntax:

get_save_filename_ext(filter, fname, directory, caption);

Argument | Description
filter | The file type filter and/or name.
fname | The suggested filename to use.
directory | The directory to start the search from.
caption | The caption for the window.

Returns: String.

Description

This function opens a dialogue and asks the player for a filename to save to with the given filter. The filter has the form "name1|mask1|name2|mask2|...", where the mask may contain the different options with a semicolon between them and you can also use a "*" to mean any string. For example: "bitmaps|*.bmp;*.wmf", would ask the user to select the name of a bitmap file from the system, but only those that have the two specified extensions (bmp and png). this function does not save the file itself! It only returns a string with the full name and path of the file. If the user presses "Cancel" an empty string "" is returned. You may also add in a directory to start the search from, and a caption to be shown at the top of the window instead of the default one.

An important thing to note when using this function is that it grants you certain permissions for that file, for the duration of your game. So, once you get the file path from the user, you can access it again and again without having to ask, and the permission applies to reading and writing equally.

NOTE: This function is only valid on the Windows and macOS targets.

Example:

var file;
file = get_save_filename_ext("screenshot|*.png", "", working_directory, "Save a level here");
if file != ""
{
screen_save(file);
}

The above code will ask the user to select an image file name file for saving in the working directory and then check the returned file name and path If it is not an empty string it takes a screen shot and saves it using the given name.

Back: File System Functions
Next: file_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Text Files

This section of the manual deals with the functions for text files.

Text files are a useful way to store large amounts of data externally from your game. Contrary to ini files, you can have up to 32 text files open at once, and you can read and write large chunks of data to them as well. However, it is up to you to decide how that data should be structured as there is no set "section" or "key" structure like with *.ini files.

Please note that for games with localizations it is very important that accented letters can be read from external files. This means that you should create the txt file in UTF8 format first and then add it into GameMaker: Studio as an included file so that it is exported on running the game and used instead of the default ANSI format txt file that is created by the GameMaker: Studio file functions when no file is previously supplied. In this way, you can read and write to it correctly with all accents and non-roman letters being maintained.

The following functions exist that deal with files:

  1. file_text_open_read
  2. file_text_open_write
  3. file_text_open_append
  4. file_text_open_from_string
  5. file_text_read_real
  6. file_text_read_string
  7. file_text_readln
  8. file_text_write_real
  9. file_text_write_string
  10. file_text_writeln
  11. file_text_eoln
  12. file_text_eof
  13. file_text_close

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Back: File Handling

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_close

Closes a given opened text file.

Syntax:

file_text_close(fileid);

Argument | Description
fileid | The id of the file to close.

Returns: N/A

Description

Once you have finished working with a given file (whether reading from it or writing to it), you must close the file again, or else you risk losing the information contained within. This also prevents memory leaks and makes sure that you never go over the file limit by having more than 32 files open.

Example:

file = file_text_open_write(working_directory + "\Game_Data.txt");
while (!file_text_eof(file))
{
file_text_readln(file);
}
file_text_write_string(file, level_data);
file_text_close(file);

The above code opens a file for writing then loops through the lines of text already written to the file until it reaches the end. At this point it writes a string and then closes the file again.

Back: Text Files
Next: file_text_open_read

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_eof

Check the current read position of a file to see if the end has been reached.

Syntax:

file_text_eof(fileid);

Argument | Description
fileid | The id of the file to check.

Returns: Boolean

Description

This function returns true when the end of a given opened text file has been reached or false if not.

Example:

var num = 0;
file = file_text_open_read(working_directory + "\Game_Data.txt");
while (!file_text_eof(file))
{
str[num++] = file_text_readln(file);
}
file_text_close(file);

The above code opens a file for writing then loops through the lines of text already written to the file until it reaches the end, storing each line in the array "str".

Back: Text Files
Next: file_text_close

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_eoln

Checks to see if the end of the line being read from a text file has been reached.

Syntax:

file_text_eoln(fileid);

Argument | Description
fileid | The id of the file to check.

Returns: Boolean

Description

With this function you can get GameMaker: Studio to check the currently opened file to see if the line being read has finished. The function returns true if the end of the line has been reached and false otherwise.

Example:

file = file_text_open_read(working_directory + "\Game_Data.txt");
var num = 0;
while (!file_text_eoln(file))
{
score_array[num] = file_text_read_real(file);
num++;
}
file_text_close(file);

The above code opens a file for reading then reads the values from a single line into an array.

Back: Text Files
Next: file_text_eof

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_open_append

Opens the text file with the indicated filename for appending.

Syntax:

file_text_open_append(fname);

Argument | Description
fname | The name of the file to append to.

Returns: Real

Description

This function opens the text file with the indicated filename for writing (if the file does not exist, it is created), returning the unique id of the file that which should be stored in a variable as it will be used for all further actions to do with that file. The position within the file for writing to is set to the last line of text that the file contains. Note that if the file can't be created (because of an illegal filename, for example) the function will return -1.

NOTE: You can only have a maximum of 32 files open at any one time. You should also always close files when finished as this writes the information and frees the memory associated with the file.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

file = file_text_open_append(working_directory + "save.txt");

This would open "save.txt" from the same directory as the game and store the file id in the variable "file".

Back: Text Files
Next: file_text_open_from_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_open_from_string

Creates a temporary text file from a string for reading.

Syntax:

file_text_open_from_string(string);

Argument | Description
string | The string to create the file from.

Returns: Real

Description

This function will create a text file from a string and open it for reading, returning the file "handle" that should be used in all further file function calls to read from this file. Note that this file is temporary and read only, and as such it will be removed from memory the moment it is closed.

NOTE: You can only have a maximum of 32 files open at any one time. You should also always close files when finished as this frees the memory associated with the file.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

file = file_text_open_from_string(reset_str);

The above code takes the string stored in the variable "reset_str" and uses it to create a read-only text file. The "handle" for this file is then stored in the variable "file" for all further file functions to use.

Back: Text Files
Next: file_text_read_real

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_open_read

Opens the text file with the indicated filename for reading.

Syntax:

file_text_open_read(fname);

Argument | Description
fname | The name of the file to read from.

Returns: Real

Description

This function opens the text file with the indicated filename for reading only, returning the unique id of the file that which should be stored in a variable as it will be used for all further actions to do with that file. If the file does not exists then the function will return the value -1.

NOTE: You can only have a maximum of 32 files open at any one time. You should also always close files when finished as this frees the memory associated with the file.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

file = file_text_open_read(working_directory + "\level.txt");

This would open "level.txt" from the same directory as the game and store the file id in the variable "file".

Back: Text Files
Next: file_text_open_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_open_write

Opens the text file with the indicated filename for writing.

Syntax:

file_text_open_write(fname);

Argument | Description
fname | The name of the file to write to.

Returns: Real

Description

This function opens the text file with the indicated filename for writing only (if the file does not exist, it is created), returning the unique id of the file that which should be stored in a variable as it will be used for all further actions to do with that file. Note that if the file can't be created (because of an illegal filename, for example) the function will return -1.

NOTE: You can only have a maximum of 32 files open at any one time. You should also always close files when finished as this writes the information and frees the memory associated with the file.

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

var file;
file = file_text_open_write(working_directory + "\level.txt");
file_text_write_string(file, level_data);
file_text_close(file);

The above code will open the file "level.txt" for writing and then write the string stored in the variable "level_data" before finally closing the file again.

Back: Text Files
Next: file_text_open_append

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_read_real

Reads real value from a given opened text file.

Syntax:

file_text_read_real(fileid);

Argument | Description
fileid | The id of the file to read from.

Returns: Real

Description

With this function you can read a real number value from a text file and the function returns that value to be used or stored in a variable.

Example:

var i, file;
file = file_text_open_read(working_directory + "\hiscore.txt");
for (i = 0; i < 10; i += 1)
{
scr[i] = file_text_read_real(file);
file_text_readln(file);
scr_name[i] = file_text_read_string(file);
file_text_readln(file);
}
file_text_close(file);

The above code opens a file for reading and then loops through the lines of the file reading alternately a real number value and a string into two different arrays for future use. The file is then closed when the loop has finished.

Back: Text Files
Next: file_text_read_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_read_string

Reads a string from a given opened text file.

Syntax:

file_text_read_string(fileid);

Argument | Description
fileid | The id of the file to read from.

Returns: String

Description

With this function you can read a string from a text file and the function returns that value to be used or stored in a variable.

Example:

var i, file;
file = file_text_open_read(working_directory + "\hiscore.txt");
for (i = 0; i < 10; i += 1)
{
scr[i] = file_text_read_real(file);
file_text_readln(file);
scr_name[i] = file_text_read_string(file);
file_text_readln(file);
}
file_text_close(file);

The above code opens a file for reading and then loops through the lines of the file reading alternately a real number value and a string into two different arrays for future use. The file is then closed when the loop has finished.

Back: Text Files
Next: file_text_readln

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_readln

Goes to the next line of the text file

Syntax:

file_text_readln(fileid);

Argument | Description
fileid | The id of the file to read from.

Returns: string

Description

With this function you can skip the remainder of the current line from a given opened text file and move to the start of the next one. The function will also return the full line as a string, making it an easy way to read complete "chunks" of data for parsing later.

Example:

var i, file;
file = file_text_open_read(working_directory + "\hiscore.txt");
for (i = 0; i < 10; i += 1)
{
scr[i] = file_text_read_real(file);
file_text_readln(file);
scr_name[i] = file_text_read_string(file);
file_text_readln(file);
}
file_text_close(file);

The above code opens a file for reading and then loops through the lines of the file reading alternately a real number value and a string into two different arrays for future use. The file is then closed when the loop has finished.

Back: Text Files
Next: file_text_write_real

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_write_real

Writes a real value to a given opened text file.

Syntax:

file_text_write_real(fileid, val);

Argument | Description
fileid | The id of the file to edit.
val | The real value to write to the file.

Returns: Real

Description

With this function you can write a number to the previously opened text file. Note that as the value to be written can be a real number, all decimals will be written with a "." point as separator. If the file already contains information, this information will be erased and the string will be written at the beginning of the file, unless you have opened the file with the file_text_open_append. You can also avoid this by using the file_text_readln function along with the file_text_eof function to loop through the contents of the file until you get to the end and then start writing.

It is important to note that when writing very large numbers to a text file using this function, it may be translated into a standard simplified format, like "6.6624e+003", which cannot be read back in to GameMaker: Studio correctly. To prevent issues like this, you should instead convert the value to a string and use the function file_text_write_string() instead.

Example:

var i, file;
file = file_text_open_write(working_directory + "\hiscore.txt");
for (i = 0; i < 10; i += 1)
{
file_text_write_real(file, scr[i]);
file_text_writeln(file);
file_text_write_string(file, scr_name[i]);
file_text_writeln(file);
}
file_text_close(file);

The above code opens a file for writing and then loops through two arrays, writing each array value to a new line of the file. The file is then closed when the loop has finished.

Back: Text Files
Next: file_text_write_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_write_string

Writes a string to a given opened text file.

Syntax:

file_text_write_string(fileid, str);

Argument | Description
fileid | The id of the file to edit.
str | The string to write to the file.

Returns: Real

Description

With this function you can write a string to a previously opened text file. If the file already contains information, this information will be erased and the string will be written at the beginning of the file, unless you have opened the file with the file_text_open_append. You can also avoid this by using the file_text_readln function along with the file_text_eof function to loop through the contents of the file until you get to the end and then start writing.

Example:

var i, file;
file = file_text_open_write(working_directory + "\hiscore.txt");
for (i = 0; i < 10; i += 1)
{
file_text_write_real(file, scr[i]);
file_text_writeln(file);
file_text_write_string(file, scr_name[i]);
file_text_writeln(file);
}
file_text_close(file);

The above code opens a file for writing and then loops through two arrays, writing each array value to a new line of the file. The file is then closed when the loop has finished.

Back: Text Files
Next: file_text_writeln

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


file_text_writeln

Writes a new line to a given opened text file.

Syntax:

file_text_writeln(fileid);

Argument | Description
fileid | The id of the file to edit.

Returns: Real

Description

With this function you can write a new line to an opened text file. In this way you can skip lines or write information on a line by line basis (see example code below).

Example:

var i, file;
file = file_text_open_write(working_directory + "\hiscore.txt");
for (i = 0; i < 10; i += 1)
{
file_text_write_real(file, scr[i]);
file_text_writeln(file);
file_text_write_string(file, scr_name[i]);
file_text_writeln(file);
}
file_text_close(file);

The above code opens a file for writing and then loops through two arrays, writing each array value to a new line of the file. The file is then closed when the loop has finished.

Back: Text Files
Next: file_text_eoln

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Ini files

This section deals with ini_file functions.

Ini files are small, lightweight files which are compatible with most platforms. They are ideal for storing small pieces of information, like interface preferences, local high scores, level data etc...

Please note that for games with localizations it is very important that accented letters can be read from external files. This means that you should create the ini file in UTF8 format first and then add it into GameMaker: Studio as an included file so that it is exported on running the game and used instead of the default ANSI format ini file that is created by the ini functions when none has been previously supplied. In this way, you can read and write to it correctly with all accents and non-roman letters being maintained.

The following functions exist for ini files:

  1. ini_open
  2. ini_close
  3. ini_write_real
  4. ini_write_string
  5. ini_read_real
  6. ini_read_string
  7. ini_key_exists
  8. ini_section_exists
  9. ini_key_delete
  10. ini_section_delete
  11. ini_open_from_string

WARNING! These functions may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Back: File Handling

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_close

Closes the currently open .ini file.

Syntax:

ini_close();

Returns: String

Description

This function should be called the moment you are finished reading or writing to any open ini file. If you do not use the function after you have used any of the ini write functions, then nothing will be written to disk, as the file information is held in memory until this function is called, which forces the write. If you try to open an ini without having previously closed another one (or the same one) you will get an error too.

The function will also return a string with the ini file encoded into it. This string can then be saved to a server and/or used again along with the function ini_open_from_string to re-create the ini.

Example:

ini_open("savedata.ini");
score = ini_read_real("save1", "score", 0);
ini_close();

This will open 'savedata.ini' and set score to the value under the section "save1" with the key "score" in it, then close the .ini again. Should there be no value under "save1", "score" or there is no "savedata.ini" file present, score will be set to 0 and a new ini_file created.

Back: Ini Files
Next: ini_write_real

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_key_delete

Deletes the indicated key from the indicated section of the currently open .ini file, should the key exist.

Syntax:

ini_key_delete(section, key);

Argument | Description
section | The section to delete a key from.
key | The key to delete.

Returns: N/A

Description

With this function you can remove the selected key (and its corresponding value) from an ini file.

Example:

ini_open('savedata.ini');
ini_write_real('save1','Score',score);
ini_key_delete('save1','Score');
ini_close();

This example will open 'savedata.ini' and write a value to 'save1' > 'Score'. It will then delete the 'Score' key and close the .ini file.

Back: Ini Files
Next: ini_section_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_key_exists

Returns whether or not a key in an open .ini file exists.

Syntax:

ini_key_exists(section, key);

Argument | Description
section | The section in the open .ini file to check a key in.
key | The key to check for.

Returns: N/A

Description

This function checks to see if a key exists in the currently open ini. This is not a necessary check to prevent errors as, when a key does not exist, reading from a non-existent key will just return a defaulted value. It can be useful to see if an ini file has saved specific data and a few other things, however.

Example:

ini_open('savedata.ini');
if !ini_key_exists('save1', 'name')
{
global.name = 'Player1';
}
ini_close();

This will set variable global.name to 'Player1' if no such key as "name" exists.

Back: Ini Files
Next: ini_section_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_open

Opens the relevant .ini file for reading and writing.

Syntax:

ini_open(name);

Argument | Description
name | The filename for the .ini file.

Returns: N/A

Description

This opens an ini_file for reading and/writing. If the ini_file does not exist at the location you are checking, GameMaker: Studio may create one, but only if you write data to it. If you have only read information from the ini file, then the default values for the read function will be returned, but the ini file will not actually be created.

Please note that you can only have one ini file open at any one time and remember to use ini_close once you're finished reading/writing from the .ini file as the information is not actually stored to disk until then (it is also stored in memory until the file is closed).

WARNING! This function may not work as you expect due to GameMaker: Studio being sandboxed! Please see the section on File System Limits for more information.

Example:

ini_open("savedata.ini");
score = ini_read_real("save1", "score", 0);
ini_close();

This will open 'savedata.ini' and read the score value under the section "save1" with the key "score" in it, then close the .ini again. Should there be no value under "save1", "score" or there is no "savedata.ini" file present, score will be set to 0 (the default value).

Back: Ini Files
Next: ini_close

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_open_from_string

Creates a temporary ini file from a string.

Syntax:

ini_open_from_string(string);

Argument | Description
string | The string containing all the ini information.

Returns: N/A

Description

This function will create an ini file from a string and open it for reading/writing. The string should be correctly formatted as an ini file (ie: with sections, line breaks keys and values) otherwise the ini file will not be created correctly. Note that this ini file is temporary and will be removed from memory the moment it is closed, losing any information that was stored in it, however the ini_close function returns a string of the full ini file which can then be saved to a server or to disk.

Example:

ini_open_from_string(str)
global.sound = ini_read_string("Options", "Sound", true);
ini_close();

The above code sets a temporary ini to hold the information from the string "str", then reads from the ini before closing it again.

Back: Ini Files
Next: ini_open

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_read_real

Reads a saved real value (number) from an .ini file.

Syntax:

ini_read_real(section, key, default);

Argument | Description
section | The section of the .ini to read from.
key | The key within the relevant section of the .ini to read from.
default | The value to return if a value is not found in the defined place (or the .ini file does not exist). Must be a real number.

Returns: Real

Description

You can use this function to read a number from an ini data file. Ini files are split into sections and then each section is subsequently split into key - value pairs. So a typical ini file would look something like this:

Example:

ini_open( 'savedata.ini' );
score = ini_read_real( 'save1', 'score', 0 );
ini_close();

This will open 'savedata.ini' and set score to the value under 'save1' > 'score' in it, then close the .ini again. Should there be no value under 'save1' > 'score', or there no 'savedata.ini' file present, score will be set to 0.

Back: Ini Files
Next: ini_read_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_read_string

Reads a saved string from an .ini file.

Syntax:

ini_read_string(section, key, default);

Argument | Description
section | The section of the .ini to read from.
key | The key within the relevant section of the .ini to read from.
default | The string to return if a string is not found in the defined place (or the .ini file does not exist). Must be a string.

Returns: String

Description

You can use this function to read a string (text) from an ini data file. Ini files are split into sections and then each section is subsequently split into key - value pairs. So a typical ini file would look something like this:

Example:

ini_open( 'savedata.ini' );
global.name = ini_read_string( 'save1', 'Name', 'Player1' );
ini_close();

This will open 'savedata.ini' and set global.name to the string under 'save1' > 'Name' in it, then close the .ini again. Should there be no string under 'save1' > 'Name', or there no 'savedata.ini' file present, global.name will be set to 'Player1'.

Back: Ini Files
Next: ini_key_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_section_delete

Deletes the indicated section of the currently open .ini file, should the section exist.

Syntax:

ini_section_delete(section);

Argument | Description
section | The section to delete.

Returns: N/A

Description

With this function you can delete a whole section of an ini file, which will also remove all key-value pairs that are associated with it.

Example:

ini_open( 'savedata.ini' );
ini_write_real( 'save1', 'Score', score );
ini_section_delete( 'save1' );
ini_close();

This example will open 'savedata.ini' and write a value to 'save1' > 'Score'. It will then delete the 'save1' section and close the .ini file.

Back: Ini Files
Next: ini_open_from_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_section_exists

Returns whether or not a section in an open .ini file exists.

Syntax:

ini_section_exists(section);

Argument | Description
section | The section in the open .ini file to check for.

Returns: Boolean

Description

This function checks to see if a section exists in the currently open ini. This is not a necessary check to prevent errors as, when a section does not exist, reading from a non-existent section will just return a default value, however it can be useful to see if an ini file has saved specific data.

Example:

ini_open("savedata.ini");
if !ini_section_exists("save1")
{
global.savegame = '1';
}
ini_close();

This will set variable global.savegame to '1' if 'save1' is NOT found. With a for loop, this could be used as a basic way of working out how many save games there are for a game (ie: creating a system for multiple simultaneous save games for one game).

Back: Ini Files
Next: ini_key_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_write_real

Writes a real value (number) to an .ini file.

Syntax:

ini_write_real(section, key, value);

Argument | Description
section | The section of the .ini to write to.
key | The key within the relevant section of the .ini to write to.
value | The real value to write to the relevant destination.

Returns: N/A

Description

You can use this function to write a value (numeric) to an ini data file. Ini files are split into sections and then each section is subsequently split into key - value pairs. So a typical ini file would look something like this:

Example:

score = 1000;
ini_open( 'savedata.ini' );
ini_write_real( 'save1', 'Score', score );
score2 = ini_read_real( 'save1', 'Score', 0 );
ini_close();

This will set score to 1000, then open 'savedata.ini' and write this value to 'save1' > 'Score'. Then, it will set score2 to the real value under 'save1' > 'score' in it, 1000, and close the .ini again. Had it not found this value, score2 would have ended up set as 0.

Back: Ini Files
Next: ini_write_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ini_write_string

Writes a string to an .ini file

Syntax:

ini_write_string(section, key, value);

Argument | Description
section | The section of the .ini to write to.
key | The key within the relevant section of the .ini to write to.
value | The string to write to the relevant destination.

Returns: N/A

Description

You can use this function to write a string (text) to an ini data file. Ini files are split into sections and then each section is subsequently split into key - value pairs. So a typical ini file would look something like this:

Example:

ini_open("savedata.ini");
ini_write_string("Save", "Player", global.Name);
ini_close();

The above code opens an ini file for reading and writing, then writes the string stored in the global variable "Name" to the section "Save" with the key "Player" before closing the file again.

Back: Ini Files
Next: ini_read_real

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Game Assets

This section deals with all those functions related to the games assets.

In GameMaker: Studio you can define various types of game assets (or resources), like sprites, sounds, fonts and backgrounds and each asset type has its own selection of codes for modifying them, using them and moving them during your game. Many even have functions that permit you to load and save these resources into your game while it is running, but be warned though - Changing resources easily leads to serious errors in your games! As such it is a good idea to follow the following rules when changing resources:

  • Don't remove (delete) assets that are being used in the current room or being referenced directly in any room.

  • If you have changed an included asset of your game (for example, you have replaced a sprite with a loaded image), when you restart the game using the game_restart() function, the changed assets are NOT restored to their original shape. In general, when you manipulate included assets you can no longer use the action or function to restart the game.

  • Changing assets from a file can be a relatively slow process, so try not to use it mid game, but rather save it for moments in which any possible pause will not interrupt the game-play.

  • Creating assets during game play (in particular sprites and background) easily uses large amount of memory, so be careful with this. For example, if you have a 32 frame 128x128 animated sprite and you decide to create 36 rotated copies of it you will use up 36x32x128x128x4 = 72 MB of memory! And, as these resources are not included in any of the pre-made texture pages that carry your original assets, they involve an extra page swap, which means many such assets can really slow things down.

  • Make sure you delete the created assets you no longer need, otherwise you can end up with a memory leak which will slow down and eventually crash your game

In general, you should try not to change any resources during game play, and it is better create and change the resources at the beginning of the game or even at the beginning of a room.

Information on resources can be found in the following pages:

  1. Sprites
  2. Backgrounds
  3. Audio
  4. Fonts
  5. Paths
  6. Timelines
  7. Rooms

There are two extra functions related to the handling game assets. These functions can be used to find the unique index value for any given asset and the type of asset that it is, which opens the door to dynamically creating game assets from strings (for example):

  1. asset_get_index
  2. asset_get_type

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


asset_get_index

Returns the unique index of the game asset with the given name.

Syntax:

asset_get_index(name);

Argument | Description
name | The name of the game asset to get the index of (a string).

Returns: Real

Description

You can use this function to get the unique identifying index for a game asset from its name. If the asset is not found, the function will return a value of -1, otherwise it will return the unique index id for the asset being checked. This id can then be used in other functions as you would any other index value, like the sprite_index or the path_index, for example. Please note that although this function can be used to reference assets from strings (see example below) you should always make sure that the asset exists before using it otherwise you may get errors that will crash your game.

NOTE: Script names will not resolve as assets on the HTML5 target platform due to obfuscation of the final code, which may cause issues and should be taken into consideration when using the function.

Example:

var obj = asset_get_index("obj_Enemy_" + string(global.Level));
if obj > -1
{
instance_create(random(room_width), random(room_height), obj);
}

The above code will get an object index from a string, and if that index exists, create an instance of the object in the game.

Back: Game Assets
Next: asset_get_type

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


asset_get_type

Returns the type of game asset referenced from its name.

Syntax:

asset_get_type(name);

Argument | Description
name | The name of the game asset to get the type of (a string).

Returns: Constant

Description

With this function you can get the type of asset being referenced from it s name (a string). The following constants are returned:

Constant | Description
asset_object | The given name refers to an object.
asset_sprite | The given name refers to a sprite.
asset_sound | The given name refers to a sound.
asset_room | The given name refers to a room.
asset_background | The given name refers to a background.
asset_path | The given name refers to a path.
asset_script | The given name refers to a script.
asset_font | The given name refers to a font.
asset_timeline | The given name refers to a time line.
asset_unknown | The given name refers to an asset that either does not exist, or is not one of the above listed.

Example:

if asset_get_type("pth_Path_" + string(global.Game)) == asset_unknown
{
show_debug_message("Path doesn't exist!!!");
}
else
{
path_index = asset_get_index("pth_Path_" + string(global.Game));
}

The above code checks a dynamically created asset name to see if the asset is of the correct type. If it is not, then a debug message will be shown, otherwise the asset name is used to assign the asset to the instance.

Back: Game Assets
Next: asset_get_index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Backgrounds

This section deals with the functions relating to background assets.

Backgrounds are another form of image asset that you can use in GameMaker: Studio, and are split into two general categories: background images and tilesets. Background images are generally the large, static images that are used to form the back of a room, with all other things being drawn over them, although they can have other uses, while tilesets are background images that are "cut up" into smaller pieces and used to add low cost graphical images to a level. For example, in a platform game you may have only one single floor object and then use a series of background tiles to hide them and give each an individual "look".

Background Variables

The following global variables are built in to GameMaker: Studio and can be used to get information about a background asset as it is currently used within a room. Most of these variables can be set as well as read and so can be used to change the way backgrounds are displayed within the room, but any changes that they make to the background are not permanent and will be reset if the player leaves and enters the room again, or the game is restarted (unless the room is persistent). Please note that these all affect the current room only, but if you should need to set any of these values for another room you should be using the function room_set_background().

  1. background_index[0..7]
  2. background_visible[0..7]
  3. background_alpha[0..7]
  4. background_blend[0..7]
  5. background_x[0..7]
  6. background_y[0..7]
  7. background_colour
  8. background_showcolour
  9. background_foreground[0..7]
  10. background_hspeed[0..7]
  11. background_vspeed[0..7]
  12. background_htiled[0..7]
  13. background_vtiled[0..7]
  14. background_width[0..7]
  15. background_height[0..7]
  16. background_xscale[0..7]
  17. background_yscale[0..7]

Background Information

The following functions can be used to get information about a background asset. Please note that these functions get the information from the base background (ie. the background asset) and not from the background as it is being used in a room. For information on backgrounds that are being used in a specific room, see the section on "Background Variables" above.

  1. background_get_name
  2. background_get_width
  3. background_get_height
  4. background_get_texture
  5. background_get_uvs

Background Manipulation

The functions below are all related to changing the sprite asset (resource) itself. This means that the majority of these functions will affect all instances that reference the sprite being changed, it also means that you must take great care to ensure that a sprite exists before referencing it, or to make sure it is not being referenced before changing it.

  1. background_exists
  2. background_add
  3. background_replace
  4. background_duplicate
  5. background_assign
  6. background_create_colour
  7. background_create_gradient
  8. background_create_from_surface
  9. background_set_alpha_from_background
  10. background_save
  11. background_delete
  12. background_flush
  13. background_flush_multi
  14. background_prefetch
  15. background_prefetch_multi

Background Tiles

The following section has all the different functions and variables that are related to background images when they are used to create tiles in a room:

  1. Background Tiles

Back: Game Assets

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_index

The unique index of the image asset assigned to the background.

Syntax:

background_index[0...7];

Returns: Real

Description

As with most resources, backgrounds can be assigned and changed by setting their index to a different game asset. This array is what you must use to change any one of the 8 possible backgrounds (numbered form 0 - 7 within the array) that a room may have, or to get the index of any of those backgrounds. When setting it you should use the index of the included image asset from the background resources, or, if you have loaded a background into the game using background_add(), the variable where you have stored the loaded background index. The value array for any one of the backgrounds can be set to -1 to remove the background.

Example:

background_index[0] = choose(bck_Day, back_Evening, bck_Night);

The above code will set the background(0) index of the current room to be one of three possible background images from included the assets.

Back: Backgrounds
Next: background_visible

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_add

Adds an image from a file to the set of sprite resources.

Syntax:

background_add(fname, removeback, smooth);

Argument | Description
fname | The name (string) of the file to added.
removeback | Indicates whether to make all pixels with the selected colour (left-bottom pixel) transparent.
smooth | Indicates whether to smooth the edges if transparent.

Returns: Real

Description

With this function you can add an image as a background, loading it from an external source where the image file to be loaded should always be *.png format. The function returns the new background index which must then be used in all further codes that relate to this background. If you use this function with HTML5 or are getting an image from an URL, this function will also generate an asynchronous event. See Advanced Use - More About Async Events for more information.

Setting the "removeback" argument to true will remove a colour from the background, by checking the bottom left pixel of the defined area for the colour there and then using that as the colour to be removed.

If you choose the "removeback" option, you may also want GameMaker: Studio to smooth the edges of the background by setting the "smooth" argument to true. All this does is create a semi-transparent border around the edges of the background after it has had its background removed.

It is worth noting that when you load a background into GameMaker: Studio in this way you must remember to remove it again (with background_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

NOTE: Depending on the target platform that is chosen you are limited as to where you can save and load files from. See Reference - Files for more information.

NOTE: You should be aware that if you are using this function in your HTML5 target game to load resources from an external server, then, due to XSS protection in browsers, attempts to load resources from across domains can be blocked and may appear to return blank results.

Example:

bck = background_add("Sky_5.png");

The above code loads a background into the game and stores its index in the variable "bck".

Back: Backgrounds
Next: background_replace

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_alpha

Returns or sets the alpha of any background within a room.

Syntax:

background_alpha[0...7]

Returns: Real

Description

This variable array returns the alpha (transparency) value of any one of the 8 backgrounds (numbered form 0 - 7 within the array) of the current room. This value can be anywhere between 0 and 1, where 0 indicates that the background is completely transparent and 1 (the default value) indicates that the background is completely opaque.

Example:

if background_alpha[0] <1 background_alpha[0] = 1;

The above code checks the alpha value for background0 and if it is less than 1, it sets it to 1.

Back: Backgrounds
Next: background_blend

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_assign

Assigns one background to another background index.

Syntax:

background_assign(index, background);

Argument | Description
index | The index of the background to be copied to (ie: over-written).
background | The background to be copied from.

Returns: N/A

Description

This function takes two previously created (or included) background indices, and copies the image from one to the other. In this way you can copy (or "clone") one background into another index. Note that you can only assign to a background that has been created dynamically using the background_duplicate() function.

Example:

bck_temp = background_duplicate(bck_Sky_Base);
background_assign(bck_Temp, bck_Sky);

The above code will copy the image from "bck_Sky" into the index of "bck_Temp".

Back: Sprites
Next: background_create_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_blend

Returns or sets the colour blend value of any background within a room.

Syntax:

background_blend[0...7]

Returns: Real

Description

This variable array returns the colour blend value of any one of the 8 backgrounds (numbered form 0 - 7 within the array) of the current room. The default value is -1 (which is also equal to the GameMaker: Studio constant c_white), but this can be set to any colour value with varying effects being achieved depending on the background image itself, as shown in the image below. For best results, it is recommended that you only blend a colour with a grey-scale, or black and white, image.

Example:

switch (background_blend[0])
{
case c_white: background_blend[0] = c_yellow; break;
case c_yellow: background_blend[0] = c_green; break;
case c_green: background_blend[0] = c_aqua; break;
case c_aqua: background_blend[0] = c_orange; break;
case c_orange: background_blend[0] = c_white; break;
}

The above code will change the blend colour of background0 depending on the current blend colour that is being used.

Back: Backgrounds
Next: background_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_colour

This variable can be changed to change the current room's background colour.

Syntax:

background_colour

Returns: Real

Description

When in a room, it can have no background image selected for any of its background_index, in which case you should set a background colour with this variable and make sure that the background_showcolour variable is set to true so it can be seen. Having a room with no background image and no background colour will result in graphical artefacts being drawn on the screen and is not recommended.

Example:

if background_index[0] = -1
{
background_colour= c_black;
background_showcolour = true;
}

The above code checks to see if background0 has an image assigned to it and if not it sets the background colour to black and flags it to be shown.

Back: Backgrounds
Next: background_showcolour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_create_colour

Creates a new background of a given size and colour.

Syntax:

background_create_colour(w, h, col);

Argument | Description
w | The width of the background.
h | The height of the background.
col | The colour to clear the background to.

Returns: Real

Description

This function creates a new background of the given width and height cleared to the given colour. The function returns the index of the newly created background and this should be stored in a variable and used in all further calls that require this background. If there is an error, the function returns -1.

NOTE: When you create a background dynamically with GameMaker: Studio you must remember to remove it again (with background_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

t_back = background_create_colour(room_width, room_height, c_black);

The above code will create a new background the same size as the current room and colours it black. The index of this new background is stored in the variable "t_back".

Back: Backgrounds
Next: background_create_gradient

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_create_from_surface

Creates a background by copying an area from a surface.

Syntax:

background_create_from_surface(index, x, y, w, h, removeback, smooth);

Argument | Description
index | The index of the surface to create from.
x | The x position to copy from.
y | The y position to copy from.
w | The width of the area to be copied (from the x position).
h | The height of the area to be copied (from the y position).
removeback | Indicates whether to make all pixels with the same colour (left-bottom pixel) transparent.
smooth | Indicates whether to smooth the edges.

Returns: Real

Description

With this function you can create a background from a previously initialised surface. The x and y coordinates that you input are relative to the (0,0) position of the surface (the top left corner) and not the game window, nor the view if you have one active. The width and height arguments are in pixels and define the width and height of the part of the surface to use.

Setting the "removeback" argument to true will remove a colour from the background, by checking the bottom left pixel of the defined area for the colour there and then using that as the colour to be removed.

If you choose the "removeback" option, you may also want GameMaker: Studio to smooth the edges of the background by setting the "smooth" argument to true. All this does is create a semi-transparent border around the edges of the background after it has had its background removed.

NOTE: When you create a background in GameMaker: Studio with this method you must remember to remove it again (with background_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

var surf;
surf = surface_create(32, 32);
surface_set_target(surf);
draw_clear_alpha(c_black, 0);
draw_background(bck_Sky, 0, 0, 0);
draw_background(bck_Mountains, 0, 0);
bck_custom = background_create_from_surface(surf, 0, 0, 32, 32, true, true);
surface_reset_target();
surface_free(surf);

The above code creates a surface and stores its index in the local variable "surf". It then targets that surface, clears it and draws two background on top of each other. Finally it creates a new background from the composite image drawn on the surface and assigns its index to "bck_Custom" before freeing up the memory used by the surface.

Back: Backgrounds
Next: background_set_alpha_from_background


background_create_gradient

Creates a new background with a coloured gradient.

Syntax:

background_create_gradient(w, h, colour1, colour2, kind);

Argument | Description
w | The width of the new background.
h | The height of the new background
colour1 | The first colour of the gradient.
colour2 | The second colour of the gradient.
kind | The type of gradient (0 - 5).

Returns: Real

Description

This function creates a new background of the given width and height cleared to the given coloured gradient. The function returns the index of the newly created background and this should be stored in a variable and used in all further calls that require this background (If there is an error, the function returns -1). The gradient itself can be set to one of 6 different kinds as shown below:

NOTE: When you create a background dynamically with GameMaker: Studio you must remember to remove it again (with background_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

t_back = background_create_gradient(room_width, room_height, c_red, c_blue, 0);

The above code will create a new background the same size as the current room and colour it with a red/blue horizontal gradient. The index of this new background is stored in the variable "t_back".

Back: Backgrounds
Next: background_create_from_surface

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_delete

Deletes the background from memory, freeing the memory used.

Syntax:

background_delete(index);

Argument | Description
index | The index of the background to be deleted.

Returns: N/A

Description

This function will delete a background from the game, freeing any memory that was reserved for it. This is a permanent removal, and if the asset that you delete was included as part of the game's resources, not even restarting the game (unless you close the application first) will recover it. This is a very important function for those moments when you need to create and change backgrounds from external resources and should always be used to remove those assets that are no longer needed by a game, or to clear an indexed asset from a variable before re-assigning another asset to that same variable.

Example:

var bck;
bck = background_create_from_screen(0, 0, 320, 320, false, false);
background_assign(bck_Custom, bck)
background_delete(bck);

The above code creates a local variable and then stores the index of the background created from the screen. This background is then assigned to the asset indexed in the variable "bck_Custom" before being removed from memory again.

Back: Backgrounds
Next: background_flush

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_duplicate

Creates a duplicate of the background with the given index.

Syntax:

background_duplicate(index);

Argument | Description
index | The index of the background to duplicate.

Returns: Real

Description

This function will return the index of a newly created background that is a duplicate (copy) of the one input as the "index" argument. If the function fails, -1 is returned.

NOTE: When you duplicate a background in GameMaker: Studio you must remember to remove it again (with background_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

new_bck = background_duplicate(background_index[0])

The above code duplicates the background currently being used as the background index of the current room and stores the index for this new background in the variable "new_bck".

Back: Backgrounds
Next: background_assign

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_exists

Determines whether a background exists or not.

Syntax:

background_exists(index);

Argument | Description
index | The index of the background to check.

Returns: N/A

Description

This function returns whether a background with the specified index exists or not. Please note, that the value used for checking must have been initialised previously or else you will get an error causing GameMaker: Studio to close.

Example:

if background_exists(bck_array[0])
{
background_index[0] = bck_array[0];
}
else
{
background_index[0] = bck_Base;
}

The above code checks an array to see if it contains a valid background index and if so it assigns that background to the current room, but if not, it assigns a background from the included resources.

Back: Backgrounds
Next: background_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_flush

Flush a background asset (and the texture page it's on) from memory.

Syntax:

background_flush(ind);

Argument | Description
ind | The index (resource name) of the background asset to flush

Returns: N/A

Description

With this function you can remove the given background texture - and the texture page it is on - from video memory (the texture page will be reloaded on next use). You supply the background index (as defined when creating the background resource) and it will be removed from the texture memory. It is worth noting that by default on the Windows platforms (YYC and standard) all textures will always be loaded into memory on start-up. If you are making a cross platform game, then you can leave this function in your code for the Windows target as it will not give any error and just not do anything. However you can also force the Windows target to not load any textures on startup and so use the flush and prefetch functions as you would on all other platforms (the setting can be found in the Windows Global Game Settings window).

NOTE: There is a performance hit as the texture is uploaded to texture memory on most devices, so you can call background_prefetch on any required graphics at the start of a level to avoid any stalls.

Example:

background_flush(bck_Trees);

The above code flushes the background "bck_Trees" from memory.

Back: Backgrounds
Next: background_flush_multi
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_flush_multi

Flush multiple background assets (and their assigned texture pages) from memory.

Syntax:

background_flush(array);

Argument | Description
array | Array with the background indices to flush

Returns: N/A

Description

With this function you can remove any number of background textures - and the texture pages they are assigned to - from video memory (their texture pages will be reloaded on next use of any background from them). You supply an array of background asset indices and they will be removed from memory when the function is called. It is worth noting that by default on the Windows platforms (YYC and standard) all textures will always be loaded into memory on start-up. If you are making a cross platform game, then you can leave this function in your code for the Windows target as it will not give any error and just not do anything. However you can also force the Windows target to not load any textures on startup and so use the flush and prefetch functions as you would on all other platforms (the setting can be found in the Windows Global Game Settings window).

Example:

bck_a[0] = bck_Trees;
bck_a[1] = bck_Clouds;
bck_a[2] = bck_Mountains;
bck_a[3] = bck_Tileset;
background_flush_multi(bck_a);

The above code creates an array where each element holds a background index. This array is then used to clear those background textures from memory.

Back: Backgrounds
Next: background_prefetch
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_foreground

This variable determines if one of the 8 backgrounds for the current room is a foreground.

Syntax:

background_foreground[0...7];

Returns: Real

Description

Although we call these image assets "backgrounds", with this flag we can set them to be foregrounds too... ie: if this variable array is set to true the image stored in the background_index will be shown on top of all other things in the game.

Example:

if intro
{
background_foreground[0] = true;
}
else
{
background_foreground[0] = false;
}

Back: Backgrounds
Next: background_hspeed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_get_height

Finds the height of a background.

Syntax:

background_get_height(index);

Argument | Description
index | The index of the background to find the height of.

Returns: real

Description

With this function you can find the height of the base background asset, with no transforms, in pixels.

Example:

if background_height[0] != background_get_height(background_index[0])
{
background_height[0] = background_get_height(background_index[0]);
}

The above code checks the height of the background as it is in the current room and if there is a difference between that and the original base background, it resets the height.

Back: Backgrounds
Next: background_get_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_get_name

Gets the name of a background.

Syntax:

background_get_name(index);

Argument | Description
index | The background image asset to get the name of.

Returns: String

Description

This function will return the name as a string of the specified background. This name is the one that has been specified for the background in the resource tree of the main GameMaker: Studio window. Please note that this is only a string and cannot be used to reference the background directly - for that you would need the background index. You can, however, use this string to get the background index using the returned string along with the function asset_get_index().

Example:

name = background_get_name(bck_1);

The above code gets the name of the background asset indexed in "bck_1" and stores it as a string in the instance variable "name".

Back: Backgrounds
Next: background_get_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_get_texture

Returns the texture id for the given background.

Syntax:

background_get_texture(back);

Argument | Description
back | The index of the background to use.

Returns: Pointer

Description

This function returns a pointer for the background texture page. This value can then be used in other draw functions, particularly in general 3D and some of the 2D primitive functions, as well as the Shader functions. You can get more information about the returned texture page using the different texture_ functions found here.

Example:

var tex;
tex = background_get_texture(back);
draw_primitive_begin_texture(pr_trianglestrip, tex);
draw_vertex_texture(0, 480, 0, 0);
draw_vertex_texture(640, 480, 1, 0);
draw_vertex_texture(640, 480, 1, 1);
draw_vertex_texture(0, 480, 0, 1);
draw_primitive_end();

The above code will draw a 4 vertex triangle strip textured with the texture held in the "tex" variable.

Back: Backgrounds
Next: background_get_uvs

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_get_uvs

Returns the texture coordinates of the background within the texture page as an array.

Syntax:

background_get_uvs(back);

Argument | Description
back | The index of the background to use.

Returns: Array

Description

This function returns an array with the UV coordinates for the texture on the texture page, filling in the array with the following values: [0] = left, [1] = top, [2] = right and [3] = bottom. This value can then be used in other draw functions, particularly in general 3D and some of the 2D primitive functions, as well as the Shader functions.

Example:

var tex = background_get_uvs(back);
tex_left = tex[0];
tex_top = tex[1];
tex_right = tex[2];
tex_bottom = tex[3];

The above code will store the UV coordinates for the given background in a local array and then assign the values to instance variables.

Back: Backgrounds
Next: background_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_get_width

Finds the width of a background.

Syntax:

background_get_width(index);

Argument | Description
index | The index of the background to find the width of.

Returns: Real

Description

With this function you can find the width of the base background asset, with no transforms, in pixels.

Example:

if background_width[0] != background_get_width(background_index[0])
{
background_width[0] = background_get_width(background_index[0]);
}

The above code checks the width of the background as it is in the current room and if there is a difference between that and the original base background, it resets the width.

Back: Backgrounds
Next: background_get_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_height

Returns the height of the background with the given index in the current room.

Syntax:

background_height[0...7];

Returns: Real

Description

This read only variable returns the height of the image that has been used for the background_index of the same array value. Should you need to make a background fit a specific height, you should change the background_yscale.

Example:

if room_height != background_height[0]
{
background_yscale[0] = 1 * (room_height / background_height[0]);
}

The above code will scale background to fit the height of the room.

Back: Backgrounds
Next: background_xscale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_hspeed

Variable that determines the horizontal scrolling speed for a background.

Syntax:

background_hspeed[0...7];

Returns: Real

Description

By setting this variable array to a different value, you can set the speed at which GameMaker: Studio automatically scrolls a background for you along the horizontal plane. A positive value will scroll from left to right, while a negative value will be right to left and 0 stops all scrolling. if you have also enabled horizontal tiling, either through the room editor or by using the background_htiled variable, then scrolling the background will make it loop infinitely.

Example:

if background_htiled[0]
{
background_hspeed[0] = 2;
}

The above code checks background0 to see if it is tiled horizontally, and if it is it then sets the horizontal scroll speed to 2.

Back: Backgrounds
Next: background_vspeed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_htiled

Variable that determines if a background should be tiled horizontally or not.

Syntax:

background_htiled[0...7];

Returns: Boolean

Description

By setting this variable array to true you can tell GameMaker: Studio to tile the background image for the selected background along the horizontal plane. This will make any moving backgrounds appear infinite, or simply repeat the same image over the width of the room if it is a static background. Setting this to false will disable tiling.

Example:

if background_htiled[0]
{
background_hspeed[0] = 2;
}

The above code checks background0 to see if it is tiled horizontally, and if it is it then sets the horizontal scroll speed to 2.

Back: Backgrounds
Next: background_vtiled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_prefetch

Fetch the texture page for a given background asset.

Syntax:

background_prefetch(ind);

Argument | Description
ind | The background index to fetch

Returns: N/A

Description

This function can be used to prefetch (place into texture memory) a texture page with the given background. You supply the background index as defined when you created the background asset, and the texture page it is on will be loaded into memory.

NOTE: There is a performance hit as the texture is uploaded to texture memory on most devices, so it's recommended that you call background_preftech on any required graphics at the start of a level to avoid any stalls.

Example:

background_prefetch(bck_Trees);

The above code will place the referenced background into texture memory ready for use.

Back: Backgrounds
Next: background_prefetch_multi
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_prefetch_multi

Fetch multiple texture pages for a number of background assets.

Syntax:

background_prefetch_multi(array);

Argument | Description
array | Array with the background indices to fetch

Returns: N/A

Description

This function can be used to prefetch (place into texture memory) a number of texture pages that contain the background given. You supply an array populated with the background indices (as defined when you created the background asset) and the texture pages that they are on will be loaded into memory.

NOTE: There is a performance hit as the texture is uploaded to texture memory on most devices, so it's recommended that you call background_preftech_multi on any required graphics at the start of a level to avoid any stalls.

Example:

bck_a[0] = bck_Trees;
bck_a[1] = bck_Clouds;
bck_a[2] = bck_Mountains;
bck_a[3] = bck_Tileset;
background_prefetch_multi(bck_a);

The above code creates an array where each element holds a background index. This array is then used to place those background textures into memory.

Back: Sprites
Next: background_exists
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_replace

Replace a background resource with another one.

Syntax:

background_replace(ind, fname);

Argument | Description
ind | The index of the background to permanently replace.
fname | The filename of the image to make the new background.
removeback | Indicates whether to make all pixels with the same colour (left-bottom pixel) transparent.
smooth | Indicates whether to smooth the edges.

Returns: N/A

Description

This function works in almost the exact same manner as background_add, only instead of returning the index of the background you are importing, it overwrites a previously created background index. The background index to be replaces is one that has been created and stored in a variable using other functions like background_add or background_create_from_surface. You can not use one from the resource tree as you cannot replace built-in assets.

NOTE: Depending on the target platform that is chosen you are limited as to where you can save and load files from. See Reference - Files for more information.

NOTE: You should be aware that if you are using this function in your HTML5 target game to load resources from an external server, then, due to XSS protection in browsers, attempts to load resources from across domains can be blocked and may appear to return blank results.

Example:

background_replace(bck_Sky, "Sky_5.png");

The above code will replace the image asset indexed in "spr_Sky" with another one loaded from an external source.

Back: Backgrounds
Next: background_duplicate

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_save

Save a background to disc.

Syntax:

background_save(back, fname);

Argument | Description
ind | The index of the background to save.
fname | The filename for the saved background.

Returns: N/A

Description

This function can be used to save any background to disc, giving it the specified filename. This image must be a *.png file.

NOTE: Depending on the target platform that is chosen you are limited as to where you can save and load files from. See Reference - Files for more information.

Example:

background_save(bck, "Custom_Back.png");

The above code will save the background indexed in the variable "bck" as a *.png.

Back: Backgrounds
Next: background_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_set_alpha_from_background

Changes the alpha (transparency) of one given background based on the intensity/value map of another.

Syntax:

background_set_alpha_from_background(ind, back);

Argument | Description
ind | The index of the background to change the transparency map of.
back | The index of the background to take the transparency map data from.

Returns: N/A

Description

This function uses the value/saturation of one background and multiplies it with the alpha of the target background. Ideally the background being used to generate the new alpha map should be greyscale, with the white areas having an equivalent alpha value of 1 (opaque), the black areas being equivalent to alpha 0 (transparent), and the grey areas being an alpha in between 0 and 1. The background that you are setting the alpha of cannot be a permanent resource as this will give an error, so you should be using the background_duplicate function first to duplicate the resource and then set the alpha on that. You will also need to duplicate the source image to be used with the same function, then set the alpha using both the duplicated images. Below is an image that illustrates how this function works with sprites, but the same is true for backgrounds:

Example:

bck = background_duplicate(bck_Clouds);
var t_bck = background_duplicate(bck_Clouds_Alpha);
background_set_alpha_from_background(bck, t_bck);
background_delete(t_bck);

The above code duplicates two background resources and then changes the first one's alpha using the value/saturation of the colour data from the resource "bck_Clouds_Alpha". The temporary background that was created to hold the "bck_Clouds_Alpha" data is then deleted to free up its memory.

Back: Backgrounds
Next: background_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_showcolour

This variable determines if the current room's background colour should be drawn.

Syntax:

background_showcolour

Returns: Boolean

Description

When in a room, it can have no background image selected for any of its background_index, in which case you should set a background colour with the background_colour variable and make sure that it is visible by setting this variable is set to true. Having a room with no background image and no background colour will result in graphical artefacts being drawn on the screen and is not recommended.

Example:

if background_index[0] == -1
{
background_colour = c_black;
background_showcolour = true;
}

The above code checks to see if background0 has an image assigned to it and if not it sets the background colour to black and flags it to be shown.

Back: Backgrounds
Next: background_foreground

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_visible

Returns or sets the visibility of any background within a room.

Syntax:

background_visible[0...7]

Returns: Real

Description

This variable array returns whether any one of the 8 backgrounds (numbered form 0 - 7 within the array) of the current room is visible. It can be set to true or false to toggle the visibility of the selected background in the room too.

Example:

if !background_visible[0] false background_visible[0] = true;

The above code checks the current visibility of the background0 in the current room and if it is not visible, it changes the flag to true, thus making it visible.

Back: Backgrounds
Next: background_alpha

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_vspeed

Variable that determines the vertical scrolling speed for a background.

Syntax:

background_vspeed[0...7];

Returns: Real

Description

By setting this variable array to a different value, you can set the speed at which GameMaker: Studio automatically scrolls a background for you along the vertical plane. A positive value will scroll from top to bottom, while a negative value will be bottom to top and 0 stops all scrolling. if you have also enabled vertical tiling, either through the room editor or by using the background_vtiled variable, then scrolling the background will make it loop infinitely.

Example:

if background_vtiled[0] = true
{
background_vspeed[0] = 2;
}

The above code checks background0 to see if it is tiled vertically, and if it is it then sets the vertical scroll speed to 2.

Back: Backgrounds
Next: background_htiled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_vtiled

Variable that determines if a background should be tiled vertically or not.

Syntax:

background_vtiled[0...7]

Returns: Real

Description

By setting this variable array to true you can tell GameMaker: Studio to tile the background image for the selected background along the vertical plane. This will make any moving backgrounds appear infinite, or simply repeat the same image over the height of the room if it is a static background. Setting this to false will disable tiling.

Example:

if background_vtiled[0]
{
background_vspeed[0] = 2;
}

The above code checks background0 to see if it is tiled vertically, and if it is it then sets the vertical scroll speed to 2.

Back: Backgrounds
Next: background_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_width

Returns the width of the background with the given index in the current room.

Syntax:

background_width[0...7]

Returns: Real

Description

This read only variable returns the width of the image that has been used for the background_index of the same array value. Should you need to make a background fit a specific width, you should change the background_xscale.

Example:

if room_width != background_width[0]
{
background_xscale[0] = 1 * (room_width / background_width[0]);
}

The above code will scale background to fit the width of the room.

Back: Backgrounds
Next: background_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_x

Returns or sets the x position of any background within a room.

Syntax:

background_x[0...7]

Returns: Real

Description

This variable array returns the x position within the room of any one of the 8 backgrounds (numbered form 0 - 7 within the array) of the current room. You can use this variable to position backgrounds at specific places within a room, even when the background being used is also tiled vertically or horizontally (in which case the whole "sheet" of tiled backgrounds will be moved).

Example:

background_x[0] = view_xview[0];
background_y[0] = view_yview[0]-50;
background_x[1] = view_xview[0]/2;
background_y[1] = view_yview[0]/2+335;
background_x[2] = view_xview[0]/8;
background_y[2] = view_yview[0]/8+500;

The above code changes the x and y values of three backgrounds in a room based on the position of the view (this effect is called parallax scrolling).

Back: Backgrounds
Next: background_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_xscale

This variable controls the scaling along the x axis of the given background number.

Syntax:

background_xscale[0...7]

Returns: Real

Description

This variable returns the x axis scale of the image that has been used for the background_index of the same array value. The default value is 1, but this can be set to other values to stretch the background image.

NOTE: You cannot scale backgrounds in any way when using the HTML5 target module without having first enabled WebGL (in the Global Game Settings).

Example:

if room_width != background_width[0]
{
background_xscale[0] = 1 * (room_width / background_width[0]);
}

The above code will scale background to fit the width of the room.

Back: Backgrounds
Next: background_yscale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_y

Returns or sets the y position of any background within a room.

Syntax:

background_y[0...7]

Returns: Real

Description

This variable array returns the y position within the room of any one of the 8 backgrounds (numbered form 0 - 7 within the array) of the current room. You can use this variable to position backgrounds at specific places within a room, even when the background being used is also tiled vertically or horizontally (in which case the whole "sheet" of tiled backgrounds will be moved).

Example:

background_x[0] = view_xview[0];
background_y[0] = view_yview[0]-50;
background_x[1] = view_xview[0]/2;
background_y[1] = view_yview[0]/2+335;
background_x[2] = view_xview[0]/8;
background_y[2] = view_yview[0]/8+500;

The above code changes the x and y values of three backgrounds in a room based on the position of the view (this effect is called parallax scrolling).

Back: Backgrounds
Next: background_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


background_yscale

This variable controls the scaling along the y axis of the given background number.

Syntax:

background_yscale[0...7]

Returns: Real

Description

This variable returns the y axis scale of the image that has been used for the background_index of the same array value. The default value is 1, but this can be set to other values to stretch the background image.

NOTE: You cannot scale backgrounds in any way when using the HTML5 target module without having first enabled WebGL (in the Global Game Settings).

Example:

if room_height != background_height[0]
{
background_yscale[0] = 1 * (room_height / background_height[0]);
}

The above code will scale background to fit the height of the room.

Back: Backgrounds
Next: background_index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Background Tiles

This section has all the functions related to using tiles.

Tiles are made from large background images that GameMaker: Studio splits into parts based on the parameters that you input. These parts are classed as individual tiles and can be used for many different things. Due to the fact that they are a purely graphic resource they are very fast to draw (they have far fewer internal variables associated with them, unlike instances) and large numbers can be used in a game to add details and life to a level, however you should still try and limit the number of different layers (depths) that are used at any one time and keep them to the minimum necessary.

Tile Layers

Tiles are drawn by depth, where lower depths appear on top of higher depths. Each depth is called a layer and there are a number of functions that can be used to get information about tile layers and to move them around:

  1. tile_layer_depth
  2. tile_layer_find
  3. tile_layer_hide
  4. tile_layer_show
  5. tile_layer_shift
  6. tile_layer_delete
  7. tile_layer_delete_at

Tile Information

The following functions can be used to get specific information about a single tile in the game (you can use the function tile_layer_find to get the index of a single tile to use in these functions):

  1. tile_get_background
  2. tile_get_alpha
  3. tile_get_visible
  4. tile_get_blend
  5. tile_get_depth
  6. tile_get_width
  7. tile_get_height
  8. tile_get_left
  9. tile_get_top
  10. tile_get_x
  11. tile_get_y
  12. tile_get_xscale
  13. tile_get_yscale
  14. tile_get_count
  15. tile_get_id
  16. tile_get_ids
  17. tile_get_ids_at_depth

Tile Manipulation

The following functions can be used to add and remove tiles at runtime, as well as to set individual tile properties:

  1. tile_exists
  2. tile_add
  3. tile_delete
  4. tile_set_background
  5. tile_set_visible
  6. tile_set_alpha
  7. tile_set_blend
  8. tile_set_depth
  9. tile_set_position
  10. tile_set_region
  11. tile_set_scale

Back: Backgrounds

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_add

Adds a new tile to the room, allowing customisation of its attributes, and returning its index.

Syntax:

tile_add(background, left, top, width, height, x, y, depth);

Argument | Description
background | The background asset from which the new tile will be extracted.
left | The x coordinate of the left of the new tile, relative to the background asset's top left corner.
top | The y coordinate of the top of the new tile, relative to the background assets top left corner.
width | The width of the tile.
height | The height of the tile.
x | The x position in the room to place the tile.
y | The y position in the room to place the tile.
depth | The depth at which to place the tile.

Returns: Real

Description

With this function you can add a tile into the game at any position within the room. You need to give it a background image as a base asset and the position within that image to extract the tile, then a position within the room and a depth to place it at. The function returns the unique index number for that tile that should be stored in a variable if you plan to change it in any way later (however, you can also get this index at a later date by using the tile_layer_find function).

Example:

tile_add(back0, 0, 0, 32, 32, 64, 64, 99999);

Takes a 32x32 pixel area from (0,0) of back0, placing it at (64,64) in the room at a depth of 99999.

Back: Background Tiles
Next: tile_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_delete

Deletes a given tile in the room.

Syntax:

tile_delete(index);

Argument | Description
index | The index of the tile to delete.

Returns: N/A

Description

With this function you can remove a tile from the current room. This is not permanent and if the player leaves the room and returns to it again, the tile will be recreated again (if it was placed in the room editor and the room is not persistent).

Example:

if mouse_check_button_pressed(mb_left)
{
var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
if tile_exists(tile) tile_delete(tile);
}

The above code will check for a press of the left mouse button, and then check the mouse position for a tile. If there is one found, that tile is deleted from the room.

Back: Background Tiles
Next: tile_set_background

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_exists

Checks if a given tile exists in the room.

Syntax:

tile_exists(index);

Argument | Description
index | The index of the tile to check for.

Returns: Boolean

Description

With this function you can check wither the tile indexed exists in the room or not. Please note that if you check for a tile by its id and its id is uninitialised, an error will be thrown.

Example:

if !tile_exists(tile)
{
tile = tile_add(bck_Room1, 0, 0, 32, 32, mouse_x, mouse_y, -1100);
}

The above code checks to see if a tile that was indexed in the variable "tile" still exists in the room, and if it does not it creates a new tile at the mouse position and stores the new index in the variable "tile".

Back: Background Tiles
Next: tile_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_alpha

Returns the alpha value of a given tile.

Syntax:

tile_get_alpha(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

This function returns the current alpha value for the given tile, alpha is the "transparency" of the image and is measured from 0 to 1, where 0 is completely transparent and 1 is completely opaque.

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
alpha = tile_get_alpha(tile);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store the alpha value in the variable "alpha".

Back: Background Tiles
Next: tile_get_visible

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_background

Returns the background index a given tile is drawn from.

Syntax:

tile_get_background(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

With this function you can get the background_index from which the tile is taken. Please note that this function returns the index (unique identifier) which is a number and not the name of the background asset, which would be a string.

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
back = tile_get_background(tile);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store the background index of the asset it was created from in the variable "back".

Back: Background Tiles
Next: tile_get_alpha

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_blend

Returns the blending colour of a given tile.

Syntax:

tile_get_blend(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

With this function you can get the blend colour that is currently being used for the specified tile. The default value is -1 (c_white).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
if tile_get_blend(tile) != -1
{
tile_set_blend(tile, c_white);
}

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to check whether the tile is blended or not, and if it is it sets the blend colour to white (default).

Back: Background Tiles
Next: tile_get_depth

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_count

Returns the total number of tiles in a room.

Syntax:

tile_get_count();

Returns: Real

Description

With this function you can get the total number of tiles, from all layers, in a room.

Example:

var num = tile_get_count();
for (var i = 0; i < num; i++;)
{
tile_set_blend(tile_get_id(i), c_red);
}

The above code will get the total number of tiles in a room, then loop through them one at a time and set their blend colour to red.

Back: Background Tiles
Next: tile_get_id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_depth

Returns the depth of a given tile.

Syntax:

tile_get_depth(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

With this function you can get the draw depth of the specified tile.

Example:

var tile, i;
for (i = 0; i > -1000; i -=1;)
{
tile = tile_layer_find(i, mouse_x, mouse_y);
if tile_get_depth(tile) != -500
{
tile_set_depth(tile, -500);
}
}

The above code will loop through the tile layers from 0 to -1000 an get the index of any tile at the mouse position. It will then use that value to check whether the tile is at depth -500, and if it is not, it sets the depth to -500.

Back: Background Tiles
Next: tile_get_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_height

Returns the height of a given tile.

Syntax:

tile_get_height(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

With this function you can get the height (in pixels) of the specified tile.

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
hh = tile_get_height(tile);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store the height of the asset in the variable "hh".

Back: Background Tiles
Next: tile_get_left

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_id

Returns the unique id for the given tile index.

Syntax:

tile_get_id(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

You can use this function to get the unique tile "id" which can then be used in other functions like tile_get_xscale, tile_set_alpha(), etc... The "index" argument that the function takes is a real number from 0 up to the number of tiles in the room (which you can find using the tile_get_count() function) and the function will return the corresponding tile id or -1 if no tile with the given index exists.

Example:

var num = tile_get_count();
for (var i = 0; i < num; i++;)
{
tile_set_depth(tile_get_id(i), -1000);
}

The above code will get the total number of tiles in a room, then loop through them one at a time and set their depth to -1000.

Back: Background Tiles
Next: tile_get_ids

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_ids

Returns an array containing the unique ID values for all tiles in a room.

Syntax:

tile_get_ids();

Returns: Array

Description

You can use this function to get the unique tile "id" for all tiles in a room, regardless of their depth. The function will return a 1D array, with each entry being the ID value for a single tile.

Example:

var tiles = tile_get_ids();
for (var i = 0; i < array_length_1d(tiles); i++;)
{
tile_set_alpha(tiles[i], 0.5);
}

The above code will get the ID of all tiles in a room and populate the array "tiles" with them, before looping through the array and setting the alpha of each tile to a new value.

Back: Background Tiles
Next: tile_get_ids

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_ids_at_depth

Returns an array containing the unique ID values for all tiles at a given depth.

Syntax:

tile_get_ids_at_depth(depth);

Argument | Description
depth | The depth of the tile layer to get the IDs of.

Returns: Array

Description

You can use this function to get the unique tile "id" for all tiles placed at a given depth. The function will return a 1D array, with each entry being the ID value for a single tile.

Example:

var tiles = tile_get_ids_at_depth(1000);
for (var i = 0; i < array_length_1d(tiles); i++;)
{
tile_set_alpha(tiles[i], 0.5);
}

The above code will get the total number of tiles on the layer at depth 1000, then loop through them one at a time and set their alpha to 0.5.

Back: Background Tiles
Next: tile_get_background

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_left

Returns the left coordinate of a given tile from its background.

Syntax:

tile_get_left(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

This function is used to get the left (x axis) local position within the background image asset of the specified tile. It is important to realise that the value returned is in relation to the background image used to create the tile, where the top left corner is the (0,0) position, and is not the position of the resource within the room.

Example:

var tile, ww, hh, ll, tt;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
ww = tile_get_width(tile);
hh = tile_get_height(tile);
ll = tile_get_left(tile);
tt = tile_get_top(tile);
tile_add(bck_Tileset, ll, tt, ww, hh, posx, posy, -1000);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store various attributes in local variables. These attributes are then used to add a new tile into the room.

Back: Background Tiles
Next: tile_get_top

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_top

Returns the top coordinate of a given tile from its background.

Syntax:

tile_get_top(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

This function is used to get the top (y axis) local position within the background image asset of the specified tile. It is important to realise that the value returned is in relation to the background image used to create the tile, where the top left corner is the (0,0) position, and is not the position of the resource within the room.

Example:

var tile, ww, hh, ll, tt;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
ww = tile_get_width(tile);
hh = tile_get_height(tile);
ll = tile_get_left(tile);
tt = tile_get_top(tile);
tile_add(bck_Tileset, ll, tt, ww, hh, posx, posy, -1000);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store various attributes in local variables. These attributes are then used to add a new tile into the room.

Back: Background Tiles
Next: tile_get_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_visible

Returns whether a tile is visible or not.

Syntax:

tile_get_visible(index);

Argument | Description
index | The index of the tile to check.

Returns: Boolean

Description

This function returns the current visibility for the given tile, where true is visible and false is invisible.

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
if !tile_get_visible(tile)
{
tile_set_visible(tile, true);
}

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to check whether the tile is visible or not, and if not set the tile to visible.

Back: Background Tiles
Next: tile_get_blend

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_width

Returns the width of a given tile.

Syntax:

tile_get_width(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

With this function you can get the width (in pixels) of the specified tile.

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
ww = tile_get_width(tile);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store the width of the asset in the variable "ww".

Back: Background Tiles
Next: tile_get_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_x

Returns the x coordinate of a given tile.

Syntax:

tile_get_x(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

This function will return the x axis position within the current room of the given tile.

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
xx = tile_get_x(tile);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store its x axis position within the variable "xx".

Back: Background Tiles
Next: tile_get_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_xscale

Returns the horizontal scaling of a given tile.

Syntax:

tile_get_xscale(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

Tiles, like instances, can be scaled once created, and this function will return the scaling amount along the horizontal axis (where 1 is the default value).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
xs = tile_get_xscale(tile);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store its horizontal scale within the variable "xs".

Back: Background Tiles
Next: tile_get_yscale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_y

Returns the y coordinate of a given tile.

Syntax:

tile_get_y(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

This function will return the y axis position within the current room of the given tile.

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
yy = tile_get_y(tile);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store its y axis position within the variable "yy".

Back: Background Tiles
Next: tile_get_xscale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_get_yscale

Returns the vertical scaling of a given tile.

Syntax:

tile_get_yscale(index);

Argument | Description
index | The index of the tile to check.

Returns: Real

Description

Tiles, like instances, can be scaled once created, and this function will return the scaling amount along the vertical axis (where 1 is the default value).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
ys = tile_get_xscale(tile);

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to store its vertical scale within the variable "ys".

Back: Background Tiles
Next: tile_get_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_layer_delete

Deletes all tiles at the indicated depth layer.

Syntax:

tile_layer_delete(depth);

Argument | Description
depth | The depth of tiles which is to be deleted.

Returns: N/A

Description

With this function you can remove a whole tile layer from the current room. This is not permanent and if the player leaves the room and returns to it again, the tile layer will be recreated (unless the room is persistent).

Example:

if keyboard_check_pressed(ord("D"))
{
tile_layer_delete(-1000);
}

The above code will delete the tile layer with depth -1000 when the player pressed the "D" key on the keyboard.

Back: Background Tiles
Next: tile_layer_delete_at

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_layer_delete_at

Deletes the tile(s) at a given depth and position.

Syntax:

tile_layer_delete_at(depth, x, y);

Argument | Description
depth | The depth of a tile to be deleted.
x | The x position at which to delete a tile.
y | The y position at which to delete a tile.

Returns: Real

Description

With this function you can delete only those tiles that overlap with the given point and that are on the specified depth. This is not permanent and if the player leaves the room and returns to it again, the tile layer will be recreated (unless the room is persistent).

Example:

var i;
i = 1000;
repeat(3)
{
tile_layer_delete_at(i, mouse_x, mouse_y);
i -= 1000;
}

The above code will loop through three different tile depths and delete any tiles that are found at the mouse x/y position.

Back: Background Tiles
Next: tile_layer_depth

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_layer_depth

Moves all tiles at a given depth to a new depth.

Syntax:

tile_layer_depth(depth, newdepth);

Argument | Description
depth | The current depth of the tile layer.
newdepth | The depth to change the layer to.

Returns: N/A

Description

With this function you can change the draw depth of a whole layer of tiles.

Example:

if change
{
tile_layer_depth(10000, -10000);
}
else
{
tile_layer_depth(-10000, 10000);
}

The above code will set the depth of a tile layer depending on whether a variable returns true or false.

Back: Background Tiles
Next: tile_layer_find

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_layer_find

Returns the id of a tile at a given depth and position.

Syntax:

tile_layer_find(depth, x, y);

Argument | Description
depth | The depth of the tile to be found.
x | The x position to check.
y | The y position to check.

Returns: Real

Description

All tiles that are placed in a room are given a unique identifying number (or index) which must be used in the functions that change specific tile properties. To get the index, you can use this function which returns the index number of the tile found at the specified depth and position (or it returns -1 if no tile has been found).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
if tile != -1
{
tile_delete(tile);
}

The above code will check the mouse position for a tile at the depth -10000, and if it finds one it is deleted.

Back: Background Tiles
Next: tile_layer_hide

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_layer_hide

Hides all tiles at the indicated depth layer.

Syntax:

tile_layer_hide(depth);

Argument | Description
depth | The depth of tiles which is to be hidden.

Returns: N/A

Description

Tiles, like backgrounds and other image assets, can be visible or not. This function can be used to turn all the tiles at a certain depth invisible so that they are no longer drawn on the screen.

Example:

tile_layer_hide(-1000);

The above code will hide the tiles with a depth of -1000.

Back: Background Tiles
Next: tile_layer_show

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_layer_shift

Shifts all tiles at the indicated depth layer by a given amount.

Syntax:

tile_layer_shift(depth, x, y);

Argument | Description
depth | The depth of tiles which is to be shifted.
x | The amount to shift over the x-axis.
y | The amount to shift over the y-axis

Returns: N/A

Description

This function can be used to move a whole tile layer. It works by shifting the layer by the specified amount over each axis, with a positive x shift moving right, a negative x shift moving left, a positive y shift moving down and a negative y shift moving up. Please note that the values move the tile layer relative to its position and are not absolute, so setting the (x,y) values to, for example, (32,32) will move the tile layer down and right by 32 pixels, it will not position it at (32,32) in the room.

Example:

tile_layer_shift(-1000, obj_Player.hspeed, 0);

The above code will shift the tile layer at depth -1000 by the same amount as the horizontal speed of the instance of object "obj_Player".

Back: Background Tiles
Next: tile_layer_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_layer_show

Shows all tiles at the indicated depth layer.

Syntax:

tile_layer_show(depth);

Argument | Description
depth | The depth of tiles which is to be shown.

Returns: Real

Description

Tiles, like backgrounds and other image assets, can be visible or not. This function can be used to turn all the tiles at a certain depth visible so that they are drawn on the screen.

Example:

tile_layer_show(-1000);

The above code will show the tiles with a depth of -1000.

Back: Background Tiles
Next: tile_layer_shift

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_set_alpha

Sets a tile's alpha (transparency).

Syntax:

tile_set_alpha(index, alpha);

Argument | Description
index | The index of the tile to set.
alpha | The transparency of the tile.

Returns: N/A

Description

With this function you can set the alpha value (transparency) of individual tiles. This can be anywhere between 0 and 1, where 0 is completely transparent and 1 is completely opaque. This is not permanent and if the player leaves the room and returns to it again, the tile will have it s original alpha value (if it was placed in the room editor and the room is not persistent).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
if tile_get_alpha(tile) < 1
{
tile_set_alpha(tile, 1);
}

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to check whether the tile alpha is less than 1 or not, and if it is it sets the tile alpha to 1.

Back: Background Tiles
Next: tile_set_blend

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_set_background

Sets the background for a tile to be drawn from.

Syntax:

tile_set_background(index, background);

Argument | Description
index | The index of the tile to set.
background | The index of the background to take the tile from.

Returns: N/A

Description

With this function you can change the background image asset that the tile is taken from (maintaining the tile in the room, at the same position but with a different graphic). This is not permanent and if the player leaves the room and returns to it again, the tile will use the original background again (if it was placed in the room editor and the room is not persistent).

Example:

if mouse_check_button_pressed(mb_left)
{
var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
if tile_exists(tile) tile_set_background(tile, bck_Forest);
}

The above code will check for a press of the left mouse button, and then check the mouse position for a tile. If there is one found, that tile has its background asset changed.

Back: Background Tiles
Next: tile_set_visible

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_set_blend

Sets a tile's blending.

Syntax:

tile_set_blend(index, colour);

Argument | Description
index | The index of the tile to set.
colour | The colour to blend the tile with.

Returns: N/A

Description

With this function you can set a colour to be blended with the tile. The default value for the blend colour is -1 (which represents the constant c_white) but any colour value can be used. This is not permanent and if the player leaves the room and returns to it again, the tile will have it s original blend colour (if it was placed in the room editor and the room is not persistent).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
if tile_get_blend(tile) != -1
{
tile_set_blend(tile, c_white);
}

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to check whether the tile blend is anything other than the default -1. If it is it sets the tile blend to white (no blending).

Back: Background Tiles
Next: tile_set_depth

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_set_depth

Sets a tile's depth.

Syntax:

tile_set_depth(index, depth);

Argument | Description
index | The index of the tile to set.
depth | The depth of the tile.

Returns: N/A

Description

With this function you can set the depth of a specific tile. This is not permanent and if the player leaves the room and returns to it again, the tile will have its original depth (if it was placed in the room editor and the room is not persistent).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
tile_set_depth(tile, 1000);

The above code will check the mouse position for a tile and store its index in a variable. This is then used to set the depth of the tile.

Back: Background Tiles
Next: tile_set_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_set_position

Sets the position of a given tile.

Syntax:

tile_set_position(index, x, y);

Argument | Description
index | The index of the tile to set.
x | The tile's new x position.
y | The tile's new y position.

Returns: N/A

Description

With this function you can move a tile from one part of the room to another by setting the (x,y) coordinates. These are absolute coordinates within the room, and the origin of a tile is always the top left corner, so setting the tile position to, for example, (64,45) will position the top left corner of the tile at that position. This is not permanent and if the player leaves the room and returns to it again, the tile will have its original position (if it was placed in the room editor and the room is not persistent).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
tile_set_position(tile, mouse_x - 100, mouse_y - 100);

The above code will check the mouse position for a tile and store its index in a variable. This is then used to set the position of the tile to the mouse position minus 100.

Back: Background Tiles
Next: tile_set_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_set_region

Sets the region of its background a tile is taken from.

Syntax:

tile_set_region(index, left, top, width, height);

Argument | Description
index | The index of the tile to set.
left | The tile's left position relative to the background's top left corner.
top | The tile's top position relative to the background's top left corner.
width | The tile's width.
height | The tile's height.

Returns: N/A

Description

With this function you can resize the tile indexed. For example, if you have a tile that is a 16x16 square taken from a background image asset and then use this function to set the region to 16x32, the tile will now be a rectangular section of the background. this function does not scale the image in anyway, it changes the shape of the area used to create the tile. This is not permanent and if the player leaves the room and returns to it again, the tile will have its original shape (if it was placed in the room editor and the room is not persistent).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
tile_set_region(tile, 0, 0, 32, 64);

The above code will check the mouse position for a tile and store its index in a variable. This is then used to set the region of the tile to a different part of the background asset it uses.

Back: Background Tiles
Next: tile_set_scale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_set_scale

Sets a tile's horizontal and vertical scaling.

Syntax:

tile_set_scale(index, xscale, yscale);

Argument | Description
index | The index of the tile to set.
xscale | The tile's horizontal scale.
yscale | The tile's vertical scale.

Returns: N/A

Description

With this function you can scale a tile which will draw the tile image stretched by the given amount (with 1 being the default horizontal and vertical scale).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
if tile_get_xscale(tile) != 1 || tile_get_yscale(tile) !=1
{
tile_set_scale(tile, 1, 1);
}

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to check whether the tile x and y scale is anything other than 1, and if it is it sets the tile scale to 1.

Back: Background Tiles
Next: tile_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tile_set_visible

Sets a tile's visibility.

Syntax:

tile_set_visible(index, visible);

Argument | Description
index | The index of the tile to set.
visible | The visibility of the tile. true=visible, false=invisible.

Returns: N/A

Description

Like instances, tiles can be flagged as visible or invisible. This function can change that flag, and by setting it to true you make the tile visible, or by setting it to false you can set it to invisible. This is not permanent and if the player leaves the room and returns to it again, the tile will be visible (if it was placed in the room editor and the room is not persistent).

Example:

var tile;
tile = tile_layer_find(-1000, mouse_x, mouse_y);
if !tile_get_visible(tile)
{
tile_set_visible(tile, true);
}

The above code will first get the index of a tile at the mouse position with a depth of -1000 and then use that value to check whether the tile is visible or not, and if not set the tile to visible.

Back: Background Tiles
Next: tile_set_alpha

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Fonts

This section deals with the functions available for fonts.

GameMaker: Studio has a number of functions that can be used to get information about the included font assets, as well as a further set of functions that can be used to change, add or remove fonts from your game at run-time. In particular the function font_add() can be used to add non-standard fonts, like Asian glyph fonts, in *.ttf format.

It is worth noting is that if you add a font to your game that doesn't have the glyphs required by the text you wish to write, then the unicode character 9647 (▯) is used to substitute those missing glyphs when rendering it in the draw event. So if your font doesn't have, for example, the ° symbol, then writing 90° will actually produce 90▯.

Font Information

The following functions can be used to get information about font resources:

  1. font_get_name
  2. font_get_fontname
  3. font_get_first
  4. font_get_last
  5. font_get_italic
  6. font_get_bold
  7. font_get_size
  8. font_get_texture
  9. font_get_uvs

Font Manipulation

The following functions can be used to change and manipulate fonts during a game:

  1. font_set_cache_size
  2. font_exists
  3. font_add
  4. font_add_sprite
  5. font_add_sprite_ext
  6. font_replace
  7. font_replace_sprite
  8. font_replace_sprite_ext
  9. font_delete

Back: Game Assets

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_add

Creates a new font resource from a standard Web Font or from a *.ttf included file, and returns its index.

Syntax:

font_add(name, size, bold, italic, first, last);

Argument | Description
name | The name of the font to be added (eg 'Arial'), or the file path if the font is an included *.ttf file.
size | The size of the font - points for Web Fonts, pixels for *.ttf fonts.
bold | Whether the font is bold (true) or not (false).
italics | Whether the font is italic (true) or not (false).
first | The first character to include (if you're unsure, go for 32).
last | The last character to include (if you're unsure, go for 128).

Returns: Real

Description

This function can be used to add a font to your game from those fonts that are installed on the system it is running on. You can define the size of the font (in points), as well as whether the font should be bold or italic, and you can also define the range of characters to include (for a full table of available characters and their UTF8 value see Font tables). The function returns an index value that should be stored in a variable as this will be needed in all further codes that refer to this font.

For the HTML5 target module, this function can only be used to add Web Fonts, but will only work if WebGL is not enabled - if WebGL is enabled then you must use an included font file. The following table shows the fonts that are standard across all browsers and that should be be available for use without problems. Any other font may or may not exist on the computer or device that is running your game, so the use of this function should be limited to these standard fonts:

Windows Font Name | Mac Font Name | Font Family
Arial | Arial / Helvetica | sans-serif
Arial Black | Arial Black / Gadget | sans-serif
Comic Sans MS | Comic Sans MS | cursive
Courier New | Courier New | monospaced
Georgia | Georgia | serif
Impact | Impact / Charcoal | sans-serif
Lucida Console | Monaco | monospaced
Lucida Sans Unicode | Lucida Grande | sans-serif
Palatino Linotype / Book Antiqua | Palatino | serif
Tahoma | Geneva | sans-serif
Times New Roman | Times New Roman / Times | serif
Trebuchet MS | Trebuchet MS | sans-serif
Verdana | Verdana / Geneva | sans-serif
Georgia | Georgia | serif
Symbol | Symbol | N/A
Webdings | Webdings | N/A
Wingdings | Zapf Dingbats | N/A
MS Sans Serif | Geneva | sans-serif
MS Serif | New York | sans-serif

On all other (non JavaScript) targets, you can use this function to add a font from a file. The file must be included in the game bundle using the Included Files functionality of GameMaker: Studio, and must be a *.ttf format font file, useful for adding non-standard fonts like Asian or Arabic.

WARNING!: If you include a font in *.ttf format with a game, it must be licensed for distribution with the game.

When loading a font from a file in this way the size of the font is in pixels and the first and last values are ignored, meaning all glyphs in the font will be added. Fonts added in this way are assigned to their own texture page, so care should be taken when using this function as it will increment the number of texture swaps when drawing. It is also worth noting that fonts may appear slightly larger when drawn, since glyphs may have parts that are drawn outside of the bounding box defined for the font. You should be aware too that there is a limitation of around 200 glyphs that can be rendered in a single frame for a particular font.

NOTE: When you load a font into GameMaker: Studio you must remember to remove it again (with font_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

newfont = font_add( 'Arial', 24, true, true, 32, 128);

This will create a new font that is 24pt in size, uses "Arial" which is bold and italic and the index for this new font is stored in the variable "newfont". The font range includes capital and lower case letters, numbers and all common punctuation.

Back: Fonts
Next: font_add_sprite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_add_sprite

Creates a new font resource based on a sprite, and returns its index.

Syntax:

font_add_sprite(spr, first, prop, sep);

Argument | Description
spr | The sprite to add a font based on.
first | The index of the first available character.
prop | Set as proportional font or not.
sep | The space to leave between each letter.

Returns: Real

Description

With this function you can use a "sprite strip" to create a new font asset, where each sub-image would be an individual symbol or letter. The index is the UTF8 map number for the first character to use and the ranges to use are the same as you would for a normal font, starting with "!" but remember that you should only include what you need and that you should be using the ord function to get the correct UTF8 value for the starting letter. The created sprite font will then have the sub-images set to an individual glyph from the font, where the "first" glyph will have the image_index of 0. You can define "space" as being any character you want, for example a single line the size that you want the space to be, and all spaces in text will be rendered at that width (but the image chosen will never be rendered), or if you don't supply a sprite for space then the width of the widest character in the sprite font will be used instead.

You can also set the spacing for the font to be proportional (true) or not (false), where a proportional font is spaced based on the actual width of the letters (so the letter "i" takes less room than the letter "w", for example) while a non-proportional font will be spaced based on the sub-image width, like a monospaced font. Finally, you can define the space to leave between each letter when writing, and this can be any integer value, with 0 being no space (the letters will "touch" if proportional). The function returns an index value that should be stored in a variable as this will be needed in all further codes that refer to this font.

It is also worth noting that there cannot be any spaces in the character map, so that if you, for example, use '.' and '0' but not '/', you need to either include '/' anyway or leave a blank sub-image between the two used characters.

The sprite itself can be a sprite asset from the resource tree or one loaded from a file using sprite_add first to get the index of the loaded sprite (which is then used in the function). For further details of the character map to use when making sprite fonts, please see the page on Font Tables. It's important to note that for the font alignment functions (like draw_set_halign()) to work as expected when using a sprite font, the sprite should have its origin set to the top left corner. If you use other values then you will need to take the origin offset into consideration when drawing text using the font.

NOTE: When you load a font into GameMaker: Studio you must remember to remove it again (with font_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

global.Font = font_add_sprite(spr_HUD_Font, ord("!"), true, 2);

The above code will create a new font asset from a sprite asset and store the index of the new font in the variable "global.Font" for later use.

Back: Fonts
Next: font_add_sprite_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_add_sprite_ext

Creates a new font resource based on a sprite with the sub-images ordered by a string, and returns its index.

Syntax:

font_add_sprite_ext(spr, string_map, prop, sep);

Argument | Description
spr | The sprite to add a font based on.
string_map | String from which sprite sub-image order is taken.
prop | Set as proportional font or not.
sep | The space to leave between each letter.

Returns: Real

Description

With this function you can use a "sprite strip" (the sprite itself must be a sprite asset from the resource tree, or a sprite you have added to the game resources using sprite_add) to create a new font asset, where each sub-image would be an individual symbol or letter. Unlike the normal font_add_sprite which has a specific order for the sub-images of the sprite, this function will map the sprite sub-images based on the argument "string_map" of the function. This argument is a string that you can use to tell GameMaker: Studio what order the sub-images of the sprite font are and it will map these automatically when writing text. So, for example, if you have a string-map of "AaBbCcDdEeFfGgHh", your sprite font must have the sub-images ordered in this way. You can define "space" as being any character you want, for example a single line the size that you want the space to be, and all spaces in text will be rendered at that width (but the image chosen will never be rendered), or if you don't supply a sprite for space then the width of the widest character in the sprite font will be used instead.

You can also set the spacing for the font to be proportional (true) or not (false), where a proportional font is spaced based on the actual width of the letters (so the letter "i" takes less room than the letter "w", for example) while a non-proportional font will be spaced based on the sub-image width, like a monospaced font. Finally, you can define the space to leave between each letter when writing, and this can be any integer value, with 0 being no space (the letters will "touch" if proportional). The function returns an index value that should be stored in a variable as this will be needed in all further codes that refer to this font.

It is worth noting that for the font alignment functions to work (like draw_set_halign()) then the font sprite should have its origin set to the top left corner. If you use other values then you will need to take the origin offset into consideration when drawing text using the font.

NOTE: When you load a font into GameMaker: Studio you must remember to remove it again (with font_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

global.Font = font_add_sprite_ext(spr_CalcFont, "0123456789+-*/=", true, 2);

The above code will create a new font asset from the sprite indexed in the variable "spr_CalcFont" and store the index of the new font in the variable "global.Font". The sub-images of the sprite font will be mapped to the string specified.

Back: Fonts
Next: font_replace

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_delete

Deletes a font asset.

Syntax:

font_delete(ind);

Argument | Description
ind | The index of the font to delete.

Returns: N/A

Description

With this function you can delete a font asset from the game. This is a permanent removal, and changing rooms, or restarting the game will not bring the removed font back. For that the player would need to exit the game and restart that way, so take care when using this function. In general it is only needed for freeing up memory that has been used by a font added to the game through the functions font_add or font_add_sprite.

Example:

font_delete(global.Font);

The above code will delete the font indexed in the global variable "Font".

Back: Fonts
Next: font_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_exists

Returns whether a given font exists or not.

Syntax:

font_exists(ind);

Argument | Description
ind | Index of the font to check.

Returns: Boolean

Description

This function returns whether a font with the specified index exists or not. Please note, that the value used for checking must have been initialised previously or else you will get an error causing GameMaker: Studio to close.

Example:

if font_exists(fnt_Main)
{
draw_set_font(fnt_Main);
}

This will set the active drawing font to fnt_Main if it exists.

Back: Fonts
Next: font_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_get_bold

Returns whether a given font is bold or not.

Syntax:

font_get_bold(ind);

Argument | Description
ind | Index of the font to check.

Returns: Boolean

Description

With this function you can check any font asset to see if it has the bold flag or not. If it does the function will return true, otherwise it will return false.

Example:

if font_get_bold(fnt_Main)
{
draw_set_font(fnt_Main);
}

This will set the active drawing font to fnt_Main if it is set as bold in its font properties.

Back: Fonts
Next: font_get_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_get_first

Returns the index of the first character in a given font.

Syntax:

font_get_first(ind);

Argument | Description
ind | Index of the font to check.

Returns: Real

Description

When defining a font in GameMaker: Studio, you can define a range of characters to include. This is because the font itself is not actually included with your game (for legal reasons) but an image of the font is included on a texture page and that is what your game will use (just like any other graphics asset). This means that you will want to keep the number of characters that you use to a minimum and specify only the range of characters that your game will need so as to keep texture memory as optimised as possible. This function can be used to find the starting character (as an ASCII value) that was used when your font asset was added to your game.

NOTE: Due to changes in the way fonts are handled, this function will always return 32, as GameMaker: Studio enforces the space character (32) into the font and doesn't allow characters with codes lower than 32 either. New functions to do similar tasks will be added in a future update.

Example:

num = font_get_first(fnt_Main);

The above code will store the ASCII value of the first letter of the font range for the font indexed in "fnt_Main".

Back: Fonts
Next: font_get_last

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_get_fontname

Returns the system name of a given font.

Syntax:

font_get_fontname(ind);

Argument | Description
ind | Index of the font to check.

Returns: String

Description

With this function you can get the actual system name of the selected font asset. This function returns a string and not an index, and the name returned will depend on the font being used. For example, you may have a font asset called "fnt_Main" in the GameMaker: Studio resource tree, and the font itself may be the Windows system font Arial. In this case the function will return "Arial" as that is the system name of the font. Should you need the name as it appears in the resource tree, you should use font_get_name.

Example:

fnt_Name = font_get_fontname(font0);

The above code will get the system name of a font resource and store it as a string in the variable "fnt_Name".

Back: Fonts
Next: font_get_first

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_get_italic

Returns whether a given font is italic or not.

Syntax:

font_get_italic(ind);

Argument | Description
ind | Index of the font to check.

Returns: Boolean

Description

With this function you can check any font asset to see if it has the italic flag or not. If it does the function will return true, otherwise it will return false.

Example:

if font_get_italic(fnt_Main)
{
draw_set_font(fnt_Main);
}

This will set the active drawing font to fnt_Main if it is set as italic in its font properties.

Back: Fonts
Next: font_get_bold

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_get_last

Returns the index of the last character in a given font.

Syntax:

font_get_last(ind);

Argument | Description
ind | Index of the font to check.

Returns: Real

Description

When defining a font in GameMaker: Studio, you can define a range of characters to include. This is because the font itself is not actually included with your game (for legal reasons) but an image of the font is included on a texture page and that is what your game will use (just like any other graphics asset). This means that you will want to keep the number of characters that you use to a minimum and specify only the range of characters that your game will need so as to keep texture memory as optimised as possible. This function can be used to find the last character (as an UTF8 value) that was used when your font asset was added to your game.

Example:

num = font_get_last(fnt_Main);

The above code will store the ASCII value of the last letter of the font range for the font indexed in "fnt_Main".

Back: Fonts
Next: font_get_italic

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_get_name

Returns the resource name of a given font.

Syntax:

font_get_name(ind);

Argument | Description
ind | Index of the font to check.

Returns: String

Description

This function can be used to get the name (as a string) that was given to the font when it was added as an asset to the GameMaker: Studio resource tree. Please note that this is only a string and cannot be used to reference the font directly - for that you would need the font index. You can, however, use this string to get the font index using the returned string along with the function asset_get_index().

Example:

fnt_Name = font_get_name(font0);

The above code will get the name of a font resource as it appears in the resource tree and store it as a string in the variable "fnt_Name".

Back: Fonts
Next: font_get_fontname

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_get_size

Returns the size of a given font.

Syntax:

font_get_size(ind);

Argument | Description
ind | Index of the font to get the size of.

Returns: Real

Description

With this function you can get the size of any font resource, which is the point value shown by the font resource dialogue.

Example:

sz = font_get_size(font0);

This will get the size of the font indexed by the "font0" variable and store it in the variable "sz".

Back: Fonts
Next: font_get_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_get_texture

Returns the texture id for the given font.

Syntax:

font_get_texture(font);

Argument | Description
font | The index of the font to use.

Returns: Pointer

Description

This function returns a special pointer for the font texture page. This value can then be used in other draw functions, particularly in general 3D and some of the 2D primitive functions, as well as the Shader functions. You can get more information about the returned texture page using the different texture_ functions found here.

Example:

tex = font_get_texture(fnt_Main);

The above code will get the texture pointer for the font indexed as "fnt_Main".

Back: Fonts
Next: font_get_uvs

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_get_uvs

Returns the texture coordinates of the font within the texture page as an array.

Syntax:

font_get_uvs(font);

Argument | Description
font | The index of the font to use.

Returns: Array

Description

This function returns an array with the UV coordinates for the font texture on the texture page, filling in the array with the following values: [0] = left, [1] = top, [2] = right and [3] = bottom. This value can then be used in other draw functions, particularly in general 3D and some of the 2D primitive functions, as well as the Shader functions.

Example:

var tex = font_get_uvs(fnt_Main);
tex_left = tex[0];
tex_top = tex[1];
tex_right = tex[2];
tex_left = tex[3];

The above code will store the UV coordinates for the given background in a local array and then assign the values to instance variables.

Back: Fonts
Next: font_set_cache_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_replace

Replaces an indexed font asset with a new one.

Syntax:

font_replace(ind, name, size, bold, italic, first, last);

Argument | Description
ind | The index of the font that shall be replaced (ie all references to this resource past this function will refer to the new font, not the original).
name | The name of the font to be added (eg 'Arial').
size | The size, in points, of the font.
bold | Whether the font is bold (true) or not (false).
italic | Whether the font is italic (true) or not (false).
first | The first character to include (if you're unsure, go for 32)
last | The last character to include (if you're unsure, go for 128).

Returns: N/A

Description

This function can be used to replace an already existing font resource with one of the fonts that are installed on the system the game is running on. You need to supply a valid font index to be replaced (one that has been added previously, not one from the resource tree as you cannot replace built-in assets) and you can define the size of the font (in points), as well as whether the font should be bold or italic, and you can also define the range of characters to include (for a full table of available characters and their UTF8 value see Font tables).

This function is for HTML5 only, with the following table showing the fonts that are standard across these platforms and that can be used without problems. Any other font may or may not exist on the computer that is running your game, so the use of this function should be limited to these standard fonts:

Windows Font Name | Mac Font Name | Font Family
Arial | Arial / Helvetica | sans-serif
Arial Black | Arial Black / Gadget | sans-serif
Comic Sans MS | Comic Sans MS | cursive
Courier New | Courier New | monospaced
Georgia | Georgia | serif
Impact | Impact / Charcoal | sans-serif
Lucida Console | Monaco | monospaced
Lucida Sans Unicode | Lucida Grande | sans-serif
Palatino Linotype / Book Antiqua | Palatino | serif
Tahoma | Geneva | sans-serif
Times New Roman | Times New Roman / Times | serif
Trebuchet MS | Trebuchet MS | sans-serif
Verdana | Verdana / Geneva | sans-serif
Georgia | Georgia | serif
Symbol | Symbol | N/A
Webdings | Webdings | N/A
Wingdings | Zapf Dingbats | N/A
MS Sans Serif | Geneva | sans-serif
MS Serif | New York | sans-serif

Example:

font_replace(fnt_Custom, 'Arial', 24, true, true, 32, 128);

This will replace the font indexed in the variable "fnt_Custom" for a new font that is 24pt in size, uses "Arial" and is bold and italic. The font range includes capital and lower case letters, numbers and all common punctuation.

Back: Fonts
Next: font_replace_sprite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_replace_sprite

Replaces an indexed sprite font asset with a new one.

Syntax:

font_replace_sprite(ind, spr, first, prop, sep);

Argument | Description
ind | The index of the font that shall be replaced (ie all references to this resource past this function will refer to the new font, not the original).
spr | The sprite to add a font based on.
first | The index of the first available character.
prop | Whether white space around each letter should be removed (if false, the created font will be monospaced, otherwise it'll be like most regular fonts).
sep | The space between each letter, 0 meaning the right of one letter just touches the left of the next one.

Returns: N/A

Description

With this function you can use a "sprite strip" to replace a previously created sprite font asset, where each sub-image would be an individual symbol or letter. The index is the UTF8 map number for the first character to use and the ranges to use are the same as you would for a normal font, starting with "!" but remember that you should only include what you need and that you should be using the ord function to get the correct UTF8 value for the starting letter.

You can also set the spacing for the font to be proportional (true) or not (false), where a proportional font is spaced based on the actual width of the letters (so the letter "i" takes less room than the letter "w", for example) while a non-proportional font will be spaced based on the sub-image width, like a monospaced font. Finally, you can define the space to leave between each letter when writing, and this can be any integer value, with 0 being no space (the letters will "touch" if proportional).

It is also worth noting that there cannot be any spaces in the character map, so that if you, for example, use '.' and '0' but not '/', you need to either include '/' anyway or leave a blank sub-image between the two used characters. The image below shows a typical sprite font layout:

For further details of the character map to use when making sprite fonts, please see the page on Font Tables.

Example:

font_replace_sprite(global.Font, working_directory + "\Sprites\spr_Font.png", ord("!"), true, 2);

The above code will replace the font asset indexed in the global variable "Font" with a new font asset from an external image file.

Back: Fonts
Next: font_replace_sprite_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_replace_sprite_ext

Replaces a previously created font asset based on a sprite with the sub-images ordered by a string.

Syntax:

font_replace_sprite_ext(font, spr, string_map, prop, sep);

Argument | Description
font | The font to replace.
spr | The sprite to add a font based on.
string_map | String from which sprite sub-image order is taken.
prop | Set as proportional font or not.
sep | The space to leave between each letter.

Returns: N/A

Description

This function will replace a sprite font that you created previously using the function font_add_sprite_ext. It uses a "sprite strip", where each sub-image is be an individual symbol or letter, and the images are mapped to letters based on the argument "string_map" of the function. This argument is a string that you can use to tell GameMaker: Studio what order the sub-images of the sprite font are and it will map these automatically when writing text. So, for example, if you have a string-map of "AaBbCcDdEeFfGgHh", your sprite font must have the sub-images ordered in this way.

You can also set the spacing for the font to be proportional (true) or not (false), where a proportional font is spaced based on the actual width of the letters (so the letter "i" takes less room than the letter "w", for example) while a non-proportional font will be spaced based on the sub-image width, like a monospaced font. Finally, you can define the space to leave between each letter when writing, and this can be any integer value, with 0 being no space (the letters will "touch" if proportional). The function returns an index value that should be stored in a variable as this will be needed in all further codes that refer to this font.

NOTE: This function requires you to have previously added a sprite font using font_add_sprite(), as it will replace that and cannot be used on fonts that are included as part of the game resources.

Example:

font_replace_sprite_ext(global.Font, spr_CalcFont, "0123456789+-*/=", true, 2);

The above code will replace a sprite font asset that is indexed in the variable "global.Font" with sprite images indexed in the variable "spr_CalcFont".

Back: Fonts
Next: font_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


font_set_cache_size

Sets the size of the cache for a given font.

Syntax:

font_set_cache_size(ind, max);

Argument | Description
ind | The index of the font to change the cache size of.
max | The maximum number of cached copies of the font that can be stored.

Returns: N/A

Description

When performing image blending and colouring, HTML5 cannot do it dynamically in the same way an executable could be performed. Therefore GameMaker: Studio has to temporarily save a blended copy of the images and load them in when needed. This function sets how many blended copies of the given font can be cached before old ones are overwritten. The default value is 4.

NOTE: for sprite fonts you should be using the equivalent function for sprites, sprite_set_cache_size.

Example:

font_set_cache_size(fnt_MainMenu, 2);

This will set the font cache of the font indexed in the variable "fnt_MainMenu" to 2 copies.

Back: Fonts
Next: font_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Font Tables

This section contains the different font tables

ASCII

UTF-8

Unicode code point | character | UTF-8 (hex.) | name
U+0000 |  | 00 | <control>
U+0001 |  | 01 | <control>
U+0002 |  | 02 | <control>
U+0003 |  | 03 | <control>
U+0004 |  | 04 | <control>
U+0005 |  | 05 | <control>
U+0006 |  | 06 | <control>
U+0007 |  | 07 | <control>
U+0008 |  | 08 | <control>
U+0009 |  | 09 | <control>
U+000A |  | 0a | <control>
U+000B |  | 0b | <control>
U+000C |  | 0c | <control>
U+000D |  | 0d | <control>
U+000E |  | 0e | <control>
U+000F |  | 0f | <control>
U+0010 |  | 10 | <control>
U+0011 |  | 11 | <control>
U+0012 |  | 12 | <control>
U+0013 |  | 13 | <control>
U+0014 |  | 14 | <control>
U+0015 |  | 15 | <control>
U+0016 |  | 16 | <control>
U+0017 |  | 17 | <control>
U+0018 |  | 18 | <control>
U+0019 |  | 19 | <control>
U+001A |  | 1a | <control>
U+001B |  | 1b | <control>
U+001C |  | 1c | <control>
U+001D |  | 1d | <control>
U+001E |  | 1e | <control>
U+001F |  | 1f | <control>
U+0020 |  | 20 | SPACE
U+0021 | ! | 21 | EXCLAMATION MARK
U+0022 | " | 22 | QUOTATION MARK
U+0023 | # | 23 | NUMBER SIGN
U+0024 | $ | 24 | DOLLAR SIGN
U+0025 | % | 25 | PERCENT SIGN
U+0026 | & | 26 | AMPERSAND
U+0027 | ' | 27 | APOSTROPHE
U+0028 | ( | 28 | LEFT PARENTHESIS
U+0029 | ) | 29 | RIGHT PARENTHESIS
U+002A | * | 2a | ASTERISK
U+002B | + | 2b | PLUS SIGN
U+002C | , | 2c | COMMA
U+002D | - | 2d | HYPHEN-MINUS
U+002E | . | 2e | FULL STOP
U+002F | / | f | SOLIDUS
U+0030 | 0 | 30 | DIGIT ZERO
U+0031 | 1 | 31 | DIGIT ONE
U+0032 | 2 | 32 | DIGIT TWO
U+0033 | 3 | 33 | DIGIT THREE
U+0034 | 4 | 34 | DIGIT FOUR
U+0035 | 5 | 35 | DIGIT FIVE
U+0036 | 6 | 36 | DIGIT SIX
U+0037 | 7 | 37 | DIGIT SEVEN
U+0038 | 8 | 38 | DIGIT EIGHT
U+0039 | 9 | 39 | DIGIT NINE
U+003A | : | 3a | COLON
U+003B | ; | 3b | SEMICOLON
U+003C | < | 3c | LESS-THAN SIGN
U+003D | = | 3d | EQUALS SIGN
U+003E | > | 3e | GREATER-THAN SIGN
U+003F | ? | 3f | QUESTION MARK
U+0040 | @ | 40 | COMMERCIAL AT
U+0041 | A | 41 | LATIN CAPITAL LETTER A
U+0042 | B | 42 | LATIN CAPITAL LETTER B
U+0043 | C | 43 | LATIN CAPITAL LETTER C
U+0044 | D | 44 | LATIN CAPITAL LETTER D
U+0045 | E | 45 | LATIN CAPITAL LETTER E
U+0046 | F | 46 | LATIN CAPITAL LETTER F
U+0047 | G | 47 | LATIN CAPITAL LETTER G
U+0048 | H | 48 | LATIN CAPITAL LETTER H
U+0049 | I | 49 | LATIN CAPITAL LETTER I
U+004A | J | 4a | LATIN CAPITAL LETTER J
U+004B | K | 4b | LATIN CAPITAL LETTER K
U+004C | L | 4c | LATIN CAPITAL LETTER L
U+004D | M | 4d | LATIN CAPITAL LETTER M
U+004E | N | 4e | LATIN CAPITAL LETTER N
U+004F | O | 4f | LATIN CAPITAL LETTER O
U+0050 | P | 50 | LATIN CAPITAL LETTER P
U+0051 | Q | 51 | LATIN CAPITAL LETTER Q
U+0052 | R | 52 | LATIN CAPITAL LETTER R
U+0053 | S | 53 | LATIN CAPITAL LETTER S
U+0054 | T | 54 | LATIN CAPITAL LETTER T
U+0055 | U | 55 | LATIN CAPITAL LETTER U
U+0056 | V | 56 | LATIN CAPITAL LETTER V
U+0057 | W | 57 | LATIN CAPITAL LETTER W
U+0058 | X | 58 | LATIN CAPITAL LETTER X
U+0059 | Y | 59 | LATIN CAPITAL LETTER Y
U+005A | Z | 5a | LATIN CAPITAL LETTER Z
U+005B | [ | 5b | LEFT SQUARE BRACKET
U+005C | \ | 5c | REVERSE SOLIDUS
U+005D | ] | 5d | RIGHT SQUARE BRACKET
U+005E | ^ | 5e | CIRCUMFLEX ACCENT
U+005F | _ | 5f | LOW LINE
U+0060 | ` | 60 | GRAVE ACCENT
U+0061 | a | 61 | LATIN SMALL LETTER A
U+0062 | b | 62 | LATIN SMALL LETTER B
U+0063 | c | 63 | LATIN SMALL LETTER C
U+0064 | d | 64 | LATIN SMALL LETTER D
U+0065 | e | 65 | LATIN SMALL LETTER E
U+0066 | f | 66 | LATIN SMALL LETTER F
U+0067 | g | 67 | LATIN SMALL LETTER G
U+0068 | h | 68 | LATIN SMALL LETTER H
U+0069 | i | 69 | LATIN SMALL LETTER I
U+006A | j | 6a | LATIN SMALL LETTER J
U+006B | k | 6b | LATIN SMALL LETTER K
U+006C | l | 6c | LATIN SMALL LETTER L
U+006D | m | 6d | LATIN SMALL LETTER M
U+006E | n | 6e | LATIN SMALL LETTER N
U+006F | o | 6f | LATIN SMALL LETTER O
U+0070 | p | 70 | LATIN SMALL LETTER P
U+0071 | q | 71 | LATIN SMALL LETTER Q
U+0072 | r | 72 | LATIN SMALL LETTER R
U+0073 | s | 73 | LATIN SMALL LETTER S
U+0074 | t | 74 | LATIN SMALL LETTER T
U+0075 | u | 75 | LATIN SMALL LETTER U
U+0076 | v | 76 | LATIN SMALL LETTER V
U+0077 | w | 77 | LATIN SMALL LETTER W
U+0078 | x | 78 | LATIN SMALL LETTER X
U+0079 | y | 79 | LATIN SMALL LETTER Y
U+007A | z | 7a | LATIN SMALL LETTER Z
U+007B | { | 7b | LEFT CURLY BRACKET
U+007C | | | 7c | VERTICAL LINE
U+007D | } | 7d | RIGHT CURLY BRACKET
U+007E | ~ | 7e | TILDE
U+007F |  | 7f | <control>
U+0080 |  | c2 80 | <control>
U+0081 |  | c2 81 | <control>
U+0082 |  | c2 82 | <control>
U+0083 |  | c2 83 | <control>
U+0084 |  | c2 84 | <control>
U+0085 |  | c2 85 | <control>
U+0086 |  | c2 86 | <control>
U+0087 |  | c2 87 | <control>
U+0088 |  | c2 88 | <control>
U+0089 |  | c2 89 | <control>
U+008A |  | c2 8a | <control>
U+008B |  | c2 8b | <control>
U+008C |  | c2 8c | <control>
U+008D |  | c2 8d | <control>
U+008E |  | c2 8e | <control>
U+008F |  | c2 8f | <control>
U+0090 |  | c2 90 | <control>
U+0091 |  | c2 91 | <control>
U+0092 |  | c2 92 | <control>
U+0093 |  | c2 93 | <control>
U+0094 |  | c2 94 | <control>
U+0095 |  | c2 95 | <control>
U+0096 |  | c2 96 | <control>
U+0097 |  | c2 97 | <control>
U+0098 |  | c2 98 | <control>
U+0099 |  | c2 99 | <control>
U+009A |  | c2 9a | <control>
U+009B |  | c2 9b | <control>
U+009C |  | c2 9c | <control>
U+009D |  | c2 9d | <control>
U+009E |  | c2 9e | <control>
U+009F |  | c2 9f | <control>
U+00A0 |  | c2 a0 | NO-BREAK SPACE
U+00A1 | ¡ | c2 a1 | INVERTED EXCLAMATION MARK
U+00A2 | ¢ | c2 a2 | CENT SIGN
U+00A3 | £ | c2 a3 | POUND SIGN
U+00A4 | ¤ | c2 a4 | CURRENCY SIGN
U+00A5 | ¥ | c2 a5 | YEN SIGN
U+00A6 | ¦ | c2 a6 | BROKEN BAR
U+00A7 | § | c2 a7 | SECTION SIGN
U+00A8 | ¨ | c2 a8 | DIAERESIS
U+00A9 | © | c2 a9 | COPYRIGHT SIGN
U+00AA | ª | c2 aa | FEMININE ORDINAL INDICATOR
U+00AB | « | c2 ab | LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
U+00AC | ¬ | c2 ac | NOT SIGN
U+00AD |  | c2 ad | SOFT HYPHEN
U+00AE | ® | c2 ae | REGISTERED SIGN
U+00AF | ¯ | c2 af | MACRON
U+00B0 | ° | c2 b0 | DEGREE SIGN
U+00B1 | ± | c2 b1 | PLUS-MINUS SIGN
U+00B2 | ² | c2 b2 | SUPERSCRIPT TWO
U+00B3 | ³ | c2 b3 | SUPERSCRIPT THREE
U+00B4 | ´ | c2 b4 | ACUTE ACCENT
U+00B5 | µ | c2 b5 | MICRO SIGN
U+00B6 | ¶ | c2 b6 | PILCROW SIGN
U+00B7 | · | c2 b7 | MIDDLE DOT
U+00B8 | ¸ | c2 b8 | CEDILLA
U+00B9 | ¹ | c2 b9 | SUPERSCRIPT ONE
U+00BA | º | c2 ba | MASCULINE ORDINAL INDICATOR
U+00BB | » | c2 bb | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
U+00BC | ¼ | c2 bc | VULGAR FRACTION ONE QUARTER
U+00BD | ½ | c2 bd | VULGAR FRACTION ONE HALF
U+00BE | ¾ | c2 be | VULGAR FRACTION THREE QUARTERS
U+00BF | ¿ | c2 bf | INVERTED QUESTION MARK
U+00C0 | À | c3 80 | LATIN CAPITAL LETTER A WITH GRAVE
U+00C1 | Á | c3 81 | LATIN CAPITAL LETTER A WITH ACUTE
U+00C2 | Â | c3 82 | LATIN CAPITAL LETTER A WITH CIRCUMFLEX
U+00C3 | Ã | c3 83 | LATIN CAPITAL LETTER A WITH TILDE
U+00C4 | Ä | c3 84 | LATIN CAPITAL LETTER A WITH DIAERESIS
U+00C5 | Å | c3 85 | LATIN CAPITAL LETTER A WITH RING ABOVE
U+00C6 | Æ | c3 86 | LATIN CAPITAL LETTER AE
U+00C7 | Ç | c3 87 | LATIN CAPITAL LETTER C WITH CEDILLA
U+00C8 | È | c3 88 | LATIN CAPITAL LETTER E WITH GRAVE
U+00C9 | É | c3 89 | LATIN CAPITAL LETTER E WITH ACUTE
U+00CA | Ê | c3 8a | LATIN CAPITAL LETTER E WITH CIRCUMFLEX
U+00CB | Ë | c3 8b | LATIN CAPITAL LETTER E WITH DIAERESIS
U+00CC | Ì | c3 8c | LATIN CAPITAL LETTER I WITH GRAVE
U+00CD | Í | c3 8d | LATIN CAPITAL LETTER I WITH ACUTE
U+00CE | Î | c3 8e | LATIN CAPITAL LETTER I WITH CIRCUMFLEX
U+00CF | Ï | c3 8f | LATIN CAPITAL LETTER I WITH DIAERESIS
U+00D0 | Ð | c3 90 | LATIN CAPITAL LETTER ETH
U+00D1 | Ñ | c3 91 | LATIN CAPITAL LETTER N WITH TILDE
U+00D2 | Ò | c3 92 | LATIN CAPITAL LETTER O WITH GRAVE
U+00D3 | Ó | c3 93 | LATIN CAPITAL LETTER O WITH ACUTE
U+00D4 | Ô | c3 94 | LATIN CAPITAL LETTER O WITH CIRCUMFLEX
U+00D5 | Õ | c3 95 | LATIN CAPITAL LETTER O WITH TILDE
U+00D6 | Ö | c3 96 | LATIN CAPITAL LETTER O WITH DIAERESIS
U+00D7 | × | c3 97 | MULTIPLICATION SIGN
U+00D8 | Ø | c3 98 | LATIN CAPITAL LETTER O WITH STROKE
U+00D9 | Ù | c3 99 | LATIN CAPITAL LETTER U WITH GRAVE
U+00DA | Ú | c3 9a | LATIN CAPITAL LETTER U WITH ACUTE
U+00DB | Û | c3 9b | LATIN CAPITAL LETTER U WITH CIRCUMFLEX
U+00DC | Ü | c3 9c | LATIN CAPITAL LETTER U WITH DIAERESIS
U+00DD | Ý | c3 9d | LATIN CAPITAL LETTER Y WITH ACUTE
U+00DE | Þ | c3 9e | LATIN CAPITAL LETTER THORN
U+00DF | ß | c3 9f | LATIN SMALL LETTER SHARP S
U+00E0 | à | c3 a0 | LATIN SMALL LETTER A WITH GRAVE
U+00E1 | á | c3 a1 | LATIN SMALL LETTER A WITH ACUTE
U+00E2 | â | c3 a2 | LATIN SMALL LETTER A WITH CIRCUMFLEX
U+00E3 | ã | c3 a3 | LATIN SMALL LETTER A WITH TILDE
U+00E4 | ä | c3 a4 | LATIN SMALL LETTER A WITH DIAERESIS
U+00E5 | å | c3 a5 | LATIN SMALL LETTER A WITH RING ABOVE
U+00E6 | æ | c3 a6 | LATIN SMALL LETTER AE
U+00E7 | ç | c3 a7 | LATIN SMALL LETTER C WITH CEDILLA
U+00E8 | è | c3 a8 | LATIN SMALL LETTER E WITH GRAVE
U+00E9 | é | c3 a9 | LATIN SMALL LETTER E WITH ACUTE
U+00EA | ê | c3 aa | LATIN SMALL LETTER E WITH CIRCUMFLEX
U+00EB | ë | c3 ab | LATIN SMALL LETTER E WITH DIAERESIS
U+00EC | ì | c3 ac | LATIN SMALL LETTER I WITH GRAVE
U+00ED | í | c3 ad | LATIN SMALL LETTER I WITH ACUTE
U+00EE | î | c3 ae | LATIN SMALL LETTER I WITH CIRCUMFLEX
U+00EF | ï | c3 af | LATIN SMALL LETTER I WITH DIAERESIS
U+00F0 | ð | c3 b0 | LATIN SMALL LETTER ETH
U+00F1 | ñ | c3 b1 | LATIN SMALL LETTER N WITH TILDE
U+00F2 | ò | c3 b2 | LATIN SMALL LETTER O WITH GRAVE
U+00F3 | ó | c3 b3 | LATIN SMALL LETTER O WITH ACUTE
U+00F4 | ô | c3 b4 | LATIN SMALL LETTER O WITH CIRCUMFLEX
U+00F5 | õ | c3 b5 | LATIN SMALL LETTER O WITH TILDE
U+00F6 | ö | c3 b6 | LATIN SMALL LETTER O WITH DIAERESIS
U+00F7 | ÷ | c3 b7 | DIVISION SIGN
U+00F8 | ø | c3 b8 | LATIN SMALL LETTER O WITH STROKE
U+00F9 | ù | c3 b9 | LATIN SMALL LETTER U WITH GRAVE
U+00FA | ú | c3 ba | LATIN SMALL LETTER U WITH ACUTE
U+00FB | û | c3 bb | LATIN SMALL LETTER U WITH CIRCUMFLEX
U+00FC | ü | c3 bc | LATIN SMALL LETTER U WITH DIAERESIS
U+00FD | ý | c3 bd | LATIN SMALL LETTER Y WITH ACUTE
U+00FE | þ | c3 be | LATIN SMALL LETTER THORN
U+00FF | ÿ | c3 bf | LATIN SMALL LETTER Y WITH DIAERESIS

Back: Fonts

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


UTF-8

This section shows all the standard UTF 8 characters.

Unicode code point | character | UTF-8 (hex.) | name
U+0000 |  | 00 | <control>
U+0001 |  | 01 | <control>
U+0002 |  | 02 | <control>
U+0003 |  | 03 | <control>
U+0004 |  | 04 | <control>
U+0005 |  | 05 | <control>
U+0006 |  | 06 | <control>
U+0007 |  | 07 | <control>
U+0008 |  | 08 | <control>
U+0009 |  | 09 | <control>
U+000A |  | 0a | <control>
U+000B |  | 0b | <control>
U+000C |  | 0c | <control>
U+000D |  | 0d | <control>
U+000E |  | 0e | <control>
U+000F |  | 0f | <control>
U+0010 |  | 10 | <control>
U+0011 |  | 11 | <control>
U+0012 |  | 12 | <control>
U+0013 |  | 13 | <control>
U+0014 |  | 14 | <control>
U+0015 |  | 15 | <control>
U+0016 |  | 16 | <control>
U+0017 |  | 17 | <control>
U+0018 |  | 18 | <control>
U+0019 |  | 19 | <control>
U+001A |  | 1a | <control>
U+001B |  | 1b | <control>
U+001C |  | 1c | <control>
U+001D |  | 1d | <control>
U+001E |  | 1e | <control>
U+001F |  | 1f | <control>
U+0020 |  | 20 | SPACE
U+0021 | ! | 21 | EXCLAMATION MARK
U+0022 | " | 22 | QUOTATION MARK
U+0023 | # | 23 | NUMBER SIGN
U+0024 | $ | 24 | DOLLAR SIGN
U+0025 | % | 25 | PERCENT SIGN
U+0026 | & | 26 | AMPERSAND
U+0027 | ' | 27 | APOSTROPHE
U+0028 | ( | 28 | LEFT PARENTHESIS
U+0029 | ) | 29 | RIGHT PARENTHESIS
U+002A | * | 2a | ASTERISK
U+002B | + | 2b | PLUS SIGN
U+002C | , | 2c | COMMA
U+002D | - | 2d | HYPHEN-MINUS
U+002E | . | 2e | FULL STOP
U+002F | / | f | SOLIDUS
U+0030 | 0 | 30 | DIGIT ZERO
U+0031 | 1 | 31 | DIGIT ONE
U+0032 | 2 | 32 | DIGIT TWO
U+0033 | 3 | 33 | DIGIT THREE
U+0034 | 4 | 34 | DIGIT FOUR
U+0035 | 5 | 35 | DIGIT FIVE
U+0036 | 6 | 36 | DIGIT SIX
U+0037 | 7 | 37 | DIGIT SEVEN
U+0038 | 8 | 38 | DIGIT EIGHT
U+0039 | 9 | 39 | DIGIT NINE
U+003A | : | 3a | COLON
U+003B | ; | 3b | SEMICOLON
U+003C | < | 3c | LESS-THAN SIGN
U+003D | = | 3d | EQUALS SIGN
U+003E | > | 3e | GREATER-THAN SIGN
U+003F | ? | 3f | QUESTION MARK
U+0040 | @ | 40 | COMMERCIAL AT
U+0041 | A | 41 | LATIN CAPITAL LETTER A
U+0042 | B | 42 | LATIN CAPITAL LETTER B
U+0043 | C | 43 | LATIN CAPITAL LETTER C
U+0044 | D | 44 | LATIN CAPITAL LETTER D
U+0045 | E | 45 | LATIN CAPITAL LETTER E
U+0046 | F | 46 | LATIN CAPITAL LETTER F
U+0047 | G | 47 | LATIN CAPITAL LETTER G
U+0048 | H | 48 | LATIN CAPITAL LETTER H
U+0049 | I | 49 | LATIN CAPITAL LETTER I
U+004A | J | 4a | LATIN CAPITAL LETTER J
U+004B | K | 4b | LATIN CAPITAL LETTER K
U+004C | L | 4c | LATIN CAPITAL LETTER L
U+004D | M | 4d | LATIN CAPITAL LETTER M
U+004E | N | 4e | LATIN CAPITAL LETTER N
U+004F | O | 4f | LATIN CAPITAL LETTER O
U+0050 | P | 50 | LATIN CAPITAL LETTER P
U+0051 | Q | 51 | LATIN CAPITAL LETTER Q
U+0052 | R | 52 | LATIN CAPITAL LETTER R
U+0053 | S | 53 | LATIN CAPITAL LETTER S
U+0054 | T | 54 | LATIN CAPITAL LETTER T
U+0055 | U | 55 | LATIN CAPITAL LETTER U
U+0056 | V | 56 | LATIN CAPITAL LETTER V
U+0057 | W | 57 | LATIN CAPITAL LETTER W
U+0058 | X | 58 | LATIN CAPITAL LETTER X
U+0059 | Y | 59 | LATIN CAPITAL LETTER Y
U+005A | Z | 5a | LATIN CAPITAL LETTER Z
U+005B | [ | 5b | LEFT SQUARE BRACKET
U+005C | \ | 5c | REVERSE SOLIDUS
U+005D | ] | 5d | RIGHT SQUARE BRACKET
U+005E | ^ | 5e | CIRCUMFLEX ACCENT
U+005F | _ | 5f | LOW LINE
U+0060 | ` | 60 | GRAVE ACCENT
U+0061 | a | 61 | LATIN SMALL LETTER A
U+0062 | b | 62 | LATIN SMALL LETTER B
U+0063 | c | 63 | LATIN SMALL LETTER C
U+0064 | d | 64 | LATIN SMALL LETTER D
U+0065 | e | 65 | LATIN SMALL LETTER E
U+0066 | f | 66 | LATIN SMALL LETTER F
U+0067 | g | 67 | LATIN SMALL LETTER G
U+0068 | h | 68 | LATIN SMALL LETTER H
U+0069 | i | 69 | LATIN SMALL LETTER I
U+006A | j | 6a | LATIN SMALL LETTER J
U+006B | k | 6b | LATIN SMALL LETTER K
U+006C | l | 6c | LATIN SMALL LETTER L
U+006D | m | 6d | LATIN SMALL LETTER M
U+006E | n | 6e | LATIN SMALL LETTER N
U+006F | o | 6f | LATIN SMALL LETTER O
U+0070 | p | 70 | LATIN SMALL LETTER P
U+0071 | q | 71 | LATIN SMALL LETTER Q
U+0072 | r | 72 | LATIN SMALL LETTER R
U+0073 | s | 73 | LATIN SMALL LETTER S
U+0074 | t | 74 | LATIN SMALL LETTER T
U+0075 | u | 75 | LATIN SMALL LETTER U
U+0076 | v | 76 | LATIN SMALL LETTER V
U+0077 | w | 77 | LATIN SMALL LETTER W
U+0078 | x | 78 | LATIN SMALL LETTER X
U+0079 | y | 79 | LATIN SMALL LETTER Y
U+007A | z | 7a | LATIN SMALL LETTER Z
U+007B | { | 7b | LEFT CURLY BRACKET
U+007C | | | 7c | VERTICAL LINE
U+007D | } | 7d | RIGHT CURLY BRACKET
U+007E | ~ | 7e | TILDE
U+007F |  | 7f | <control>
U+0080 |  | c2 80 | <control>
U+0081 |  | c2 81 | <control>
U+0082 |  | c2 82 | <control>
U+0083 |  | c2 83 | <control>
U+0084 |  | c2 84 | <control>
U+0085 |  | c2 85 | <control>
U+0086 |  | c2 86 | <control>
U+0087 |  | c2 87 | <control>
U+0088 |  | c2 88 | <control>
U+0089 |  | c2 89 | <control>
U+008A |  | c2 8a | <control>
U+008B |  | c2 8b | <control>
U+008C |  | c2 8c | <control>
U+008D |  | c2 8d | <control>
U+008E |  | c2 8e | <control>
U+008F |  | c2 8f | <control>
U+0090 |  | c2 90 | <control>
U+0091 |  | c2 91 | <control>
U+0092 |  | c2 92 | <control>
U+0093 |  | c2 93 | <control>
U+0094 |  | c2 94 | <control>
U+0095 |  | c2 95 | <control>
U+0096 |  | c2 96 | <control>
U+0097 |  | c2 97 | <control>
U+0098 |  | c2 98 | <control>
U+0099 |  | c2 99 | <control>
U+009A |  | c2 9a | <control>
U+009B |  | c2 9b | <control>
U+009C |  | c2 9c | <control>
U+009D |  | c2 9d | <control>
U+009E |  | c2 9e | <control>
U+009F |  | c2 9f | <control>
U+00A0 |  | c2 a0 | NO-BREAK SPACE
U+00A1 | ¡ | c2 a1 | INVERTED EXCLAMATION MARK
U+00A2 | ¢ | c2 a2 | CENT SIGN
U+00A3 | £ | c2 a3 | POUND SIGN
U+00A4 | ¤ | c2 a4 | CURRENCY SIGN
U+00A5 | ¥ | c2 a5 | YEN SIGN
U+00A6 | ¦ | c2 a6 | BROKEN BAR
U+00A7 | § | c2 a7 | SECTION SIGN
U+00A8 | ¨ | c2 a8 | DIAERESIS
U+00A9 | © | c2 a9 | COPYRIGHT SIGN
U+00AA | ª | c2 aa | FEMININE ORDINAL INDICATOR
U+00AB | « | c2 ab | LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
U+00AC | ¬ | c2 ac | NOT SIGN
U+00AD |  | c2 ad | SOFT HYPHEN
U+00AE | ® | c2 ae | REGISTERED SIGN
U+00AF | ¯ | c2 af | MACRON
U+00B0 | ° | c2 b0 | DEGREE SIGN
U+00B1 | ± | c2 b1 | PLUS-MINUS SIGN
U+00B2 | ² | c2 b2 | SUPERSCRIPT TWO
U+00B3 | ³ | c2 b3 | SUPERSCRIPT THREE
U+00B4 | ´ | c2 b4 | ACUTE ACCENT
U+00B5 | µ | c2 b5 | MICRO SIGN
U+00B6 | ¶ | c2 b6 | PILCROW SIGN
U+00B7 | · | c2 b7 | MIDDLE DOT
U+00B8 | ¸ | c2 b8 | CEDILLA
U+00B9 | ¹ | c2 b9 | SUPERSCRIPT ONE
U+00BA | º | c2 ba | MASCULINE ORDINAL INDICATOR
U+00BB | » | c2 bb | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
U+00BC | ¼ | c2 bc | VULGAR FRACTION ONE QUARTER
U+00BD | ½ | c2 bd | VULGAR FRACTION ONE HALF
U+00BE | ¾ | c2 be | VULGAR FRACTION THREE QUARTERS
U+00BF | ¿ | c2 bf | INVERTED QUESTION MARK
U+00C0 | À | c3 80 | LATIN CAPITAL LETTER A WITH GRAVE
U+00C1 | Á | c3 81 | LATIN CAPITAL LETTER A WITH ACUTE
U+00C2 | Â | c3 82 | LATIN CAPITAL LETTER A WITH CIRCUMFLEX
U+00C3 | Ã | c3 83 | LATIN CAPITAL LETTER A WITH TILDE
U+00C4 | Ä | c3 84 | LATIN CAPITAL LETTER A WITH DIAERESIS
U+00C5 | Å | c3 85 | LATIN CAPITAL LETTER A WITH RING ABOVE
U+00C6 | Æ | c3 86 | LATIN CAPITAL LETTER AE
U+00C7 | Ç | c3 87 | LATIN CAPITAL LETTER C WITH CEDILLA
U+00C8 | È | c3 88 | LATIN CAPITAL LETTER E WITH GRAVE
U+00C9 | É | c3 89 | LATIN CAPITAL LETTER E WITH ACUTE
U+00CA | Ê | c3 8a | LATIN CAPITAL LETTER E WITH CIRCUMFLEX
U+00CB | Ë | c3 8b | LATIN CAPITAL LETTER E WITH DIAERESIS
U+00CC | Ì | c3 8c | LATIN CAPITAL LETTER I WITH GRAVE
U+00CD | Í | c3 8d | LATIN CAPITAL LETTER I WITH ACUTE
U+00CE | Î | c3 8e | LATIN CAPITAL LETTER I WITH CIRCUMFLEX
U+00CF | Ï | c3 8f | LATIN CAPITAL LETTER I WITH DIAERESIS
U+00D0 | Ð | c3 90 | LATIN CAPITAL LETTER ETH
U+00D1 | Ñ | c3 91 | LATIN CAPITAL LETTER N WITH TILDE
U+00D2 | Ò | c3 92 | LATIN CAPITAL LETTER O WITH GRAVE
U+00D3 | Ó | c3 93 | LATIN CAPITAL LETTER O WITH ACUTE
U+00D4 | Ô | c3 94 | LATIN CAPITAL LETTER O WITH CIRCUMFLEX
U+00D5 | Õ | c3 95 | LATIN CAPITAL LETTER O WITH TILDE
U+00D6 | Ö | c3 96 | LATIN CAPITAL LETTER O WITH DIAERESIS
U+00D7 | × | c3 97 | MULTIPLICATION SIGN
U+00D8 | Ø | c3 98 | LATIN CAPITAL LETTER O WITH STROKE
U+00D9 | Ù | c3 99 | LATIN CAPITAL LETTER U WITH GRAVE
U+00DA | Ú | c3 9a | LATIN CAPITAL LETTER U WITH ACUTE
U+00DB | Û | c3 9b | LATIN CAPITAL LETTER U WITH CIRCUMFLEX
U+00DC | Ü | c3 9c | LATIN CAPITAL LETTER U WITH DIAERESIS
U+00DD | Ý | c3 9d | LATIN CAPITAL LETTER Y WITH ACUTE
U+00DE | Þ | c3 9e | LATIN CAPITAL LETTER THORN
U+00DF | ß | c3 9f | LATIN SMALL LETTER SHARP S
U+00E0 | à | c3 a0 | LATIN SMALL LETTER A WITH GRAVE
U+00E1 | á | c3 a1 | LATIN SMALL LETTER A WITH ACUTE
U+00E2 | â | c3 a2 | LATIN SMALL LETTER A WITH CIRCUMFLEX
U+00E3 | ã | c3 a3 | LATIN SMALL LETTER A WITH TILDE
U+00E4 | ä | c3 a4 | LATIN SMALL LETTER A WITH DIAERESIS
U+00E5 | å | c3 a5 | LATIN SMALL LETTER A WITH RING ABOVE
U+00E6 | æ | c3 a6 | LATIN SMALL LETTER AE
U+00E7 | ç | c3 a7 | LATIN SMALL LETTER C WITH CEDILLA
U+00E8 | è | c3 a8 | LATIN SMALL LETTER E WITH GRAVE
U+00E9 | é | c3 a9 | LATIN SMALL LETTER E WITH ACUTE
U+00EA | ê | c3 aa | LATIN SMALL LETTER E WITH CIRCUMFLEX
U+00EB | ë | c3 ab | LATIN SMALL LETTER E WITH DIAERESIS
U+00EC | ì | c3 ac | LATIN SMALL LETTER I WITH GRAVE
U+00ED | í | c3 ad | LATIN SMALL LETTER I WITH ACUTE
U+00EE | î | c3 ae | LATIN SMALL LETTER I WITH CIRCUMFLEX
U+00EF | ï | c3 af | LATIN SMALL LETTER I WITH DIAERESIS
U+00F0 | ð | c3 b0 | LATIN SMALL LETTER ETH
U+00F1 | ñ | c3 b1 | LATIN SMALL LETTER N WITH TILDE
U+00F2 | ò | c3 b2 | LATIN SMALL LETTER O WITH GRAVE
U+00F3 | ó | c3 b3 | LATIN SMALL LETTER O WITH ACUTE
U+00F4 | ô | c3 b4 | LATIN SMALL LETTER O WITH CIRCUMFLEX
U+00F5 | õ | c3 b5 | LATIN SMALL LETTER O WITH TILDE
U+00F6 | ö | c3 b6 | LATIN SMALL LETTER O WITH DIAERESIS
U+00F7 | ÷ | c3 b7 | DIVISION SIGN
U+00F8 | ø | c3 b8 | LATIN SMALL LETTER O WITH STROKE
U+00F9 | ù | c3 b9 | LATIN SMALL LETTER U WITH GRAVE
U+00FA | ú | c3 ba | LATIN SMALL LETTER U WITH ACUTE
U+00FB | û | c3 bb | LATIN SMALL LETTER U WITH CIRCUMFLEX
U+00FC | ü | c3 bc | LATIN SMALL LETTER U WITH DIAERESIS
U+00FD | ý | c3 bd | LATIN SMALL LETTER Y WITH ACUTE
U+00FE | þ | c3 be | LATIN SMALL LETTER THORN
U+00FF | ÿ | c3 bf | LATIN SMALL LETTER Y WITH DIAERESIS

Back: Fonts
Next: font_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Audio

This section contains the functions necessary to use the GameMaker: Studio audio API

GameMaker: Studio has a re-vamped audio engine that is based on the *.ogg sound format. You must still load your sounds into the IDE as either *.wav or *.mp3 but you can select compressed audio from the Audio Editor and GameMaker: Studio will convert the sounds to *.ogg (Ogg Vorbis) format when your finished game is compiled. In this way you can keep the final file size of your game to a minimum while ensuring maximum quality. The added benefit of the new GM:S Audio engine is that you now have access to full audio streaming as well as 3D sound with the ability to place a "listener" for all sounds as well as different sound "emitters" to create some stunning special audio effects!

Please note that for compatibility with older projects, GameMaker: Studio still has some legacy audio functionality. However, you cannot have both the new audio engine and the legacy engine active at the same time. For old games created with other versions of GameMaker or for those games started before the new audio engine was added, the Legacy Audio will be used as default, while for all new games GameMaker: Studio will default to the new audio engine. This behaviour can be changed from the Global Game Settings - General Tab.

Basic Audio Functions

The following functions are for dealing with audio in the most straightforward and simple way possible, avoiding the use of emitters and permitting the user to generate sounds and play music easily as these sounds are always generated at the listener position (see below for more details on the listener) and so are generally not affected by any changes to the listener:

  1. audio_exists
  2. audio_get_name
  3. audio_get_type
  4. audio_play_sound
  5. audio_play_sound_at
  6. audio_pause_sound
  7. audio_pause_all
  8. audio_resume_sound
  9. audio_resume_all
  10. audio_stop_sound
  11. audio_stop_all
  12. audio_is_playing
  13. audio_is_paused
  14. audio_create_stream
  15. audio_destroy_stream

Advanced Audio Functions

The following functions are designed to give more control over how the audio engine works, and how the sounds played through it will be "heard" by the listener. As such it is recommended that you have a good working knowledge of how the rest of the GameMaker: Studio audio engine works before using any of the following functions:

  1. audio_sound_set_track_position
  2. audio_sound_get_track_position
  3. audio_sound_length
  4. audio_sound_pitch
  5. audio_sound_get_pitch
  6. audio_falloff_set_model
  7. audio_sound_gain
  8. audio_sound_get_gain
  9. audio_master_gain
  10. audio_set_master_gain
  11. audio_get_master_gain
  12. audio_channel_num
  13. audio_debug

Further advanced functionality, like setting listeners, recording audio, or synchronising multiple audio tracks over time can all be found from the sub-sections listed below:

  1. Audio Emitters
  2. Audio Listeners
  3. Audio Groups
  4. Audio Buffers
  5. Audio Synchronisation

Legacy Sound

The following section also contains information on the Legacy Sound System, provided for compatibility with previous versions of GameMaker and also still of use when dealing with HTML5 and JS games:

  1. Legacy Sound

The legacy functions are still valid and available due to the fact that certain browsers for HTML5 games do not support the newer sound system. This means that you may wish to check in-game which sound system is actually being used and change the functions being used as appropriate. To that end there is a special function available:

  1. audio_system

Obsolete Functions

There are also some obsolete audio functions which were designed specifically for music. These functions no longer work and will give an unknown function or script error when they have been used, and you should update any legacy projects that use these functions to use the standard audio_*() functions instead:

  1. audio_play_music
  2. audio_pause_music
  3. audio_resume_music
  4. audio_stop_music
  5. audio_music_is_playing
  6. audio_music_gain
  7. audio_get_type

Back: Game Assets
Next: Fonts

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Audio Buffers

This section covers the functions necessary to use audio buffers for recording, streaming and queueing your audio files.

You can use audio buffers to load, save and manipulate audio files within your games. These buffers are created beforehand using the appropriate buffer functions and then you can use the following functions to create a sound to use in your project:

  1. audio_create_buffer_sound
  2. audio_free_buffer_sound

Note that once you have created a sound from an audio buffer, you are not creating a new sound in memory, but rather pointing to the position within the buffer where the sound is stored. You should not change this buffer after a sound has been associated with it otherwise you will get unexpected results, and you cannot delete the buffer while a sound is associated with it. Instead, free the sound (or sounds) first then delete the buffer. Once you have created your new audio resource from a buffer, you can use it's index value in any of the regular audio functions to play it, change it's gain or pitch, pause it, etc... Note that the buffer used to load the audio can only support PCM sounds, so formats like OGG will not be supported.

Another feature of buffered audio is that you can use a buffer to create a queue of audio which can then be streamed to the device running your project. An audio queue takes a regular buffer which you have previously filled with audio data, and enables you to "point" to parts of it and tell GameMaker: Studio to stream the audio in a given order from that buffer. The available functions for audio queues are:

  1. audio_create_play_queue
  2. audio_free_play_queue
  3. audio_queue_sound

Once a queue has been created, you can then use the returned queue index just as you would the sound index for any normal sound to play it, pause it, restart it, or change it's gain and pitch. The only thing you cannot do is get the track length or set the track position, but other than that, an audio queue can be used just like any other sound. You should also note that some of the audio queue functions will also trigger an Audio Playback Asynchronous Event.

Audio buffers will also permit you to record sound from any of the available sources (like microphones or the OS), which can then be queued and streamed using the above functions (for example). Recording audio will trigger an Audio Recording Asynchronous Event which will contain specific information about what is being recorded.

For recording audio, the following functions are available:

  1. audio_start_recording
  2. audio_stop_recording
  3. audio_get_recorder_count
  4. audio_get_recorder_info

NOTE: Most platforms support recording audio in some form, but that does not mean that all devices will permit it, even if the platform does, so you should always check that the audio_get_recorder_count() function returns a value greater than 0 to verify that recording devices are available before using the rest of the recording functions.

Back: Audio
Next: Audio Synchronisation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Audio Emitters

This section explains the functions required to use audio emitters in GameMaker: Studio.

Audio emitters are provided to increase the flexibility of the GameMaker: Studio audio engine, and they permit you to add real time effects to your audio assets, like pitch and Doppler variations, as well as the ability to position your sounds within the 3D audio space and give them realistic motion effects. All these functions are affected by the position of the listener within the audio environment and so will require that you use the provided functions for changing the listener position, velocity and orientation too (see - Audio Listeners).

The following functions exist to deal with audio emitters:

  1. audio_emitter_create
  2. audio_emitter_exists
  3. audio_emitter_position
  4. audio_emitter_velocity
  5. audio_emitter_falloff
  6. audio_emitter_gain
  7. audio_emitter_pitch
  8. audio_emitter_free
  9. audio_play_sound_on
  10. audio_emitter_get_gain
  11. audio_emitter_get_pitch
  12. audio_emitter_get_x
  13. audio_emitter_get_y
  14. audio_emitter_get_z
  15. audio_emitter_get_vx
  16. audio_emitter_get_vy
  17. audio_emitter_get_vz

Back: Audio
Next: Audio Listeners

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Audio Groups

This section explains how to set-up and use audio groups to better control your audio output.

Your audio files can be grouped together from the IDE - you can create audio groups from the Audio Groups Tab in the Global Game Settings, and assign your files to a specific group from the Sound Properties Window. These groups can then be loaded or unloaded from memory as well as have certain properties set for them using the following functions:

NOTE: Audio groups can only be used when working with the normal audio system, but will not work with legacy audio.
  1. audio_group_load
  2. audio_group_unload
  3. audio_group_is_loaded
  4. audio_group_load_progress
  5. audio_group_name
  6. audio_group_stop
  7. audio_group_set_gain

Back: Audio
Next: Audio Buffers

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Audio Listeners

This section explains the set-up and use of different listeners for audio.

When dealing with complex audio situations it can be useful to define where in the audio environment the listener should be situated. When working with the simple audio functions, it is not normally necessary for the listener to be changed in any way, however when using emitters to generate realistic audio within the 3D audio space, it is important that the listener be changed and moved correctly, or else the sound will be in the wrong position for the person playing your game.

GameMaker: Studio provides the following listener functions:

  1. audio_listener_position
  2. audio_listener_velocity
  3. audio_listener_orientation
  4. audio_listener_get_data
  5. audio_listener_set_position
  6. audio_listener_set_velocity
  7. audio_listener_set_orientation

Certain target platforms can permit more than one listener, with each one corresponding to a different output device, ie: your target platform could permit two listeners, one for the headphones and one for the monitor. Therefore GameMaker: Studio provides you with a number of extra functions with which you can find the available listeners as well as set them for sounds being played:

  1. audio_get_listener_count
  2. audio_get_listener_info
  3. audio_set_listener_mask
  4. audio_sound_set_listener_mask
  5. audio_emitter_set_listener_mask
  6. audio_get_listener_mask
  7. audio_sound_get_listener_mask
  8. audio_emitter_get_listener_mask

Back: Audio
Next: Audio Groups

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Audio Synchronisation

This section contains the functions necessary to synchronise the playback of various audio tracks over time.

The audio sync group functions let you play multiple sounds that start at exactly the same time and stay in sync (on a per sample level). This enables you to (for example) add various tracks for a single song and then fade in and out sections without having to worry about whether there will be any delay between them. Note that these functions currently only work with compressed audio, ie. *.ogg and *.mp3 format files.

NOTE: Audio sync group functionality is not available for the HTML5 target platform. You will see a console message that the function call is not supported.

The following functions exist to deal with synchronising audio tracks:

  1. audio_create_sync_group
  2. audio_play_in_sync_group
  3. audio_start_sync_group
  4. audio_stop_sync_group
  5. audio_pause_sync_group
  6. audio_resume_sync_group
  7. audio_sync_group_get_track_pos
  8. audio_destroy_sync_group
  9. audio_sync_group_debug
  10. audio_sync_group_is_playing

Back: Audio
Next: Audio Emitters

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_channel_num

Set the number of available audio channels.

Syntax:

audio_channel_num(num);

Argument | Description
num | Number of available audio channels (default is 128).

Returns: N/A

Description

With this function you can set how many audio channels are available for playing audio in GameMaker: Studio. What this basically means is that you give the number of simultaneous sounds that can be played at any one time, and if the number exceeds the amount, those sounds with a lower priority are stopped to free up a channel for the sounds with a higher priority. You can use this function to optimise your game for devices as the lower the number of channels for audio the better the performance, but bear in mind that this may also cause noticeable cut off of certain sounds if many are played at once.

Example:

switch (os_browser)
{
case browser_not_a_browser:
switch (os_type)
{
case os_windows:
case os_macos:
audio_channel_num(200);
break;
default:
audio_channel_num(64);
break;
}
break;
default:
audio_channel_num(16);
break;
}

The above code checks the platform that the game is running on and changes the number of available sound channels to increase performance.

Back: Sound
Next: audio_debug

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_create_buffer_sound

Create a new sound from the contents of a buffer.

Syntax:

audio_create_buffer_sound(bufferId, bufferFormat, bufferRate, bufferOffset, bufferLength, bufferChannels);

Argument | Description
bufferId | The ID of the buffer to use.
bufferFormat | The format of the data in the buffer (buffer_u8 or buffer_s16).
bufferRate | The sample rate of the data in the buffer.
bufferOffset | The offset into the buffer to read the sample data from (in bytes).
bufferLength | The length of the buffer (the number of the samples in the buffer).
bufferChannels | The channels to use from one of the constants listed below.

Returns: Index

Description

With this function you can create a new sound from the contents of a buffer. The buffer will have been created previously (see the buffer functions for details on how to do this), and have had data added or loaded into it. You then pass it to this function with the data format (only buffer_u8 or buffer_s16 are currently supported), the sample rate (which can be between 1000hz and 48000hz), and an offset into the buffer to get the data from. You also need to supply the number of samples in the buffer and the channels that the sound requires. These channels are defined by one of the following constants:

Constant | Description
audio_mono | Mono (single channel) audio.
audio_stereo | Stereo (dual channel) audio.
audio_3D | 3D (5.1) audio.

Note that after you have created a sound, you should free the pointer index associated with it when it is no longer required using the function audio_free_buffer_sound(). If you fail to do this and then re-assign the variable or change rooms etc... the sound ID will be lost and you will have a memory leak. Also note that you cannot delete the buffer if any sound has been created from it and the sound has not been freed up first. So you would free the sound (or sounds) first, then delete the buffer. It is also worth noting that adding anything to the buffer, or changing the buffer size, after it has had a sound created from it will give unexpected results and it is not recommended - once you have started creating sounds from any buffer you should not manipulate it in any other way afterwards.

Example:

rate = 44100;
hertz = irandom_range(220, 880);
samples = 44100;
bufferId = buffer_create(rate, buffer_fast, 1);
buffer_seek(bufferId, buffer_seek_start, 0);
num_to_write = rate / hertz;
val_to_write = 1;
for (var i = 0; i < (samples / num_to_write) + 1; i++;)
{
for (var j = 0; j < num_to_write; j++;)
{
buffer_write(bufferId, buffer_u8, val_to_write * 255);
}
val_to_write = (1 - val_to_write);
}
soundId = audio_create_buffer_sound(bufferId, buffer_u8, rate, 0, 44100, audio_mono);

The above creates a buffer and then procedurally fills it with data. This data is then used to create a new sound, which is stored in the variable "soundID".

Back: Audio Buffers
Next: audio_free_buffer_sound

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_create_play_queue

Create a queue of audio from a buffer for streaming.

Syntax:

audio_create_play_queue(queueFormat, queueRate, queueChannels);

Argument | Description
queueFormat | The format of the buffer data to use (buffer_u8 or buffer_s16).
queueRate | The sample rate of the data in the buffer queue.
queueChannels | The channels to use from one of the constants listed below.

Returns: Index

Description

This function prepares a buffer queue for audio. You pass data format (only buffer_u8 or buffer_s16 are currently supported), the sample rate (which can be between 1000hz and 48000hz), and the channels that the audio requires from one of the constants listed below:

Constant | Description
audio_mono | Mono (single channel) audio.
audio_stereo | Stereo (dual channel) audio.
audio_3D | 3D (5.1) audio.

Note that you should free up any audio queues created with this function when no longer required to prevent memory leaks using the function audio_free_play_queue().

This function will trigger an Audio Playback Asynchronous Event when the queue has reached the end, and in this event a special ds_map will be created in the variable async_load with the following key/value pairs:

  • "queue_id" - the queue that has finished playing data
  • "buffer_id" - the buffer that is no longer being played from
  • "queue_shutdown" - this is set to 0 during normal playback and 1 when the event is received because audio_free_play_queue has been called. When this is set to 1, you don't want to queue up any further data.

Example:

audio_queue = audio_create_play_queue(buffer_s16, 11052, audio_mono);

The above code creates a new audio queue and assigns its index to a variable for future reference.

Back: Audio Buffers
Next: audio_free_play_queue

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_create_stream

Create a new sound index from an external audio source for streaming.

Syntax:

audio_create_stream(filename);

Argument | Description
filename | The file (OGG only) to stream the audio from.

Returns: Sound Index

Description

With this function you can create a new sound index which can then be used in the regular audio functions to stream audio directly from an external OGG file source. The function requires the filename (which can be an included file, for example) and will return the new sound index for use. Note that after you no longer need the sound you should call the function audio_destroy_stream() with the sound index to remove it from memory otherwise you may get a memory leak which will slow down and eventually crash your game.

Example:

snd = audio_create_stream("Music/Track1.ogg");
audio_play_sound(snd, 0, true);

The above code creates a new sound index in the variable "snd" from the given file, then plays this sound.

Back: Audio
Next: audio_destroy_stream

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_create_sync_group

Create a new synchronisation group for audio.

Syntax:

audio_create_sync_group(loop);

Argument | Description
loop | Whether the tracks in the group should loop (true) or not (false).

Returns: index

Description

Creates a sync group and returns a unique ID value for it which should then be used in all further audio function calls for this group. If you want the group to loop then pass in true, otherwise pass in false, but note that if you want them to loop, all the tracks added later need to be the same length. Note that when you create a sync group, you will need to free the memory and sounds associated with it when not in use using the audio_destroy_sync_group() function - for example, in the Room End or Destroy events.

Example:

sg = audio_create_sync_group(true);
audio_play_in_sync_group(sg, sound1);
audio_play_in_sync_group(sg, sound2);
audio_set_gain(sound2, 0, 0);
audio_play_in_sync_group(sg, sound3);
audio_set_gain(sound3, 0, 0);
audio_play_in_sync_group(sg, sound4);
audio_set_gain(sound4, 0, 0);
audio_start_sync_group(sg);

The above creates a new sync group and assigns the index of the group to the variable "sg". Four sounds are then added to the group, with the gain for three of them set to 0. Finally the sync group is played.

Back: Audio Synchronisation
Next: audio_play_in_sync_group

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_debug

Enable or disable the audio debug overlay.

Syntax:

audio_debug(enable);

Argument | Description
enable | Enable (set to true) or disable (false) audio debugging.

Returns: N/A

Description

This function can be used to display debug information about the audio system, with true switching it on and false to switch it off. When you are debugging audio in this way, the overlay will show the following information:

  1. Handle - The OpenAL source handle (unique for every sound played)
  2. Data Handle - The OpenAL buffer handle (shows the same value for multiple sounds with the same source handle)
  3. Processed Buffers - how many buffers have been played
  4. Queued Buffers - how many buffers have been queued (and are still waiting to play)
  5. Gain - The gain value for the audio (0 - 65536)
  6. Play Offset - the sample position (current play position) into the current buffer
  7. Queued Buffers Bars - a small box diagram of the processed/queued buffers with the play offset (current position) drawn as a blue line

For synchronised groups of audio, you also have the function audio_sync_group_debug().

NOTE: This function does not work on the HTML5 target platform.

Example:

if (debug_mode)
{
audio_debug(true);
}
else
{
audio_debug(false);
}

The above code will switch on or off the audio debug overlay depending on whether the game is running in debug mode or not.

Back: Sound
Next: audio_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_destroy_stream

Remove the given audio stream from memory.

Syntax:

audio_destroy_stream(filename);

Argument | Description
filename | The file to stream the audio from.

Returns: NA

Description

If you have previously created an audio stream from a file using the function audio_create_stream() and no longer need that sound, you can call this function to delete it from memory. Any further calls to the sound index after it has been destroyed will give an error.

Example:

audio_destroy_stream(snd);

The above code removes the sound indexed in the variable "snd" from memory.

Back: Audio
Next: audio_sound_set_track_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_destroy_sync_group

Get the current play position for the given sync group.

Syntax:

audio_destroy_sync_group(group_index);

Argument | Description
group_index | The group index to be destroyed.

Returns: N/A

Description

Audio sync groups need to be destroyed when not in use to free up the memory and sound resources associated with them using this function. It takes the group index as returned when the group was created using the function audio_create_sync_group(), and frees all resources used by the group.

Example:

audio_destroy_sync_group(sg);

The above code destroys the sync group indexed in the variable "sg", and would probably be used in the destroy or Room End events.

Back: Audio Synchronisation
Next: audio_sync_group_debug

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_create

Create a new audio emitter.

Syntax:

audio_emitter_create();

Returns: Real

Description

This function creates a new audio emitter and returns the index for it. This index should be stored in a variable for all further functions that relate to this emitter, and then when it is no longer needed it should be removed from memory using the function audio_emitter_free to prevent memory leaks which may eventually crash your game.

Example:

s_emit = audio_emitter_create();

The above code creates a new audio emitter and assigns its index to the variable "s_emit".

Back: Audio Emitters
Next: audio_emitter_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_exists

Checks whether the given emitter exists.

Syntax:

audio_emitter_exists(index);

Argument | Description
index | The index of the emitter to check the existence of.

Returns: Boolean

Description

This function returns whether an audio emitter exists (true) or not (false). Note that if the index you search for has not been initialised previously, this function will cause an error as it is searching for non-existent indices.

Example:

if audio_emitter_exists(s_emit)
{
audio_play_sound_on(s_emit, snd_Explode, false, 1);
}
else
{
s_emit = audio_emitter_create();
audio_play_sound_on(s_emit, snd_Explode, false, 1);
}

The above code checks to see if an emitter exists, indexed in the (previously initialised) variable "s_emit". If it does then a sound is played through it, but if it does not, it is created and then the sound is played.

Back: Audio Emitters
Next: audio_emitter_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_falloff

Changes the audio fall-off distance for an emitter.

Syntax:

audio_emitter_falloff(emitter, falloff_ref, falloff_max, falloff_factor);

Argument | Description
emitter | The index of the emitter to change.
falloff_ref | The falloff reference relative to the listener (clamp).
falloff_max | The maximum falloff distance relative to the listener.
falloff_factor | The falloff factor (default 1).

Returns: N/A

Description

With this function you can set the fall-off distance for an emitter. This is the distance from the listener the emitter has to be before the sound will have "fallen off" to a volume of 0. The default value for this is 100, but beware of setting this to any value lower than 1 as that will make any sound played through this emitter inaudible to the listener, however any other value will cause the sound to fade away the further that the emitter is from the listener.

How the sound itself is heard will depend on the falloff reference (which is the distance under which the volume for the source would normally drop by half) and the roll off factor (which affects the sound past the falloff reference distance only). The default factor is normally 1, and the effect of the different falloff values will depend on the model chosen.

For a complete guide to the different falloff models and how these values are used, please see the function audio_falloff_set_model

Example:

s_emit = audio_emitter_create();
audio_emitter_position(s_emit, x, y, 0);
audio_emitter_falloff(s_emit, 100, 300, 1);

The above code creates an audio emitter and assigns its index to the variable "s_emit". This emitter is then placed at the position of the instance creating it and is given a fall-off distance of 300, meaning that when the emitter is further than 300 pixels from the listener position it will be silent. Its falloff factor is the default 1 and the falloff reference is 100, so at 100 pixels from the listener the falloff will start.

Back: Audio Emitters
Next: audio_emitter_gain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_free

Removes the given emitter from memory.

Syntax:

audio_emitter_free(emitter);

Argument | Description
emitter | The index of the emitter to free.

Returns: N/A

Description

With this function you can remove the given emitter from memory. This should always be done whenever the emitter is not going to be used further in the room or the game, ie: in the Destroy Event of the instance or in the Room End Event, otherwise you may end up with a memory leak that will slow down and eventually crash your game.

Example:

if lives = 0
{
audio_emitter_free(s_emit);
room_goto(rm_Menu);
}

The above code checks the value of the global variable "lives" and if it returns 0, it will destroy the emitter indexed in the variable "s_emit" and then go to the room indexed in the variable "rm_Menu".

Back: Audio Emitters
Next: audio_play_sound_on

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_gain

Changes the maximum gain (volume) for an emitter.

Syntax:

audio_emitter_gain(emitter, gain);

Argument | Description
emitter | The index of the emitter to change.
gain | The maximum gain (default 1).

Returns: N/A

Description

This function sets the maximum gain (volume) for the sound. The perceived volume for a sound can change depending on the fall-off value and the position it has relative to the listener, but by setting the gain with this function, the full volume will never exceed the specified gain value. The image below illustrates how gain affects the volume of the emitter when fall-off is greater than 0:

This function will change the volume of the sound while it is being played as well all subsequent sounds played through the given emitter.

NOTE: the final volume will also be influenced by the global audio gain that has been set by the function audio_master_gain.

Example:

if up
{
gain += 0.05;
if gain >= 1 up = false;
}
else
{
gain += 0.05;
if gain <= 0 up = true;
}
audio_emitter_gain(s_emit, gain);

The above code sets the variable "gain" to different values and then uses that same variable to set the gain of the emitter indexed in the variable "s_emit".

Back: Audio Emitters
Next: audio_emitter_pitch

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_get_gain

Returns the current gain of a given emitter.

Syntax:

audio_emitter_get_gain(emitter);

Argument | Description
emitter | The index of the emitter to use.

Returns: Real

Description

This function returns the current gain (volume) set for the given audio emitter, a value between 0 and 1.

Example:

if audio_emitter_get_gain(emitter_player) < 1
{
audio_emitter_gain(emitter_player, 1);
}

The above code checks the current gain of a given emitter and if it is less than 1 it is set to 1.

Back: Audio Emitters
Next: audio_emitter_get_pitch

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_get_listener_mask

Gets the listener bit-mask data for an emitter.

Syntax:

audio_emitter_get_listener_mask(emitterID);

Argument | Description
emitterID | The unique ID of the emitter to get the mask of

Returns: Real

Description

This function will return the bit-mask data that defines which audio listeners an emitter should play sounds from.

Example:

s_emit = audio_emitter_create();
if audio_emitter_get_listener_mask(s_emit) != global.PlayerMask
{
audio_emitter_set_listener_mask(snd, global.PlayerMask);
}

The above code creates an emitter then checks the listener mask data for it, and if it's not the same as that which is stored in a global variable, it sets the listener(s) to play from using the mask data stored in the global variable.

Back: Audio Listeners
Next: audio_create_buffer_sound

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_get_pitch

Returns the current pitch of a given emitter.

Syntax:

audio_emitter_get_pitch(emitter);

Argument | Description
emitter | The index of the emitter to use.

Returns: Real

Description

This function returns the current pitch value set for the given audio emitter.

Example:

if audio_emitter_get_pitch(emitter_player) != 1
{
audio_emitter_pitch(emitter_player, 1);
}

The above code checks the current pitch of a given emitter and if it is not equal to 1 it is set to 1.

Back: Audio Emitters
Next: audio_emitter_get_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_get_vx

Returns the current velocity along the x axis for a given emitter.

Syntax:

audio_emitter_get_vx(emitter);

Argument | Description
emitter | The index of the emitter to use.

Returns: Real

Description

This function returns the current velocity along the x axis for the given audio emitter.

Example:

if audio_emitter_get_vx(emitter_player) != 0
{
audio_emitter_velocity(emitter_player, 0, 0, 0);
}

The above code checks the current x velocity of a given emitter and if it is not equal to 0, it is set to 0.

Back: Audio Emitters
Next: audio_emitter_get_vy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_get_vy

Returns the current velocity along the y axis for a given emitter.

Syntax:

audio_emitter_get_vy(emitter);

Argument | Description
emitter | The index of the emitter to use.

Returns: Real

Description

This function returns the current velocity along the y axis for the given audio emitter.

Example:

if audio_emitter_get_vy(emitter_player) != 0
{
audio_emitter_velocity(emitter_player, 0, 0, 0);
}

The above code checks the current y velocity of a given emitter and if it is not equal to 0, it is set to 0.

Back: Audio Emitters
Next: audio_emitter_get_vz

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_get_vz

Returns the current velocity along the z axis for a given emitter.

Syntax:

audio_emitter_get_vz(emitter);

Argument | Description
emitter | The index of the emitter to use.

Returns: Real

Description

This function returns the current velocity along the z axis for the given audio emitter.

Example:

if audio_emitter_get_vz(emitter_player) != 0
{
audio_emitter_velocity(emitter_player, 0, 0, 0);
}

The above code checks the current z velocity of a given emitter and if it is not equal to 0, it is set to 0.

Back: Audio Emitters
Next: audio_listener_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_get_x

Returns the current x position of a given emitter.

Syntax:

audio_emitter_get_x(emitter);

Argument | Description
emitter | The index of the emitter to use.

Returns: Real

Description

This function returns the current x position of the given audio emitter.

Example:

if audio_emitter_get_x(emitter_player) != x
{
audio_emitter_position(emitter_player, x, y, 0);
}

The above code checks the current x position of a given emitter and if it is not equal to the instance x position, it is set to the instance position.

Back: Audio Emitters
Next: audio_emitter_get_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_get_y

Returns the current y position of a given emitter.

Syntax:

audio_emitter_get_y(emitter);

Argument | Description
emitter | The index of the emitter to use.

Returns: Real

Description

This function returns the current y position of the given audio emitter.

Example:

if audio_emitter_get_y(emitter_player) != x
{
audio_emitter_position(emitter_player, x, y, 0);
}

The above code checks the current y position of a given emitter and if it is not equal to the instance y position, it is set to the instance position.

Back: Audio Emitters
Next: audio_emitter_get_z

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_get_z

Returns the current z position of a given emitter.

Syntax:

audio_emitter_get_z(emitter);

Argument | Description
emitter | The index of the emitter to use.

Returns: Real

Description

This function returns the current z position of the given audio emitter.

Example:

if audio_emitter_get_z(emitter_player) != 0
{
var ex = audio_emitter_get_x(emitter_player);
var ey = audio_emitter_get_y(emitter_player);
audio_emitter_position(emitter_player, ex, ey, 0);
}

The above code checks the current z position of a given emitter and if it is not equal to 0, it is set to 0.

Back: Audio Emitters
Next: audio_emitter_get_vx

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_pitch

Changes the output pitch for sounds played by the emitter.

Syntax:

audio_emitter_pitch(emitter, pitch);

Argument | Description
emitter | The index of the emitter to change.
pitch | The pitch multiplier (default 1).

Returns: N/A

Description

This function can be used to change the pitch of all sounds emitted from the given emitter. It is a pitch multiplier, in that the input value multiplies the current pitch by that amount, so the default value of 1 is no pitch change, while a value of less than 1 will lower the pitch and greater than 1 will raise the pitch. It is best to use small increments for this function as any value under 0 or over 5 may not be audible anyway.

NOTE: If a sound is being looped through the emitter, the change in pitch will not be detected unless the sound is stopped and looped again!

Example:

switch (gear)
{
case 1: audio_emitter_pitch(s_emit, 0.8); break;
case 2: audio_emitter_pitch(s_emit, 0.9); break;
case 3: audio_emitter_pitch(s_emit, 0.95); break;
case 4: audio_emitter_pitch(s_emit, 1); break;
case 5: audio_emitter_pitch(s_emit, 1.2); break;
}

The above code will change the pitch of the audio played from the emitter indexed in the variable "s_emit" based on the value of the variable "gear".

Back: Audio Emitters
Next: audio_emitter_free

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_position

Changes the position of the given emitter within the audio space.

Syntax:

audio_emitter_position(emitter, x, y, z);

Argument | Description
emitter | The index of the emitter to change.
x | The x position.
y | The y position.
z | The z position.

Returns: N/A

Description

With this function you can change the position of an audio emitter within the 3D audio space. The position will affect the sound in different ways depending on where the listener is positioned within the audio space too (default position is (0, 0, 0). See audio_listener_position for more information), so for example if the emitter position is set to (100, 0, 0) and the current listener is at (200, 0, 0) the audio streamed from the emitter will appear to be on the left of the audio field. The image below shows a visual representation of emitters and their relative positions to the listener:

Example:

if speed > 0
{
audio_emitter_position(s_emit, x, y, 0);
}

The above code checks to see if the instance speed is over 0 and if it is it updates the audio emitter indexed in the variable "s_emit" to the current x/y position.

Back: Audio Emitters
Next: audio_emitter_velocity

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_set_listener_mask

Sets the bit mask for a given emitter, defining the listeners to play it to.

Syntax:

audio_emitter_set_listener_mask(emitterID, mask);

Argument | Description
emitterID | The unique ID of the emitter to set the mask of
mask | The bitmask data to set for the sound

Returns: N/A

Description

This function can be used to set the the bit-mask for an emitter so that all sounds played through the emitter will play only from those listeners specified. You can create a bit-mask by using the audio_get_listener_info() and then using the bitwise or ("|") to create a custom mask with those listeners that you require the sound to play from, and then apply this custom mask to the emitter. This mask will over-ride the default mask or that which you may have set using the function audio_set_listener_mask().

Example:

s_emit = audio_emitter_create();
audio_emitter_set_listener_mask(snd, global.PlayerMask);

The above code creates an audio emitter and then sets the listener(s) to play from using the mask data stored in a global variable.

Back: Audio Listeners
Next: audio_get_listener_mask

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_emitter_velocity

Changes the doppler calculations of the emitter within the audio space.

Syntax:

audio_emitter_velocity(emitter, vx, vy, vz);

Argument | Description
emitter | The index of the emitter to change.
vx | The x vector value (default 0).
vy | The y vector value (default 0).
vz | The z vector value (default 0).

Returns: N/A

Description

This function can be used to give an emitter doppler effects and simulate audio motion based on the vector that is resolved from the given relative x, y and z positions (for more information on vectors, please see Maths - Vectors). If the emitter itself is not ever going to move you would normally not need to set these values, but, for example, if you are making a scrolling shooter game where the enemies come from the right and scroll to the left, you would set this to have a velocity of (hspeed, 0, 0) in the create event of the enemies (and update the emitter of each instance in the step event using audio_emitter_position) to give any sounds emitted by the enemy instances the correct doppler as they pass the player instance (which in turn would be using the function audio_listener_position to set the listener to the correct position).

Example:

s_emit = audio_emitter_create();
audio_emitter_position(s_emit, room_width, 0, 0);
audio_emitter_velocity(s_emit, -5, 0, 0);

The above code creates an audio emitter and assigns its index to the variable "s_emit". This emitter is then placed at a position within the room and given a velocity of 5 pixels per step along the x axis (it will doppler correctly in relation to the listener as if it had a horizontal speed of 5 pixels per step).

Back: Audio Emitters
Next: audio_emitter_falloff

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_exists

Checks whether the given sound exists.

Syntax:

audio_exists(index);

Argument | Description
index | The index of the sound to check the existence of.

Returns: Boolean

Description

This function returns whether a sound exists (true) or not (false). Note that if the index you search for has not been initialised previously, this function will cause an error as it is searching for non-existent asset indices. The sound to check can either be a single instance of a sound (the index for individual sounds being played can be stored in a variable when using the audio_play_sound or audio_play_sound_at functions) or a sound asset.

Example:

if audio_exists(global.Music)
{
audio_play_sound(global.Music, 0, true);
}

The above code checks to see if a sound exists. If it does it is set to play in a loop.

Back: Audio
Next: audio_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_falloff_set_model

Sets the model on which all falloff values will be calculated.

Syntax:

audio_falloff_set_model(model);

Argument | Description
model | The constant used to set the falloff model.

Returns: N/A

Description

To add more versatility to the audio engine, GameMaker: Studio permits you to select the falloff model that suits your game. This model will be used for all the audio functions in the game or app, and so you should make sure that the model you choose is the correct one, as each one will affect how the listener perceives the sounds you play through emitters or with the function audio_play_sound_at.

When setting falloff in your game with the appropriate functions there are three arguments that you will need to set, and each one is appropriate to a specific, model and will affect the way the final sound is "heard" by the player depending on the distance that the listener is from the source. The three arguments are:

  • reference distance - this is the distance from the listener the distance under which the volume for the sound playing would normally drop by half before being influenced by rolloff factor or the specified maximum distance.

  • maximum distance - this sets the distance where there will no longer be any attenuation of the source sound. This can be the point at which the sound is no longer heard or the point at which the sound volume no longer decreases below the minimum threshold defined by the model chosen.

  • falloff factor - The falloff factor is used in distance attenuation based on the inverse distance model and sets the final minimum threshold for a sound with falloff.

The falloff models that are affected by these arguments are represented in GameMaker: Studio by the following constants (the table shows the exact calculations used too):

Constant Function
audio_falloff_exponent_distance
gain = (listener_distance / reference_distance) ^ (-falloff_factor)

audio_falloff_exponent_distance_clamped
distance = clamp(listener_distance, reference_distance, maximum_distance)
gain = (distance / reference_distance) ^ (-falloff_factor)

audio_falloff_inverse_distance
gain = reference_distance / (reference_distance + falloff_factor * (listener_distance – reference_distance))

audio_falloff_inverse_distance_clamped
distance = clamp(listener_distance, reference_distance, maximum_distance)
gain = reference_distance / (reference_distance + falloff_factor * (distance – reference_distance))

audio_falloff_linear_distance
distance = min(distance, maximum_distance)
gain = (1 – falloff_factor * (distance – reference_distance) / (maximum_distance – reference_distance))

audio_falloff_linear_distance_clamped
distance = clamp(listener_distance, reference_distance, maximum_distance)
gain = (1 – falloff_factor * (distance – reference_distance) / (maximum_distance – reference_distance))

audio_falloff_none
gain = 1

The following graphs are visual representations of how the above constants work and affect the sound being played:

Example:

audio_falloff_set_model(audio_falloff_exponent_distance_clamped);
audio_play_sound_at(snd_Waterfall, x, y, 0, 100, 300, 1, true, 1);

The above code sets the falloff model and then plays the sound indexed in the variable "snd_Waterfall", which will be looped at its room position, with a fall-off reference of 100, a falloff distance of 300, a falloff factor of 1 and a low priority.

Back: Audio
Next: audio_sound_gain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_free_buffer_sound

Frees the buffered sound.

Syntax:

audio_free_buffer_sound(index);

Argument | Description
index | The index of the buffered sound to free.

Returns: N/A

Description

With this function you can free up the pointer index value associated with the sound ID. Freed sounds will not be available for playing, and if multiple instances of the sound are being played they will all be stopped. Note that before you can delete the buffer itself, you must first free all sound ID's associated with it.

Example:

audio_free_buffer_sound(soundID);

The above code frees the buffered sound indexed in the variable "soundID".

Back: Audio Buffers
Next: audio_create_play_queue

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_free_play_queue

Free the memory associated with an audio queue.

Syntax:

audio_free_play_queue(queueIndex);

Argument | Description
queueIndex | The index of the queue to free.

Returns: N/A

Description

This function is used to free up the memory associated with the given audio queue. The queue index is the value returned when you created the queue using the function audio_create_play_queue(), and this function should be called when the queue is no longer required to prevent memory leaks. Freeing the queue will stop any sound that is be playing, and you cannot delete the buffer that a sound is being streamed from until the queue it is assigned to has been freed. This function will trigger an Audio Playback Asynchronous Event, and in this event a special ds_map will be created in the variable async_load with the following key/value pairs:

  • "queue_id" - the queue that has finished playing data
  • "buffer_id" - the buffer that is no longer being played from
  • "queue_shutdown" - this is set to 0 during normal playback and 1 when the event is received because you have freed the queue with this function. When this is set to 1, you don't want to queue up any further data.

Example:

var q_id = async_load[? "queue_id"];
if q_id == audio_queue
   {
audio_free_play_queue(audio_queue);
buffer_delete(audio_buffer);
}

The above code would go in the asynchronous Audio Playback event and checks to see if the audio that has finished playing is from the "audio_queue" and if it is it frees the queue and the buffer associated with it.

Back: Audio Buffers
Next: audio_queue_sound

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_get_listener_count

Returns the number of available listeners for the target platform.

Syntax:

audio_get_listener_count();

Returns: Real

Description

Certain target platforms permit more than one listener, so it is important that you know how many the target has before changing or using different listeners. This function will return the number of listeners available.

Example:

global.listener_num= audio_get_listener_count();

The above code gets the number of available listeners and stores the return value in a global variable.

Back: Audio Listeners
Next: audio_get_listener_info

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_get_listener_info

Returns a ds_map with information about the listener.

Syntax:

audio_get_listener_info(num);

Argument | Description
num | The listener number to get the data for.

Returns: ds_map

Description

This function will create a ds_map and populate it with information for the given listener.

NOTE: You are responsible for the destruction of the returned ds_map using the appropriate function.

The ds_map will contain the following keys:

  1. "name" - The name of the listener, as a string, with "default" being the standard listener name on most target platforms
  2. "mask" - The bit-mask for the listener
  3. "index" - The unique index value of the listener

The mask value can be used to set a sound or emitter to play from multiple listeners at once, simply using the bitwise or "|" to generate a mask for the sound (see the example code below), while the index is used to set the properties like position or velocity for a given listener using functions like audio_listener_set_position().

Example:

var num = audio_get_listener_count();
var mask = 0;
for(var i = 0; i < num; ++i;)
{
var info = audio_get_listener_info(i);
var m = audio_listener_get_data(info[? "mask"]);
mask = mask | m;
ds_map_destroy(info);
}
audio_set_listener_mask(mask);

The above code checks the number of listeners available then loops through them gets their mask bits, which are then combined to create a single bit mask which is applied to the global listener.

Back: Audio Listeners
Next: audio_set_listener_mask

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_get_listener_mask

Gets the default (global) listener bit mask.

Syntax:

audio_get_listener_mask();

Returns: Real

Description

This function will return the bit-mask data that defines the current default (global) mask for the audio listeners.

Example:

var g_mask = audio_get_listener_mask();
if g_mask != global.Audio_Mask
{
var num = audio_get_listener_count();
global.Audio_Mask = 0;
   for(var i = 0; i < num; ++i;)
{
var info = audio_get_listener_info(i);
var m = audio_listener_get_data(info[? "mask"]);
global.Audio_Mask = global.Audio_Mask | m;
ds_map_destroy(info);
}
audio_set_listener_mask(mask);
}

The above code gets the current listener mask data and compares it to the data stored in a global variable. If they are not the same, the code checks the number of listeners available then loops through them and gets their mask bits, which are then combined to create a single mask which is applied to the audio system to define the global listeners.

Back: Audio Listeners
Next: audio_sound_get_listener_mask

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_get_master_gain

Get the global sound and music volume for a specific listener.

Syntax:

audio_get_master_gain(listenerIndex);

Argument | Description
listenerIndex | The index of the listener to get the gain of.

Returns: Real

Description

With this function you can get the absolute value for the global volume of all sounds and music for a specific listener. The default listener index is 0, but you can use the function audio_get_listener_info to get the different indices available for the target platform. The gain value returned is based on a linear scale from 0 (silent) to 1 (full volume).

Example:

var num = audio_get_listener_count();
for( var i = 0; i < num; ++i;)
{
var info = audio_get_listener_info(i);
var ind = info[? "index"];
if audio_get_master_gain(ind) != 1
{
audio_set_master_gain(info[? "index"], 1);
}
ds_map_destroy(info);
}

The above code loops through the available listeners, checking to see if their gain is 1 or not, and if it is not it sets it to 1 for each of them.

Back: Audio
Next: audio_channel_num

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_get_name

Returns the name (as a string) of the given audio resource.

Syntax:

audio_get_name(index);

Argument | Description
index | The index of the sound to check.

Returns: String

Description

This function will return the name of a given audio resource as a string. The "index" value can be that of the resource itself (as seen in the resource tree) or the unique ID value that is given when you play the sound using, for example, audio_play_sound(). Note that the string returned is not the same as the resource ID and cannot be used to access the resource itself, so should only be used for displaying or error checking.

Example:

var snd = audio_play_sound(choose(snd_One, snd_Two, snd_Three), 0, false);
var name = audio_get_name(snd);
show_debug_message("Sound = " + name);

The above code plays a random sound chosen from three different sound resources then shows a debug message with its name.

Back: Audio
Next: audio_get_type

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_get_recorder_count

Returns the number of recording devices found attached to the system.

Syntax:

audio_get_recorder_count();

Returns: Integer

Description

This function will return the number of audio recording sources (like microphones, etc...) currently available to your game. So, if you have a return value of, for example, four, then you will have audio input on the sources 0, 1, 2 and 3, with one of these values being that which you use to start recording from using the function audio_start_recording(). This value can change at any time as people plug/unplug microphones or other input sources to the device. Note that you can use the function audio_get_recorder_info to get information on each device connected.

Example:

if audio_get_recorder_count() > 0
{
channel_index = audio_start_recording(0);
}

The above code checks the audio recorders available and if there are 1 or more, it starts recording from the first one indexed (source 0).

Back: Audio Buffers
Next: audio_get_recorder_info

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_get_recorder_info

Returns a ds_map containing information about the indexed recording device.

Syntax:

audio_get_recorder_info(recorder_index);

Argument | Description
recorder_index | The index of the recorder source to get the information from.

Returns: ds_map

Description

This function will return a ds_map with information about the given recorder source index. You can find out how many recorder sources are available using the function audio_get_recorder_count, and the map returned will contain the following key/value pairs:

  • "name" - a name to describe the device
  • "index" - the index to be used to record
  • "data_format" - the format data will be returned in (this is currently always buffer_s16 but other formats may be supported in the future)
  • "sample_rate" - the sample rate (in Hz) of the data returned (currently clamped to 16000hz but this may change in future)
  • "channels" - the constant audio_mono (further constants for stereo and 3D may be supported in the future)

note that while the function creates a ds_map for you, it does not remove it again later and so you should be destroying the map yourself when it is no longer needed to prevent any memory leaks.

NOTE: Most platforms support recording audio in some form, but that does not mean that all devices will permit it, even if the platform does, so you should always check that the audio_get_recorder_count() function returns a value greater than 0 to verify that recording devices are available before using the rest of the recording functions.

Example:

len = async_load[? "data_len"];
audio_buff = buffer_create(len, buffer_fast, 1);
buffer_copy(async_load[? "buffer_id"], 0, len, buff, 0);
audio_queue_sound(audio_queue, audio_buff, 0, len);
audio_play_sound(audio_queue, 10, 0);

The above code would be called in the asynchronous Audio Recording event and assigns some recorded data to a buffer, which is then added to an audio queue. This is then played.

Back: Audio Buffers
Next: audio_system

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_get_type

Returns the type of audio for the given sound.

Syntax:

audio_get_type(index);

Argument | Description
index | The index of the sound to check.

Returns: Real

Description

When adding audio to GameMaker: Studio it can be either streamed or in memory. If you need to know whether a given sound index is for streamed audio or not you can use this function which will return 1 for streamed, 0 for sound in memory, and -1 if there is any error or the index does not point to a valid sound resource.

Example:

type = audio_get_type(snd_Music_1);

The above code checks the type of audio indexed in the variable "snd_Music_1" and stores the returned value in the variable "type".

Back: Audio
Next: audio_play_sound

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_group_is_loaded

Check an audio group to see if it is loaded into memory.

Syntax:

audio_group_is_loaded(groupID);

Argument | Description
groupID | The index of the audio group to check (as defined in the Global Game Settings Audio Groups Tab)

Returns: Boolean

Description

This function will check a specific audio group to see if it has been loaded into memory, ready for use.

Example:

if audio_group_is_loaded(audiogroup_level1)
{
audio_group_unload(audiogroup_level1);
}

The above code checks to see if an audio group has been loaded and if it has it unloads it.

Back: Audio Groups
Next: audio_group_load_progress

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_group_load

Load an audio group into memory asynchronously.

Syntax:

audio_group_load(groupID);

Argument | Description
groupID | The index of the audio group to load (as defined in the Global Game Settings Audio Groups Tab)

Returns: Boolean

Description

This function will load all the sounds that are flagged as belonging to the given Audio Group into memory. The function will return true if loading is initiated and false if the group ID is invalid, or it has already been flagged for loading. The function is asynchronous so your game will continue to run while the audio is loaded in the background. This means that it will also trigger an Asynchronous Load/Save Event to inform you that the whole group has been loaded into memory and the sounds can now be used.

Example:

if !audio_group_is_loaded(audiogroup_level1)
{
audio_group_load(audiogroup_level1);
}

The above code checks to see if an audio group has been loaded and if not, it loads it.

Back: Audio Groups
Next: audio_group_unload

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_group_load_progress

Get the loading progress for an audio group.

Syntax:

audio_group_load_progress(groupID);

Argument | Description
groupID | The index of the audio group to check (as defined in the Global Game Settings Audio Groups Tab)

Returns: Real

Description

This function will check the loading progress for an audio group and return an (approximate) value between 0 and 100.

Example:

if load
{
var pc = audio_group_load_progress(audiogroup_level1);
draw_text(32, 32, "Loading: " + string(pc));
}

The above code checks a variable and if it returns true then some text will be drawn showing the progress of the audio being loaded.

Back: Audio Groups
Next: audio_group_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_group_name

Returns the name of the audio group as a string.

Syntax:

audio_group_name(groupID);

Argument | Description
groupID | The index value constant of the audio group to check (as defined in the Global Game Settings Audio Groups Tab)

Returns: String

Description

This function will return a string containing the name of the given audio group for displaying or checking. When you define an audio group in the Global Game Settings, you give it a unique "name" which is really a constant to use as an ID value for the group. All this function does is take the ID and return a string of the ID name you gave.

Example:

var name= audio_group_name(audiogroup_level1);
draw_text(32, 32, "Now Playing Group: " + name);

The above code retrieves the name of the given audio group constant and displays it on the screen.

Back: Audio Groups
Next: audio_group_stop

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_group_set_gain

Set the gain for all audio assigned to the given group.

Syntax:

audio_group_set_gain(groupID, volume, time);

Argument | Description
groupID | The index of the audio group to stop (as defined in the Global Game Settings Audio Groups Tab)
volume | The final value for the group volume.
time | The length of the change in gain in milliseconds.

Returns: N/A

Description

With this function you can fade a group of sounds in or out over a given length of time, or it can be used to set the group gain instantly. The time is measured in milliseconds, and the function requires that you input a final level of gain for the group to have reached by the end of that time. This gain can be between 0 (silent) and 1 (full volume) and the scale is linear, such that a value of 0.5 would be half volume. To instantly change the gain, simply set the time argument to 0.

Example:

if keyboard_check_pressed(vk_space)
{
audio_group_set_gain(audiogroup1, 0, 5000);
}

The above code checks for the "space" key and then fades all the audio for "audiogroup1" down to 0 over 5 seconds.

Back: Audio Groups
Next: audio_emitter_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_group_stop

Stops all sounds assigned to a given audio group playing.

Syntax:

audio_group_stop(groupID);

Argument | Description
groupID | The index of the audio group to stop (as defined in the Global Game Settings Audio Groups Tab)

Returns: N/A

Description

This function will stop all sounds from the given audio group that are currently playing.

Example:

if keyboard_check_pressed(vk_space)
{
audio_group_stop(audiogroup_level1);
}

The above code checks for the "space" key and then stops all the audio playing from the given group.

Back: Audio Groups
Next: audio_group_set_gain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_group_unload

Unload an audio group from memory.

Syntax:

audio_group_unload(groupID);

Argument | Description
groupID | The index of the audio group to unload (as defined in the Global Game Settings Audio Groups Tab)

Returns: Boolean

Description

This function will unload all the sounds that are flagged as belonging to the given Audio Group into memory. The function will return true if unloading is initiated and false if the group ID is invalid, or it has already been flagged for unloading. Note that any audio currently being played when this function is called will be stopped.

Example:

if audio_group_is_loaded(audiogroup_level1)
{
audio_group_unload(audiogroup_level1);
}

The above code checks to see if an audio group has been loaded and if it has it unloads it.

Back: Audio Groups
Next: audio_group_is_loaded

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_is_paused

Checks to see if the indicated sound is paused.

Syntax:

audio_is_paused(index);

Argument | Description
index | The index of the sound to check.

Returns: Boolean

Description

This function will check the given sound to see if it is currently paused. The sound can either be a single instance of a sound (the index for individual sounds being played can be stored in a variable when using the audio_play_sound or audio_play_sound_at functions) or a sound asset, in which case all instances of the given sound will be checked and if any of them are paused the function will return true otherwise it will return false.

Example:

if audio_is_paused(snd_Waterfall)
{
audio_resume_sound(snd_Waterfall);
}

The above code checks to see if the sound indexed in the variable "snd_Waterfall" is currently paused and if it returns true then the playing of the sound will be resumed.

Back: Audio
Next: audio_create_stream

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_is_playing

Checks to see if the indicated sound is playing.

Syntax:

audio_is_playing(index);

Argument | Description
index | The index of the sound to check.

Returns: Boolean

Description

This function will check the given sound to see if it is currently playing. The sound can either be a single instance of a sound (the index for individual sounds being played can be stored in a variable when using the audio_play_sound or audio_play_sound_at functions) or a sound asset, in which case all instances of the given sound will be checked and if any of them are playing the function will return true otherwise it will return false. Note that this function will still return true if the sound being checked has previously been paused using the audio_pause_sound function.

Example:

if !audio_is_playing(snd_Waterfall)
{
audio_play_sound_at(snd_Waterfall, x, y, 0, 300, true, 1);
}

The above code checks to see if the sound indexed in the variable "snd_Waterfall" is currently playing and if it returns false then the sound will be looped at its room position, with a fall-off distance of 300 and a low priority.

Back: Audio
Next: audio_is_paused

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_listener_get_data

Returns a ds_map with position, velocity and orientation data for the given listener.

Syntax:

audio_listener_get_data(index);

Argument | Description
index | The listener to get the data for (default 0).

Returns: ds_map

Description

This function will create a ds_map and populate it with the position, velocity and orientation values for the given listener. The default listener index is 0, but you can use the function audio_get_listener_info to get the different indices available for the target platform. If you provide an incorrect listener index then the function will return -1.

NOTE: You are responsible for the destruction of the returned ds_map using the appropriate function.

The ds_map will contain the following keys:

  1. "x" - The x position of the listener
  2. "y" - The y position of the listener
  3. "z" - The z position of the listener
  4. "vx" - The x axis velocity of the listener
  5. "vy" - The y axis velocity of the listener
  6. "vz" - The z axis velocity of the listener
  7. "lookat_x" - The x component of the look at vector of the listener
  8. "lookat_y" - The y component of the look at vector of the listener
  9. "lookat_z" - The z component of the look at vector of the listener
  10. "up_x" - The x component of the up vector of the listener
  11. "up_y" - The y component of the up vector of the listener
  12. "up_z" - The z component of the up vector of the listener

Example:

var num = audio_get_listener_count();
for(var i = 0; i < num; ++i;)
{
var info = audio_get_listener_info(i);
var data = audio_listener_get_data(info[? "index"]);
if data[? "x"] != 0
{
audio_listener_set_position(info[? "index"], 0, 0, 0);
}
ds_map_destroy(info);
ds_map_destroy(data);
}

The above code checks the number of listeners available then loops through them and if their x position is not 0, it sets their position to 0, 0, 0.

Back: Audio Listeners
Next: audio_listener_set_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_listener_orientation

Changes the orientation of the listener within the audio space.

Syntax:

audio_listener_orientation(lookat_x, lookat_y, lookat_z, up_x, up_y, up_z);

Argument | Description
lookat_x | The x look vector (default 0).
lookat_y | The y look vector (default 0).
lookat_z | The z look vector (default 1000).
up_x | The x up vector (default 0).
up_y | The y up vector (default 1).
up_z | The z up vector (default 0).

Returns: N/A

Description

With this function you can change the orientation of the listener within the 3D audio space. The look at direction and up direction are based on the vectors that are resolved from the given relative x, y and z positions (for more information on vectors, please see Maths - Vectors), and default to (0, 0, 1000) for the look at direction and (0, 1, 0) for the up direction, as shown in the illustration below:

NOTE: if you have multiple listeners you should use the function audio_listener_set_orientation.

Changing the listener orientation with this function will change how sound created by audio emitters around the game room are perceived by the player of your game. In the example below, sounds created by the emitter when the listener is at the default position would appear to be coming from below and to the right of the listener, but with the new position and orientation of the listener they will now be perceived as coming from above and to the right.

Example:

xt = x + cos(degtorad(direction));
yt = y - sin(degtorad(direction));
zt = z - sin(degtorad(zdirection));
d3d_set_projection(x, y, z, xt, yt, zt, 0, 0, 1);
audio_listener_position(x, y, z)
audio_listener_orientation(xt, yt, zt, 0, 0, 1)

The above code use three variables to set the 3D camera projection and the 3D audio listener position and orientation too.

Back: Audio Listeners
Next: audio_listener_get_data

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_listener_position

Changes the position of the listener within the audio space.

Syntax:

audio_listener_position(x, y, z);

Argument | Description
x | The x position of the listener (default 0).
y | The y position of the listener (default 0).
z | The z position of the listener (default 0).

Returns: N/A

Description

With this function you can change the position of the listener within the 3D audio space. The example image below shows the default position for the listener in the audio space:

NOTE: if you have multiple listeners you should use the function audio_listener_set_position.

As you can see, the default position is (0, 0, 0) but you would normally use this function to move the listener around with the player object within your game and so change the way audio created by emitters is heard by the player, for example, in the image below of a top down game, the player instance sets the listener which will cause the audio from the various emitters to "change" as the player moves around the level:

Example:

if speed > 0
{
audio_listener_position(x, y, 0);
}

The above code checks to see if the player instance speed is over 0 and if it is it updates the audio listener to the current x/y position.

Back: Audio Listeners
Next: audio_listener_velocity

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_listener_set_orientation

Changes the orientation of the given listener within the audio space.

Syntax:

audio_listener_set_orientation(index, x, y, z);

Argument | Description
index | The listener to get the data for (default 0).
lookat_x | The x look vector (default 0).
lookat_y | The y look vector (default 0).
lookat_z | The z look vector (default 1000).
up_x | The x up vector (default 0).
up_y | The y up vector (default 1).
up_z | The z up vector (default 0).

Returns: N/A

Description

With this function you can change the orientation of the given listener within the 3D audio space. The default listener index is 0, but you can use the function audio_get_listener_info to get the different indices available for the target platform.

The look at direction and up direction are based on the vectors that are resolved from the given relative x, y and z positions (for more information on vectors, please see Maths - Vectors), and default to (0, 0, 1000) for the look at direction and (0, 1, 0) for the up direction, as shown in the illustration below: Changing the given listener orientation with this function will change how sound created by audio emitters around the game room are perceived by the player of your game. In the example below, sounds created by the emitter when the listener is at the default position would appear to be coming from below and to the right of the listener, but with the new position and orientation of the listener they will now be perceived as coming from above and to the right.

Example:

var num = audio_get_listener_count();
for(var i = 0; i < num; ++i;)
{
var info = audio_get_listener_info(i);
var data = audio_listener_get_data(info[? "index"]);
if data[? "up_x"] != 0
{
audio_listener_set_orientation(info[? "index"], 0, 0, 1000, 0, 1, 0);
}
ds_map_destroy(info);
ds_map_destroy(data);
}

The above code checks the number of listeners available then loops through them and if their up_x orientation is not 0, it sets all their orientation values to default ones.

Back: Audio Listeners
Next: audio_get_listener_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_listener_set_position

Changes the position of the given listener within the audio space.

Syntax:

audio_listener_set_position(index, x, y, z);

Argument | Description
index | The listener to get the data for (default 0).
x | The x position of the listener (default 0).
y | The y position of the listener (default 0).
z | The z position of the listener (default 0).

Returns: N/A

Description

With this function you can change the position of a given listener within the 3D audio space. The default listener index is 0, but you can use the function audio_get_listener_info to get the different indices available for the target platform. The example image below shows the default position for the listener in the audio space: As you can see, the default position is (0, 0, 0) but you would normally use this function to move the listener around with the player object within your game and so change the way audio created by emitters is heard by the player, for example, in the image below of a top down game, the player instance sets the listener which will cause the audio from the various emitters to "change" as the player moves around the level:

Example:

var num = audio_get_listener_count();
for(var i = 0; i < num; ++i;)
{
var info = audio_get_listener_info(i);
var data = audio_listener_get_data(info[? "index"]);
if data[? "x"] != 0
{
audio_listener_set_position(info[? "index"], 0, 0, 0);
}
ds_map_destroy(info);
ds_map_destroy(data);
}

The above code checks the number of listeners available then loops through them and if their x position is not 0, it sets their position to 0, 0, 0.

Back: Audio Listeners
Next: audio_listener_set_velocity

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_listener_set_velocity

Changes the velocity of the given listener within the audio space.

Syntax:

audio_listener_set_velocity(index, x, y, z);

Argument | Description
index | The listener to get the data for (default 0).
x | The x velocity of the listener (default 0).
y | The y velocity of the listener (default 0).
z | The z velocity of the listener (default 0).

Returns: N/A

Description

This function can be used to give the given listener doppler effects and simulate audio motion based on the vector that is resolved from the given relative x, y and z positions (for more information on vectors, please see Maths - Vectors). The default listener index is 0, but you can use the function audio_get_listener_info to get the different indices available for the target platform.

If the given listener is not ever going to move, or the movement is not a constant motion, you would normally not need to set these values, but, for example, if you are making a scrolling game where the player has a constant bottom to top movement and the enemies a constant top to bottom movement, you would set the listener and emitter velocities (for emitters you would use audio_emitter_velocity) to the appropriate vectors to simulate the correct doppler effect as they move past the player instance.

The image below shows how this could be setup for the example game given above:

Example:

var num = audio_get_listener_count();
for(var i = 0; i < num; ++i;)
{
var info = audio_get_listener_info(i);
var data = audio_listener_get_data(info[? "index"]);
if data[? "vx"] != 0
{
audio_listener_set_velocity(info[? "index"], 0, 0, 0);
}
ds_map_destroy(info);
ds_map_destroy(data);
}

The above code checks the number of listeners available then loops through them and if their x velocity is not 0, it sets their velocity values to 0, 0, 0.

Back: Audio Listeners
Next: audio_listener_set_orientation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_listener_velocity

Changes the doppler calculations of the listener within the audio space.

Syntax:

audio_listener_velocity(vx, vy, vz);

Argument | Description
x | The x velocity component of the listener (default 0).
y | The y velocity component of the listener (default 0).
z | The z velocity component of the listener (default 0).

Returns: N/A

Description

This function can be used to give the listener doppler effects and simulate audio motion based on the vector that is resolved from the given relative x, y and z positions (for more information on vectors, please see Maths - Vectors). If the listener itself is not ever going to move, or the movement is not a constant motion, you would normally not need to set these values, but, for example, if you are making a scrolling game where the player has a constant bottom to top movement and the enemies a constant top to bottom movement, you would set the listener and emitter velocities (for emitters you would use audio_emitter_velocity) to the appropriate vectors to simulate the correct doppler effect as they move past the player instance.

NOTE: if you have multiple listeners you should use the function audio_listener_set_velocity.

The image below shows how this could be setup for the example game given above:

Example:

if speed > 0
{
audio_listener_velocity(abs(hspeed), abs(vspeed), 0);
}

The above code checks to see if the player instance speed is over 0 and if it is it then uses the appropriate absolute hspeed and vspeed components to set the listener velocity.

Back: Audio Listeners
Next: audio_listener_orientation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_master_gain

Set the global sound and music volume.

Syntax:

audio_master_gain(gain);

Argument | Description
gain | Value for the global volume (0 to 1).

Returns: N/A

Description

With this function you can set the absolute value for the global volume of all sounds and music. It is based on a linear scale from 0 (silent) to 1 (full volume) and will affect the relative volume of all sounds and music played from within your game.

Example:

if keyboard_check(vk_up)
{
if vol < 1 vol += 0.05;
audio_master_gain(vol);
}
if keyboard_check(vk_down)
{
if vol > 0 vol -= 0.05;
audio_master_gain(vol);
}

The above code checks for key-presses of the up and down arrow keys, which then increase or decrease the variable "vol". This variable is then used to set the global gain of all sound and music in the game.

Back: Audio
Next: audio_set_master_gain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_music_gain

Set the volume for music files to play at (OBSOLETED).

Syntax:

audio_music_gain(volume, time);

Argument | Description
volume | Value for the music volume.
time | The length for the change in gain in milliseconds.

Returns: N/A

Description

WARNING! This function has been obsoleted and you should use audio_sound_gain instead.

With this function you can fade music in or out over a given length of time. The time is measured in milliseconds, and the function requires that you input a final gain for the sound to have reached by the end of that time. This gain will generally be between 0 (silent) and 1 (full volume) and the scale is logarithmic in nature, so a gain of 0.5 is not half volume, as illustrated by the image below:

This function will affect all music that can be played in the game and the final gain will set the volume at which all later music files will be played.

Example:

if val
{
audio_music_gain(0, 0);
audio_play_music(snd_music, true);
audio_music_gain(1, 5000);
}

The above code checks a variable and if it returns true, the code will set the gain for the music indexed as "snd_Music" to 0, then start it playing, and then set the gain to fade up to full volume (1) over 5 seconds (5000 milliseconds).

Back: Audio
Next: audio_get_type

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_music_is_playing

Checks to see if music is currently playing (OBSOLETED).

Syntax:

audio_music_is_playing();

Returns: Boolean

Description

WARNING! This function has been obsoleted and you should use audio_is_playing instead.

This function will check to see if a music file is currently playing, returning true if it is and false if it is not.

Example:

if !audio_music_is_playing()
{
audio_play_music(snd_Intro, true);
}

The above code checks to see if any music is playing and if it is not, it then plays the track indexed in "snd_Intro".

Back: Audio
Next: audio_music_gain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_pause_all

Pauses all sounds.

Syntax:

audio_pause_all();

Returns: N/A

Description

With this function you can pause all sounds that are currently playing.

Example:

if keyboard_check_pressed(ord("P"))
{
global.Pause = !global.Pause;
if global.Pause
{
audio_pause_all();
}
else
{
audio_resume_all();
}
}

The above code checks for a press of the keyboard key "P" and if it detects one it sets the global variable "Pause" to true or false and then either pauses all sounds or restarts all previously paused sounds.

Back: Audio
Next: audio_resume_sound

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_pause_music

Pauses the indicated music track (OBSOLETED).

Syntax:

audio_pause_music();

Returns: N/A

Description

WARNING! This function has been obsoleted and you should use audio_pause_sound instead.

With this function you can pause a music track that is currently playing.

Example:

if keyboard_check_pressed(ord("P"))
{
global.Pause = !global.Pause;
if global.Pause
{
audio_pause_music();
}
else
{
audio_resume_music();
}
}

The above code checks for a press of the keyboard key "P" and if it detects one it sets the global variable "Pause" to true or false and then either pauses the music or it resumes the music from its paused state depending on the returned value.

Back: Audio
Next: audio_resume_music

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_pause_sound

Pauses the indicated sound.

Syntax:

audio_pause_sound(index);

Argument | Description
index | The index of the sound to pause.

Returns: N/A

Description

With this function you can pause any sound that is currently playing. The sound can either be a single instance of a sound (the index for individual sounds being played can be stored in a variable when using the audio_play_sound or audio_play_sound_at functions) or a sound asset, in which case all instances of the given sound will be paused.

Example:

if keyboard_check_pressed(ord("P"))
{
global.Pause = !global.Pause;
if global.Pause
{
audio_pause_sound(snd_Waterfall);
}
else
{
audio_resume_sound(snd_Waterfall);
}
}

The above code checks for a press of the keyboard key "P" and if it detects one it sets the global variable "Pause" to true or false and then either pauses the sound indexed in the variable "snd_Waterfall" or it resumes the sound from its paused state.

Back: Audio
Next: audio_pause_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_pause_sync_group

Pause a synchronised group of tracks that are currently playing.

Syntax:

audio_pause_sync_group(group_index);

Argument | Description
group_index | The group index to pause.

Returns: N/A

Description

This function will pause the given sync group if it is playing, with the group index being the value returned when you created the group using the function audio_create_sync_group(). This does not stop the sound, and calling audio_resume_sync_group(), will start it playing from the same position it was paused at again.

Example:

if (keyboard_check_pressed((ord)"P"))
{
global.Pause = !global.Pause
if global.Pause
{
audio_pause_sync_group(sg);
}
else
{
audio_resume_sync_group(sg);
}
}

The above code checks for a key press of the "P" key, and if one is detected it toggles the "global.Pause" variable then checks it to pause or resume the sync group indexed in the variable "sg".

Back: Audio Synchronisation
Next: audio_resume_sync_group

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_play_in_sync_group

Assign a sound resource to a sync group.

Syntax:

audio_play_in_sync_group(group_index, sound_index);

Argument | Description
group_index | The group index to assign the sound to.
sound_index | The sound index to be assigned to the group.

Returns: Index

Description

With this function you can assign a sound to a previously create sync group. The group index is the value returned when you created the group using the function audio_create_sync_group(), and the sound index is the index of any compressed sound (*.ogg or *.mp3) from the resource tree. This function only adds the sound to the group, but it does not play the sound. The function returns a unique ID value for the sound that has been added (distinct to the sound index) which can then be used as usual in all the other audio functions.

Example:

sg = audio_create_sync_group(true);
snd[0] = audio_play_in_sync_group(sg, sound1);
snd[1] = audio_play_in_sync_group(sg, sound2);
snd[2] = audio_play_in_sync_group(sg, sound3);
snd[3] = audio_play_in_sync_group(sg, sound4);
audio_sound_gain(snd[2], 0, 0);
audio_sound_gain(snd[3], 0, 0);
audio_sound_gain(snd[4], 0, 0);
audio_start_sync_group(sg);

The above creates a new sync group and assigns the index of the group to the variable "sg". Four sounds are then added to the group, with the gain for three of them being set to 0. Finally the sync group is played.

Back: Audio Synchronisation
Next: audio_start_sync_group

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_play_music

Plays the indicated background music either once or in a continuous loop (OBSOLETE).

Syntax:

audio_play_music(index, loop);

Argument | Description
index | The index of the music to play.
loop | Flags the music as looping or not.

Returns: N/A

Description

WARNING! This function has been obsoleted and you should use audio_play_sound and audio_stop_sound instead.

This function can be used to start a piece of background music playing. You can only have one piece of background playing at a time when using this function, and starting a sound while a previous one is playing will end the previous one directly. You can also choose whether the sound should loop back to the beginning by setting the loop flag to true, or only to play once by setting it to false.

Example:

if !global.Music
{
audio_stop_music();
}
else
{
audio_play_music(snd_MusicIntro, true);
}

The above code checks the global variable "Music" and if it returns false, it will stop all background music that is currently playing, and if it returns true, it will loop the music indexed in the variable "snd_MusicIntro".

Back: Audio
Next: audio_pause_music

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_play_sound

Plays the indicated sound.

Syntax:

audio_play_sound(index, priority, loop);

Argument | Description
index | The index of the sound to play.
priority | Set the channel priority for the sound.
loop | Sets the sound to loop or not.

Returns: Index

Description

With this function you can play any sound resource in your game. You provide the sound index and assign it a priority, which is then used to determine how sounds are dealt with when the number of sounds playing is over the limit set by the function audio_channel_num. Lower priority sounds will be stopped in favour of higher priority sounds, and the priority value can be any real number (the actual value is arbitrary, and can be from 0 to 1 or 0 to 100, as GameMaker: Studio will prioritize them the same). The final argument is for making the sound loop and setting it to true will make the sound loop until it is stopped and setting it to false will play the sound once only.

This function will also return a unique index number for the sound being played which can then be stored in a variable so that you can then pause it or stop it with the appropriate functions. This means that if you have multiple instances of the same sound playing at any one time you can target just one instance of that sound to deal with using the audio functions.

Example:

if health <= 0
{
lives -= 1;
audio_play_sound(snd_PlayerDead, 10, false);
}

The above code checks the "health" global variable and if it is less than or equal to 0, it will remove 1 from the "lives" global variable and play a sound.

Back: Audio
Next: audio_play_sound_at

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_play_sound_at

Plays the indicated sound at a given position.

Syntax:

audio_play_sound_at(index, x, y, z, falloff_ref, falloff_max, falloff_factor, loop, priority);

Argument | Description
index | The index of the sound to play.
x | The x position.
y | The y position.
z | The z position.
falloff_ref | The falloff reference relative to the listener (clamp).
falloff_max | The maximum falloff distance relative to the listener.
falloff_factor | The falloff factor (default 1).
loop | Flags the sound as looping or not.
priority | Set the channel priority for the sound.

Returns: Index

Description

With this function you can play any sound resource at a given position within the audio space. You provide the sound index and then assign it a position within the 3D space. The default listener position is (0, 0, 0) so this means that if the listener has not been moved and you want the sound to come from the left (for example), you should set the x position to a negative value (for more information on setting the listener position see audio_listener_position).

You can also set a fall-off distance (0 will make the sound silent, default is 100) which will make the sound fade out as it gets further from the listener position. How the fade itself is heard will depend on the falloff reference (which is the distance under which the volume for the source would normally drop by half) and the roll off factor (which affects the sound past the falloff reference distance only). The default factor is normally 1, and the effect of the different falloff values will depend on the model chosen (for a complete guide to the different falloff models and how these values are used, please see the function audio_falloff_set_model).

The last two arguments are to set the sound is to loop or not and, finally, for assigning a priority to the sound. This priority is then used to determine how sounds are dealt with when the number of sounds playing is over the limit set by the function audio_channel_num. Lower priority sounds will be stopped in favour of higher priority sounds, and the priority value can be any real number (the actual value is arbitrary, and can be from 0 to 1 or 0 to 100, as GameMaker: Studio will prioritize them the same).

This function will return a unique index number for the sound being played which can then be stored in a variable so that you can then pause it or stop it with the appropriate functions. This means that if you have multiple instances of the same sound playing at any one time you can target just one instance of that sound to deal with using the audio functions.

Example:

if global.SFX
{
audio_play_sound_at(snd_Waterfall, x, y, 0, 100, 300, 1, true, 1);
}

The above code checks the global variable "SFX" and if it returns true then the sound indexed in the variable "snd_Waterfall" will be looped at its room position, with a fall-off reference of 100, a falloff distance of 300, a falloff factor of 1 and a low priority.

Back: Audio
Next: audio_pause_sound

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_play_sound_on

Plays the indicated sound on a given emitter.

Syntax:

audio_play_sound_on(emitter, sound, loop, priority);

Argument | Description
emitter | The index of the emitter to use.
sound | The index of the sound to use.
loop | Flags the sound as looping or not.
priority | Set the channel priority for the sound.

Returns: Index

Description

With this function you can play any sound resource through an emitter, with any changes to the emitter gain, position, pitch or velocity affecting how the user hears the final sound being played. You provide the emitter index to use, the sound index of the sound to be played and then specify whether the sound is to loop or not. Finally you can assign a priority, which is then used to determine how sounds are dealt with when the number of sounds playing is over the limit set by the function audio_channel_num. Lower priority sounds will be stopped in favour of higher priority sounds, and the priority value can be any real number (the actual value is arbitrary, and can be from 0 to 1 or 0 to 100, as GameMaker: Studio will prioritize them the same).

This function will also return a unique index number for the sound being played which can then be stored in a variable so that you can then pause it or stop it with the appropriate functions. This means that if you have multiple instances of the same sound playing at any one time you can target just one instance of that sound to deal with using the audio functions.

Example:

if global.SFX
{
audio_play_sound_on(s_emit, snd_Explode, false, 1);
}

The above code checks the global variable "SFX" and if it returns true then the sound indexed in the variable "snd_Explode" will be played through the emitter indexed in the variable "s_emit" with a low priority and no looping.

Back: Audio Emitters
Next: audio_emitter_get_gain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_queue_sound

Add audio to the audio queue from a buffer.

Syntax:

audio_queue_sound(queueIndex, bufferId, bufferOffset, bufferLength);

Argument | Description
queueIndex | The index of the queue to add to.
bufferId | The buffer to add to the queue.
bufferOffset | The offset within the source buffer to start from.
bufferLength | The length of the buffer (the number of the bytes in the buffer).

Returns: N/A

Description

This function will add the data from a buffer into the audio queue that you previously created using the function audio_create_play_queue. You specify the queue index to add to, and the buffer ID to get the data from as well as the position (offset) within the buffer and the number of bytes to add. Once you have added audio from a buffer to a queue, the buffer cannot be deleted until you have first freed the queue using the function audio_free_play_queue, and the buffer properties should match those of the the queue that you are adding the sound to.

Example:

len = async_load[? "data_len"];
audio_buff = buffer_create(len, buffer_fast, 1);
buffer_copy(async_load[? "buffer_id"], 0, len, buff, 0);
audio_queue_sound(audio_queue, audio_buff, 0, len);
audio_play_sound(audio_queue, 10, 0);

The above code would be called in the asynchronous Audio Recording event and assigns some recorded data to a buffer, which is then added to an audio queue. This is then played.

Back: Audio Buffers
Next: audio_start_recording

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_resume_all

Resumes all sounds after they have been paused.

Syntax:

audio_resume_all();

Returns: N/A

Description

With this function you can resume all sounds that have been paused previously.

Example:

if keyboard_check_pressed(ord("P"))
{
global.Pause = !global.Pause;
if global.Pause
{
audio_pause_all();
}
else
{
audio_resume_all();
}
}

The above code checks for a press of the keyboard key "P" and if it detects one it sets the global variable "Pause" to true or false and then either pauses all sounds or restarts all previously paused sounds.

Back: Audio
Next: audio_stop_sound

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_resume_music

Resumes the current music track after it has been paused (OBSOLETE).

Syntax:

audio_resume_music();

Returns: N/A

Description

WARNING! This function has been obsoleted and you should use audio_resume_sound instead.

With this function you can resume a music track that is currently paused (after using the function audio_pause_music).

Example:

if keyboard_check_pressed(ord("P"))
{
global.Pause = !global.Pause;
if global.Pause
{
audio_pause_music();
}
else
{
audio_resume_music();
}
}

The above code checks for a press of the keyboard key "P" and if it detects one it sets the global variable "Pause" to true or false and then either pauses the music or it resumes the music from its paused state depending on the returned value.

Back: Audio
Next: audio_stop_music

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_resume_sound

Resumes the indicated sound after it has been paused.

Syntax:

audio_resume_sound(index);

Argument | Description
index | The index of the sound to resume.

Returns: N/A

Description

With this function you can resume any sound that is currently paused (after using the function audio_pause_sound). The sound can either be a single instance of a sound (the index for individual sounds being played can be stored in a variable when using the audio_play_sound or audio_play_sound_at functions) or a sound asset, in which case all instances of the given sound will be re-started.

Example:

if keyboard_check_pressed(ord("P"))
{
global.Pause = !global.Pause;
if global.Pause
{
audio_pause_sound(snd_Waterfall);
}
else
{
audio_resume_sound(snd_Waterfall);
}
}

The above code checks for a press of the keyboard key "P" and if it detects one it sets the global variable "Pause" to true or false and then either pauses the sound indexed in the variable "snd_Waterfall" or it resumes the sound from its paused state.

Back: Audio
Next: audio_resume_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_resume_sync_group

Resume playing a paused synchronised group of tracks.

Syntax:

audio_resume_sync_group(group_index);

Argument | Description
group_index | The group index to resume.

Returns: N/A

Description

This function will resume the given sync group if it is playing and has previously been paused (using the function audio_pause_sync_group). The group index is the value returned when you created the group using the function audio_create_sync_group().

Example:

if (keyboard_check_pressed((ord)"P"))
{
global.Pause = !global.Pause
if global.Pause
{
audio_pause_sync_group(sg);
}
else
{
audio_resume_sync_group(sg);
}
}

The above code checks for a key press of the "P" key, and if one is detected it toggles the "global.Pause" variable then checks it to pause or resume the sync group indexed in the variable "sg".

Back: Audio Synchronisation
Next: audio_sync_group_get_track_pos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_set_listener_mask

Sets the default (global) listener bit mask.

Syntax:

audio_set_listener_mask(mask);

Argument | Description
mask | The bitmask data to set for the listeners

Returns: N/A

Description

When using multiple listeners on a system, you can set the bit-mask for a sound and have it heard from the flagged listener only. However, you can also set the global mask using this function and all sounds played normally will be heard from the listeners flagged by this mask, without the need to set the mask for each sound individually.

Example:

var num = audio_get_listener_count();
var mask = 0;
for(var i = 0; i < num; ++i;)
{
var info = audio_get_listener_info(i);
var m = audio_listener_get_data(info[? "mask"]);
mask = mask | m;
ds_map_destroy(info);
}
audio_set_listener_mask(mask);

The above code checks the number of listeners available then loops through them gets their mask bits, which are then combined to create a single bit mask which is applied to the global listener.

Back: Audio Listeners
Next: audio_sound_set_listener_mask

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_set_master_gain

Set the global sound and music volume for a specific listener.

Syntax:

audio_set_master_gain(listenerIndex, gain);

Argument | Description
listenerIndex | The index of the listener to set the gain on.
gain | Value for the global volume (0 to 1).

Returns: N/A

Description

With this function you can set the absolute value for the global volume of all sounds and music for a specific listener. The default listener index is 0, but you can use the function audio_get_listener_info to get the different indices available for the target platform. The gain value is based on a linear scale from 0 (silent) to 1 (full volume) and will affect the relative volume of all sounds and music played from within your game through that listener.

Example:

var num = audio_get_listener_count();
for( var i = 0; i < num; i++;)
{
var info = audio_get_listener_info(i);
audio_set_master_gain(info[? "index"], 0.75);
ds_map_destroy(info);
}

The above code loops through the available listeners and then sets their master gain to 0.75.

Back: Audio
Next: audio_get_master_gain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sound_gain

Set the volume for a specific sound to play at, either instantly or over a given time.

Syntax:

audio_sound_gain(index, volume, time);

Argument | Description
index | The index of the sound to set the gain for.
volume | Value for the music volume.
time | The length for the change in gain in milliseconds.

Returns: N/A

Description

With this function you can fade a sound in or out over a given length of time, or it can be used to set the sound gain instantly. The time is measured in milliseconds, and the function requires that you input a final level of gain for the sound to have reached by the end of that time. This gain can be between 0 (silent) and 1 (full volume) and the scale is linear, such that a value of 0.5 would be half volume. To instantly change the gain, simply set the time argument to 0.

This function will affect all instances of the sound that are playing currently in the room if the index is a sound resource, and the final volume will be the volume at which all further instances of the sound will be played. However if you have used the index returned from a function like audio_play_sound it will only affect that one instance of the sound.

Example:

if val
{
var snd = audio_play_sound(snd_fountain);
audio_sound_gain(snd, 0, 0);
audio_sound_gain(snd, 1, 5000);
}

The above code checks a variable and if it returns true it will then assign the index of a sound to be played to the local variable "snd". This variable is then used to reduce the volume of that specific sound to 0 and fade up to full volume over 5 seconds.

Back: Audio
Next: audio_sound_get_gain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sound_get_gain

Get the volume a specific sound is set to play at.

Syntax:

audio_sound_get_gain(index);

Argument | Description
index | The index of the sound to get the gain of.

Returns: N/A

Description

This function will return the current gain value for the given sound. The sound can either be one referenced from an index for an individual sound being played which has been stored in a variable when using the audio_play_sound or audio_play_sound_at functions, or an actual sound asset from the resource tree.

Example:

if audio_sound_get_gain(snd_Music) != 1
{
audio_sound_gain(snd_Music, 1, 0);
}

The above code will change the gain of the audio played from the sound indexed as "snd_Music" if its gain is not equal to 1.

Back: Audio
Next: audio_master_gain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sound_get_listener_mask

Gets the listener bit-mask data for a sound being played.

Syntax:

audio_sound_get_listener_mask(soundID);

Argument | Description
soundID | The unique ID of the sound to get the mask of

Returns: Real

Description

This function will return the bit-mask data that defines which audio listeners a sound should be played from.

Example:

var snd = audio_play_sound(snd_PlayerDead, 10, false);
if audio_sound_get_listener_mask(snd) != global.PlayerMask
{
audio_sound_set_listener_mask(snd, global.PlayerMask);
}

The above code plays a sound then checks the listener mask data for the sound, and if it's not the same as that which is stored in a global variable, it sets the listener(s) to play from using the mask data stored in the global variable.

Back: Audio Listeners
Next: audio_emitter_get_listener_mask

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sound_get_pitch

Get the pitch of the given sound.

Syntax:

audio_sound_get_pitch(index);

Argument | Description
index | The index of the sound to get the pitch of.

Returns: Real

Description

This function can be used to get the get pitch of a given sound. The sound can either be one referenced from an index for an individual sound being played which has been stored in a variable when using the audio_play_sound or audio_play_sound_at functions, or an actual sound asset from the resource tree.

Example:

if audio_sound_get_pitch(snd_Explode) != 1
{
audio_sound_pitch(snd_Explode, 1);
}

The above code will change the pitch of the audio played from the sound indexed as "snd_Explode" if its pitch is not equal to 1.

Back: Audio
Next: audio_falloff_set_model

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sound_get_track_position

Set a time position for a sound to play from.

Syntax:

audio_sound_get_track_position(index);

Argument | Description
index | The index of the sound to get the play position of.

Returns: Real

Description

This function will get the position (in seconds) within the sound file for the sound to play from. The sound can only be a single instance of a sound (the index for individual sounds being played can be stored in a variable when using the audio_play_sound or audio_play_sound_at functions).

Example:

if audio_sound_get_track_position(global.Music) != 0
{
audio_sound_set_track_position(global.Music, 0);
}

The above code checks a track to get it's start position and if it's not 0 seconds it sets it to 0 seconds.

Back: Audio
Next: audio_sound_length

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sound_length

Returns the length of the indexed sound.

Syntax:

audio_sound_length(index);

Argument | Description
index | The index of the sound to check.

Returns: Real

Description

This function will return the length of the given sound in seconds. The sound can either be a referenced from index for an individual sound being played which has been stored in a variable when using the audio_play_sound or audio_play_sound_at functions, or an actual sound asset from the resource tree.

Example:

var len;
len = audio_sound_length(snd_Beam);
audio_play_sound(snd_Beam, 1, false);
alarm[0] = room_speed * len;

The above code gets the length (in seconds) of the sound indexed in the variable "snd_Beam", then plays the sound and sets an alarm to go off when the sound has finished playing using the length of the sound to calculate the time needed for the alarm.

Back: Audio
Next: audio_sound_pitch

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sound_pitch

Set the pitch of the given sound.

Syntax:

audio_sound_pitch(index, pitch);

Argument | Description
index | The index of the sound to change.
pitch | The pitch multiplier (default 1).

Returns: N/A

Description

This function can be used to change the pitch of a given sound. The sound can either be one referenced from an index for an individual sound being played which has been stored in a variable when using the audio_play_sound or audio_play_sound_at functions, or an actual sound asset from the resource tree. If it is an index of a playing sound, then only that instance will be changed, however when using a sound asset from the resource tree, all further instances being played of that sound will be changed.

The pitch argument is a pitch multiplier, in that the input value multiplies the current pitch by that amount, so the default value of 1 is no pitch change, while a value of less than 1 will lower the pitch and greater than 1 will raise the pitch. It is best to use small increments for this function as any value under 0 or over 5 may not be audible anyway. It is worth noting that the total pitch change permitted is clamped to (1/256) - 256 octaves, so any value over or under this will not be registered.

NOTE: The clamped value given above is what GameMaker: Studio attempts to clamp the range to, but this value is not guaranteed on all target platforms. iOS, for example, clamps to (1/256) - 8, so you may need to experiment on each target platform and have different versions of a sound resource, each one pre-shifted, should you require higher or lower octave values.

Example:

var s_engine = audio_play_sound(snd_CarEngine, 10, false);
switch (gear)
{
case 1: audio_sound_pitch(s_engine, 0.8); break;
case 2: audio_sound_pitch(s_engine, 0.9); break;
case 3: audio_sound_pitch(s_engine, 0.95); break;
case 4: audio_sound_pitch(s_engine, 1); break;
case 5: audio_sound_pitch(s_engine, 1.2); break;
}

The above code will change the pitch of the audio played from the sound indexed in the variable "s_engine" based on the value of the variable "gear".

Back: Audio
Next: audio_sound_get_pitch

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sound_set_listener_mask

Sets the bit mask for a given sound, defining the listeners to play it to.

Syntax:

audio_sound_set_listener_mask(soundID, mask);

Argument | Description
soundID | The unique ID of the sound to set the mask of
mask | The bitmask data to set for the sound

Returns: N/A

Description

This function can be used to set the the bit-mask for a sound so that it will play only from those listeners specified. You can create a bit-mask by using the audio_get_listener_info() and then using the bitwise or ("|") to create a custom mask with those listeners that you require the sound to play from, and then apply this custom mask to the sound after you have played it. This mask will over-ride the default mask or that which you may have set using the function audio_set_listener_mask().

NOTE: This function can only be used on a sound after it has been set to play and requires the soundID as returned by the function used to play the sound.

Example:

var snd = audio_play_sound(snd_PlayerDead, 10, false);
audio_sound_set_listener_mask(snd, global.PlayerMask);

The above code plays a sound then sets the listener(s) to play from using the mask data stored in a global variable.

Back: Audio Listeners
Next: audio_emitter_set_listener_mask

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sound_set_track_position

Set a time position for a sound to play from.

Syntax:

audio_sound_set_track_position(index, time);

Argument | Description
index | The index of the sound to change.
time | The time (in seconds) to set the start point to.

Returns: N/A

Description

This function will set the position (in seconds) within the sound file for the sound to play from. The sound can either be a single instance of a sound (the index for individual sounds being played can be stored in a variable when using the audio_play_sound or audio_play_sound_at functions) or a sound asset. If it is a unique sound ID that you use, then the position will change immediately to the new time given, and if it is a resource tree asset then all further plays of the given sound will start at the new time. The function will ignore any value given that is longer than the length of the sound given for the "index" value.

Example:

var snd = audio_play_sound(snd_MainTrack, 0, false);
audio_sound_set_track_position(snd, 32);

The above code plays a sound and then uses the returned ID value to set the start position for the sound to 32 seconds.

Back: Audio
Next: audio_sound_get_track_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_start_recording

Start recording audio to the recorder buffer from a given source.

Syntax:

audio_start_recording(recorder_index);

Argument | Description
recorder_index | The index of the recorder source to use.

Returns: Index

Description

This function will start recording audio from the recorder source indexed. You can get the number of recorder sources using the function audio_get_recorder_count(), and once you start recording the audio will be stored in a temporary buffer and start triggering an Audio Recording Asynchronous Event. This event is triggered every step that recording takes place and will create the special ds_map in the variable async_load with the following key/value pairs:

  • "buffer_id" - the ID of the temporary buffer you can use to retrieve the audio data
  • "channel_index" - the recording channel index (as returned by the function) this data came from
  • "data_len" - the length of data (in bytes) you've received

Note that after the asynchronous event has been triggered, the audio in the temporary buffer will be wiped, so you should be copying it's data into a custom buffer that you have previously created.

NOTE: Most platforms support recording audio in some form, but that does not mean that all devices will permit it, even if the platform does, so you should always check that the audio_get_recorder_count() function returns a value greater than 0 to verify that recording devices are available before using the rest of the recording functions.

Example:

audio_record = audio_start_recording(0);

The above code starts recording from the recorder source 0, storing the channel index of the recording in the variable "audio_record" for use in the asynchronous Audio Recording event.

Back: Audio Buffers
Next: audio_stop_recording

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_start_sync_group

Start a group of synchronised audio tracks playing.

Syntax:

audio_start_sync_group(group_index);

Argument | Description
group_index | The group index to play.

Returns: N/A

Description

With this function you can strat a previously create sync group playing. The group index is the value returned when you created the group using the function audio_create_sync_group().

Example:

sg = audio_create_sync_group(true);
audio_play_in_sync_group(sg, sound1);
audio_play_in_sync_group(sg, sound2);
audio_set_gain(sound2, 0, 0);
audio_play_in_sync_group(sg, sound3);
audio_set_gain(sound3, 0, 0);
audio_play_in_sync_group(sg, sound4);
audio_set_gain(sound4, 0, 0);
audio_start_sync_group(sg);

The above creates a new sync group and assigns the index of the group to the variable "sg". Four sounds are then added to the group, with the gain for three of them set to 0. Finally the sync group is played.

Back: Audio Synchronisation
Next: audio_stop_sync_group

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_stop_all

Stops all the currently playing sounds.

Syntax:

audio_stop_all();

Returns: N/A

Description

This function will stop all sounds that are currently playing.

Example:

if !global.SFX
{
audio_stop_all();
}

The above code checks the global variable "SFX" and if it returns false, it will stop all sounds that are currently playing.

Back: Audio
Next: audio_is_playing

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_stop_music

Stops the indicated background music (OBSOLETE).

Syntax:

audio_stop_music();

Returns: N/A

Description

WARNING! This function has been obsoleted and you should use audio_play_sound and audio_stop_sound instead.

This function will stop any background music that is currently playing. This function only affects the sounds that have been played by the audio_play_music function.

Example:

if !global.Music
{
audio_stop_music();
}
else
{
audio_play_music(snd_MusicIntro, true);
}

The above code checks the global variable "Music" and if it returns false, it will stop all background music that is currently playing, and if it returns true, it will loop the music indexed in the variable "snd_MusicIntro".

Back: Audio
Next: audio_music_is_playing

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_stop_recording

Add audio to the audio queue from a buffer.

Syntax:

audio_stop_recording(channel_index);

Argument | Description
channel_index | The index of the recorder channel to stop.

Returns: N/A

Description

This function will stop recording on the given recorder channel (the channel index is returned when you call the function audio_start_recording). When you stop recording, no further Audio Recording Asynchronous Events will be triggered for the given recorder channel, so you would normally use this function in the actual asynchronous event to ensure that you have captured all the data.

NOTE: Most platforms support recording audio in some form, but that does not mean that all devices will permit it, even if the platform does, so you should always check that the audio_get_recorder_count() function returns a value greater than 0 to verify that recording devices are available before using the rest of the recording functions.

Example:

audio_stop_recording(audio_channel);

The above code tells GameMaker: Studio to stop recording on the given audio channel index.

Back: Audio Buffers
Next: audio_get_recorder_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_stop_sound

Stops the indicated sound.

Syntax:

audio_stop_sound(index);

Argument | Description
index | The index of the sound to stop.

Returns: N/A

Description

This function will stop the given sound if it is currently playing. The sound can either be a single instance of a sound (the index for individual sounds being played can be stored in a variable when using the audio_play_sound or audio_play_sound_at functions) or a sound asset, in which case all instances of the given sound will be stopped.

Example:

if !global.SFX
{
audio_stop_sound(snd_Waterfall);
}
else
{
audio_play_sound_at(snd_Waterfall, x, y, 0, 100, 300, 1, true, 1);
}

The above code checks the global variable "SFX" and if it returns false, it will stop the sound indexed in the variable "snd_Waterfall" that is currently playing, and if it returns true, it will loop the sound.

Back: Audio
Next: audio_stop_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_stop_sync_group

Stop a synchronised group of tracks that are currently playing.

Syntax:

audio_stop_sync_group(group_index);

Argument | Description
group_index | The group index to stop playing.

Returns: N/A

Description

This function will stop the given sync group if it is playing, with the group index being the value returned when you created the group using the function audio_create_sync_group().

Example:

if mouse_check_button_pressed(mb_left)
{
audio_stop_sync_group(sg);
}

The above code checks for a mouse click, and if one is detected it stops the sync group indexed in the variable "sg".

Back: Audio Synchronisation
Next: audio_pause_sync_group

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sync_group_debug

Toggle on or off the audio sync group debug overlay.

Syntax:

audio_sync_group_debug(group_index);

Argument | Description
group_index | The group index to debug, or -1 to switch off the debugging.

Returns: N/A

Description

This function can be used to display debug information about any given sync group (the group index is the value returned when the group was created using the function audio_create_sync_group()). You can call the function with a value of -1 to switch off the overlay.

When you are debugging the audio sync groups, the overlay will show Which sync groups is debugging

  1. How many channels are in it
  2. How many times the sync group has failed (this means it's tried to do too much work)
  3. A list of the channels
    • Red means this channel is not currently doing any work
    • Yellow means the channel is in initial state (not yet decoding or playing)
    • Green means the track is currently seeking/decoding
    • Purple means the channel has run out of data
  4. A profiling bar that shows what work the decoding thread is doing
    • blue means a file is being read for the first time
    • red means the thread is reading a file to find out where to read from
    • green means the thread is decoding data
    • purple means the thread is sleeping until it needs to work

Note that for general debugging of audio, you also have the function audio_debug().

Example:

if (debug_mode)
{
audio_sync_group_debug(sg);
}
else
{
audio_sync_group_debug(-1);
}

The above code will switch on or off the audio sync group debug overlay showing the sync group indexed in the variable "sg" depending on whether the game is run in debug mode or not.

Back: Audio Synchronisation
Next: audio_sync_group_is_playing

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sync_group_get_track_pos

Get the current play position for the given sync group.

Syntax:

audio_sync_group_get_track_pos(group_index);

Argument | Description
group_index | The group index to get the position of.

Returns: Real

Description

This function returns the current play position of the given sync group. The group index is the value returned when you created the group using the function audio_create_sync_group(), and the return value is the time in seconds that the tracks have been playing.

Example:

var real_secs = audio_sync_group_get_track_pos(sg);
var secs = real_secs mod 60;
var mins = string(real_secs div 60);
if (secs > 9)
{
secs = string(secs);
}
else
{
secs = "0" + string(secs);
}
draw_text(32, 32, "Time = " + mins + ":" + secs);

The above code gets the time position for the sync group indexed in the variable "sg", then uses this value to draw the time played on the screen.

Back: Audio Synchronisation
Next: audio_destroy_sync_group

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_sync_group_is_playing

Check to see if the given sync group is currently playing any audio.

Syntax:

audio_sync_group_is_playing(group_index);

Argument | Description
group_index | The group index to check.

Returns: N/A

Description

This function can be used to check if any audio in a synchronised group is playing. You are required to supply the synch group ID as returned by the function audio_create_sync_group().

Example:

if audio_sync_group_is_playing(group_one)
{
audio_stop_sync_group(group_one);
}

The above code will switch on or off the audio sync group debug overlay showing the sync group indexed in the variable "sg" depending on whether the game is run in debug mode or not.

Back: Audio Synchronisation
Next: audio_create_sync_group

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


audio_system

Checks whether the legacy sound or normal audio is in use.

Syntax:

audio_system();

Returns: Constant

Description

This function returns whether the current sound system is the legacy or the normal one. The return value can be one of the following two constants:

Constant | Description
audio_old_system | the legacy sound system is in use
audio_new_system | the normal sound system is in use

This function is important only if you are using the HTML5 target module, as some browsers are not compatible with the new audio system, and so GameMaker: Studio will automatically switch back to the legacy audio.

Example:

if audio_system() == audio_old_system
{
global.SS = false;
}
else
{
global.SS = true;
}

The above code checks to see if the sound system being used is the legacy or the new one, and sets a global variable accordingly.

Back: Audio
Next: audio_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Legacy Sound

This section explains the Legacy Sound System and its functions.

The Legacy Sound system exists to maximise the compatibility of GameMaker: Studio with previous projects that were made with older versions of GameMaker and as such it needs to be switched on through the setting in the Global Game Settings: General Tab as the default setting is for GM:S Audio support. It should be noted that these functions are not as flexible nor as stable as the newer ones and where possible they should be avoided or changed.

The following legacy functions exist that deal with sounds:

  1. sound_exists
  2. sound_get_name
  3. sound_play
  4. sound_loop
  5. sound_stop
  6. sound_stop_all
  7. sound_isplaying
  8. sound_volume
  9. sound_fade
  10. sound_global_volume

Below you can find a list of functions that have been deprecated in GameMaker: Studio. These functions will no longer work as you must have all sounds included with the game bundle:

  1. sound_add
  2. sound_replace
  3. sound_delete

Back: Sound

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_add

Adds a new sound from a given file. DEPRECATED

Syntax:

sound_add(fname, kind, preload);

Argument | Description
fname | The filename of the sound to add.
kind | The kind of sound it should be added as (legacy Feature) 0=normal, 1=background, 2=3D, 3=multimedia player, for things like MP3s).
preload | Whether the sound should preload into memory immediately (true) or not (false) (legacy Feature) .

Returns: Real

Description

WARNING!: This function has been deprecated and will no longer work!

This function will load a sound file from an external source. This file can be either a *.wav or a *.mp3. The last two arguments are a left over from previous versions of GameMaker and can be set to 0 as they have no effect on the function.

NOTE: Depending on the target platform that is chosen you are limited as to where you can save and load files from. See Reference - Files for more information.

NOTE: You should be aware that if you are using this function in your HTML5 target game to load resources from an external server, then, due to XSS protection in browsers, attempts to load resources from across domains can be blocked and may appear to return blank results.

Example:

global.newsound=sound_add(working_directory + '\hello.wav', 0, 0);
sound_play(global.newsound);

This will add a new sound and store the index of this sound in the variable "global.newsound", from file 'hello.wav' and then play it.

Back: Legacy Sound
Next: sound_replace

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_delete

Deletes the indicated sound to free it from game memory. DEPRECATED

Syntax:

sound_delete(index);

Argument | Description
index | The index of the sound to delete.

Returns: N/A

Description

WARNING!: This function has been deprecated and will no longer work!

This function will delete the indexed sound from your game.

NOTE: This is a permanent removal that lasts as long as the game is running, meaning that if the deleted sound is an included game asset, even restarting the game with game_restart will not restore the sound. For that the game must be exited and re-loaded again.

Example:

if sound_exists(global.Music)
{
sound_delete(global.Music);
}

The above code checks to see if the global variable "Music" indexes a sound and if it does it then deletes that sound from the game.

Back: Legacy Sound
Next: sound_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_exists

Checks whether the given sound exists.

Syntax:

sound_exists(index);

Argument | Description
index | The index of the sound to check the existence of.

Returns: Boolean

Description

This function returns whether a sound exists (true) or not (false). Note that if the index you search for has not been initialised previously, this function will cause an error as it is searching for non-existent asset indices.

Example:

if sound_exists(global.Music)
{
sound_loop(global.Music);
}
else
{
global.Music = sound_add(working_directory + "\MainMusic.mp3", 1, 0);
sound_loop(global.Music);
}

The above code checks to see if a sound exists. If it does it is set to play in a loop, but if it does not, it is loaded into memory from an external source and then set to loop.

Back: Legacy Sound
Next: sound_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_fade

Fade a sound in or out over a given time.

Syntax:

sound_fade(index, value, time);

Argument | Description
index | The index of the sound to fade.
value | The final volume from 0 to 1.
time | The length of the fade in milliseconds.

Returns: N/A

Description

With this function you can fade a sound in or out over a given length of time. The time is measured in milliseconds, and the function requires that you input a final volume for the sound to have reached by the end of that time. This volume can be between 0 (silent) and 1 (full volume) and the volume scale is logarithmic in nature, so a volume of 0.5 is not half volume, as illustrated by the image below:

This function will affect all instances of the sound that are playing currently in the room and the final volume will be the volume at which all further instances of the sound will be played.

Example:

if val == 0
{
sound_volume(snd_Music, 0);
sound_play(snd_music);
sound_fade(snd_Music, 1, 5000);
}

The above code checks a variable and if it returns true, the code will set the volume for the sound indexed as "snd_Music" to 0, then start it playing, and then set the volume to fade up to full volume (1) over 5 seconds (5000 milliseconds).

Back: Legacy Sound
Next: sound_global_volume

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_get_name

Returns the resource name of the given sound.

Syntax:

sound_get_name(index);

Argument | Description
index | The index of the sound to check.

Returns: String

Description

This function will return the name of the given resource as a string. Please note that this is only a string and cannot be used to reference the sound directly - for that you would need the sound index. You can, however, use this string to get the sound index using the returned string along with the function asset_get_index().

Example:

var title;
title = sound_get_name(global.Music);
draw_text(32, 32, "Now Playing:" + title);

The above code gets the name of the sound resource indexed in the global variable "Music" and then displays it on the screen.

Back: Legacy Sound
Next: sound_play

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_global_volume

Sets the volume of all sounds.

Syntax:

sound_global_volume(value);

Argument | Description
value | The new global volume from 0 to 1.

Returns: N/A

Description

With this function you can change the final volume of all sounds in your game. This will change the volume for all future instances created where sound is played, but will not affect those instances already playing sounds, and the volume can be set to a value between 0 (silent) and 1 (full volume), with a value of 1 being the default volume. Note that any individual volumes set with the function sound_volume will also be affected by this function meaning that the final volume for a sound is the compound result of the individual volume and the global volume. The volume scale is logarithmic in nature, so a volume of 0.5 is not half volume, as illustrated by the image below:

Example:

if keyboard_check_pressed(vk_add)
{
if vol < 1 vol += 0.1;
sound_global_volume(vol);
}

The above code checks for a key press and when it detects one it raises the global volume (to a maximum of 1).

Back: Legacy Sound
Next: sound_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_isplaying

Checks to see if a given sound is playing.

Syntax:

sound_isplaying(index);

Argument | Description
index | The index of the sound to check for.

Returns: Boolean

Description

With this function you can check to see if an instance of the sound index is playing currently (true) or not (false). Please note that if you do this check a moment after the indexed sound is supposed to have started it may return false erroneously as the sound system has not had enough time to initialize the sound properly.

Example:

if !sound_isplaying(snd_Music)
{
sound_play(snd_GameOver);
instance_create(x, y, obj_GameOver_Menu);
}

The above code checks the sound to see if it is still playing and if it is not, it plays another sound and creates a new instance.

Back: Legacy Sound
Next: sound_volume

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_loop

Loops the indicated sound.

Syntax:

sound_loop(index);

Argument | Description
index | The index of the sound to loop.

Returns: N/A

Description

This function can be used to make a sound play and loop (ie: when the sound ends it immediately starts again) from the moment the function is called until either of the functions sound_stop or sound_stop_all are used. If the sound to loop is *.mp3 format, then it will silence any other *.mp3 sound currently playing.

Example:

if global.Music
   {
sound_loop(snd_MainMusic);
}

The above code will check a global variable and if it returns true then the sound indexed in the variable "snd_MainMusic" will start to play and loop again when finished.

Back: Legacy Sound
Next: sound_stop

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_play

Plays the indicated sound once.

Syntax:

sound_play(index);

Argument | Description
index | The index of the sound to play.

Returns: N/A

Description

This function plays the specified sound once. If the sound to played is in *.mp3 format (ie: background music), then any other sound that is playing with the same format will be stopped as the legacy GameMaker: Studio sound system does not permit more than one *.mp3 format file to be played at a time.

Example:

if mouse_check_button_pressed(mb_left)
{
sound_play(snd_MB_Press);
}

The above code checks to see if the left mouse button has been pressed and if it has, it will play the sound indexed in the variable "snd_MB_Press" once.

Back: Legacy Sound
Next: sound_loop

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_replace

Replaces an existing sound with one from a given filename DEPRECATED.

Syntax:

sound_replace(index, fname, kind, preload);

Argument | Description
index | The index of the sound to be replace.
fname | The filename of the new sound.
kind | The kind of sound it should be added as (legacy Feature) 0=normal, 1=background, 2=3D, 3=multimedia player, for things like MP3s).
preload | Whether the sound should preload into memory immediately (true) or not (false) (legacy Feature) .

Returns: Boolean

Description

WARNING!: This function has been deprecated and will no longer work!

This function will load a sound file from an external source into a previously created sound asset (normally one from the resource tree, but you can also replace sounds that have been added using the sound_add function. This file can be either a *.wav or a *.mp3. The last two arguments are a left over from previous versions of GameMaker and can be set to 0 as they have no effect on the function.

NOTE: Depending on the target platform that is chosen you are limited as to where you can save and load files from. See Reference - Files for more information.

NOTE: You should be aware that if you are using this function in your HTML5 target game to load resources from an external server, then, due to XSS protection in browsers, attempts to load resources from across domains can be blocked and may appear to return blank results.

Example:

if sound_exists(global.Music)
{
sound_replace(global.Music, working_directory + "\bgm.mp3", 0, 0);
sound_loop(global.Music);
}

The above code checks to see if a sound is indexed in the global variable "Music" and if it is it replaces that sound with another and then sets it to loop.

Back: Legacy Sound
Next: sound_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_stop

Stops a given sound.

Syntax:

sound_stop(index);

Argument | Description
index | The index of the sound to stop.

Returns: N/A

Description

With this function you can stop all instances of the given sound. Note that if the sound is being played by different instances all will stop playing, regardless of the instance running this code or that is playing the sound.

Example:

if lives = 0
{
sound_stop(snd_GameMusic);
}

The above code will check the number of lives that the player has and if it is equal to 0, it will stop the sound playing that is indexed in the variable "snd_GameMusic".

Back: Legacy Sound
Next: sound_stop_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_stop_all

Stops every currently-playing sound.

Syntax:

sound_stop_all();

Returns: N/A

Description

With this function you can stop not just one sound, but all sounds that are currently being played (or looped) in the current room, irrespective of the instance that is playing them, or the instance that is running this function.

Example:

if keyboard_check_pressed(ord("M"))
{
global.Sound = false;
sound_stop_all();
}

The above code will check for a press of the keyboard and if it detects one it will set a global variable and stop all sounds.

Back: Legacy Sound
Next: sound_isplaying

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sound_volume

Sets the volume of a given sound.

Syntax:

sound_volume(index, value);

Argument | Description
index | The index of the sound to change the volume of.
value | The new volume from 0 to 1.

Returns: N/A

Description

With this function you can change the volume of the given sound. This will change the volume for all further instances where the indexed sound is played and the volume can be set to a value between 0 (silent) and 1 (full volume), with a value of 1 being the default volume for the sound unless it has been previously changed in the sound resource. The volume scale is logarithmic in nature, so a volume of 0.5 is not half volume, as illustrated by the image below:

Example:

if keyboard_check_pressed(vk_add)
{
if vol < 1 vol += 0.1;
sound_volume(global.Music, vol);
}

The above code checks for a key press and when it detects one it raises the volume (to a maximum of 1) of the sound indexed in the global variable "Music".

Back: Legacy Sound
Next: sound_fade

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Sprites

This section deals with the functions relating to sprite assets.

Sprites are generally the visual representations of objects within the game you are creating, although they can be used for many other purposes. A sprite is either a single image, or a set of images that, when played one after another, looks like a looping animation. Sprites can be created in many formats, with the "traditional" sprite being made up of frames of pixel images, imported into GameMaker: Studio as *.png files. However you can also import vector sprites that have been saved in the *.swf format, or skeletal animation sprites that have been saved out as *.json files with accompanying *.atlas and *.png files.

Since sprites are an integral part of any game, GameMaker: Studio has a large number of functions that can be used for getting information about specific sprites, or for changing those that are in your game, or even for loading into an application your own sprites from a source image file.

Sprite Information

The following functions can be used to get information about a sprite asset. Please note that these functions get the information from the base sprite (ie. the sprite asset) and not from the sprite as it is being used in an instance. For example, you can use instance variable sprite_width to get the width of the sprite that an instance is using and this width will take into account any scaling that may have been applied. However, if you need to know the width of a sprite as it would be normally, with no transforms applied, you would need to use the sprite_get_width() function below. For more information on the sprite instance variables see the section on Instance Properties.

  1. sprite_get_name
  2. sprite_get_number
  3. sprite_get_width
  4. sprite_get_height
  5. sprite_get_xoffset
  6. sprite_get_yoffset
  7. sprite_get_bbox_bottom
  8. sprite_get_bbox_left
  9. sprite_get_bbox_right
  10. sprite_get_bbox_top
  11. sprite_get_tpe
  12. sprite_get_texture
  13. sprite_get_uvs

Sprite Manipulation

The functions below are all related to changing the sprite asset (resource) itself. This means that the majority of these functions will affect all instances that reference the sprite being changed, it also means that you must take great care to ensure that a sprite exists before referencing it, or to make sure it is not being referenced before changing it.

  1. sprite_exists
  2. sprite_add
  3. sprite_replace
  4. sprite_duplicate
  5. sprite_assign
  6. sprite_merge
  7. sprite_create_from_surface
  8. sprite_add_from_surface
  9. sprite_collision_mask
  10. sprite_set_offset
  11. sprite_delete
  12. sprite_set_alpha_from_sprite
  13. sprite_set_cache_size
  14. sprite_set_cache_size_ext
  15. sprite_save
  16. sprite_save_strip
  17. sprite_flush
  18. sprite_flush_multi
  19. sprite_prefetch
  20. sprite_prefetch_multi

Skeletal Animation

Due to the nature of sprites made using skeletal animation, they also require a sub-set of functions for manipulating the drawn sprite in your games. These functions can be found in the following section of the manual:

  • Skeletal Animations

    • Back: Game Assets


sprite_add

Adds an image from a file to the set of sprite assets.

Syntax:

sprite_add(fname, imgnumb, removeback, smooth, xorig, yorig);

Argument | Description
fname | The name (a string file path) of the file to add.
imgnum | Use to indicate the number of sub-images (1 for a single image). For gif images, this argument is not used and can be set to 0.
removeback | Indicates whether to make all pixels with the background colour (left-bottom pixel) transparent.
smooth | Indicates whether to smooth the edges if transparent.
xorig | Indicate the x position of the origin in the sprite.
yorig | Indicate the y position of the origin in the sprite.

Returns: Real

Description

With this function you can add an image as a sprite, loading it from an external source where the image file to be loaded should always be in either *.png, *.gif or *.jpg/jpeg format. The function returns the new sprite index which must then be used in all further codes that relate to the sprite. If you use this function with HTML5 or are getting an image from an URL, this function will also generate an asynchronous event. See Advanced Use - More About Async Events for more information.

All images that are to be turned into animated sprites - except for *.gif (see below) - should have a "strip" format (see the image below) and it will be split into the number of sub-images specified following the rule sprite width = strip width / sub images. As you can see in the above image, the sprite has been placed on a dark purple background, and this can be removed by setting the "removeback" argument to true. This works by checking the bottom left pixel of the sprite for the colour there and then uses that as the colour to be removed. For example, in the above image, if we had the bottom left pixel colour as green, all the green parts of the sprite would have been removed and the rest of the purple background ignored.

If you choose the "removeback" option, you may also want GameMaker: Studio to smooth the edges of the sprite by setting the "smooth" argument to true. All this does is create a semi-transparent border around the edges of the sprite after it has had its background removed.

Finally you can also specify the x and y origin for the sprite. This is the point where the sprite is "fixed" onto the instance that uses it, and is always calculated as relative to the 0,0 top left corner of one sprite sub-image. So, for example, a sprite that is 32 x 32 pixels with these values set to (16,16) will have its origin in the center.

If you are adding a *.gif format image, then you only need to specify the filename and can leave all the other arguments as 0, but note that only the first image of the GIF will be loaded.

By default all new sprites have their bounding boxes calculated automatically (the exact bbox will depend on the size and transparency of the sprite), however you may wish to customise this, in which case you should also use the function sprite_collision_mask.

NOTE: When you load a sprite into GameMaker: Studio you must remember to remove it again (with sprite_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

spr = sprite_add("player_5.png", 16, true, true, 0, 0);

The above code loads a sprite into the game and stores its index in the variable "spr".

Back: Sprites
Next: sprite_replace

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_add_from_surface

Adds an area of a surface as a next subimage to a sprite.

Syntax:

sprite_add_from_surface(index, surface, x, y, w, h, removeback, smooth);

Argument | Description
index | The index of the sprite to add the new image to.
surface | The index of the surface from which the get the image.
x | The x position to copy from.
y | The y position to copy from.
w | The width of the area to be copied (from the x position).
h | The height of the area to be copied (from the y position).
removeback | Indicates whether to make all pixels with the background colour (left-bottom pixel) transparent.
smooth | Indicates whether to smooth the edges.

Returns: N/A

Description

This function works in exactly the same way as sprite_create_from_surface only instead of creating a new sprite from the area of the indexed surface that you select, it adds the defined area of the surface as a new sub-image to a previously created sprite.

Example:

spr_custom = sprite_create_from_surface(surf, 0, 0, 32, 32, true, true, 16, 16);
var i;
for (i = 1; i < 8; i +=1)
{
sprite_add_from_surface(spr_Custom, surf, i, 0, 32, 32, true, true, 16, 16);
}

The above code creates a sprite from the surface indexed in the variable "surf", assigning its index to the variable "spr_Custom", and then uses a for loop to move across the surface and capture various sections which are added into the sprite as sub-images.

Back: Sprites
Next: sprite_collision_mask

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_assign

Assigns one sprite to another sprite index.

Syntax:

sprite_assign(index, sprite);

Argument | Description
index | The index of the sprite to be copied to (ie: overwritten).
sprite | The sprite to be copied from.

Returns: N/A

Description

This function takes two previously created (or included) sprite indexes, and copies the image from one to the other. In this way you can copy (or "clone") one sprite into another index. Note that you cannot copy to a game resource. You have to have created the sprite to be copied to previously using the sprite_add or sprite_duplicate functions.

Example:

if sprite_exists(global.Player_Sprite)
{
var t_spr = sprite_add("player.png", 16, true, true, 0, 0);
sprite_assign(global.Player_Sprite, t_spr);
sprite_delete(t_spr);
}
else
{
global.Player_Sprite = sprite_add("player.png", 16, true, true, 0, 0);
}

The above code checks to see if the global variable "Player_Sprite" contains a sprite and if it does it uses sprite_assign to change it for one that has been loaded from an external file. If it does not contain a sprite one is loaded and its index is stored in that variable.

Back: Sprites
Next: sprite_merge

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_collision_mask

Defines a collision mask for the given sprite.

Syntax:

sprite_collision_mask(ind, sepmasks, bboxmode, bbleft, bbtop, bbright, bbbottom, kind, tolerance);

Argument | Description
ind | The index of the sprite to set the bounding box of.
sepmasks | Whether to create collision masks for each sub-image of the sprite (true), or one mask for all (false).
bboxmode | What kind of bounding box to use. 0=automatic, 1=full image, 2=user defined.
bbleft | The maximum left position of the bounding box.
bbtop | The maximum top position of the bounding box.
bbright | The maximum right position of the bounding box.
bbbottom | The maximum bottom position of the bounding box.
kind | The kind of mask (0=precise, 1=bounding box, 2=disk, 3=diamond).
tolerance | Indicates the tolerance in the transparency value (0=no tolerance, 255=full tolerance).

Returns: N/A

Description

With this function you can set the type of collision mask that a sprite should have. If you select either automatic, or precise, then the bounding box values can be set to 0, however for a user defined mask you will have to set these values.

The bounding box is always a relative value, based on the (0,0) position being the top left corner of the sprite (irrespective of the x and y origin).

The kind of mask sets the general shape for the mask itself, although if you have a user defined bounding box, you may end up with a "cut off" mask that is not complete.

Finally, tolerance is used to define how precise the precise mask is, with a tolerance of 0 meaning that the mask will follow every single pixel that has a transparency over 0, while other values will shift the collision mask perimeter depending on the transparency of the pixels.

NOTE: This function is only useful for bitmap sprites and will not work with SWF or JSON (Spine) sprites.

NOTE: This function will only work on duplicated sprites and not directly on pre-made resources. you can duplicate sprites using the function sprite_duplicate.

Example:

spr = sprite_add("player_5.png", 16, true, true, 0, 0);
sprite_collision_mask(spr, true, 1, 0, 0, 0, 0, 0, 0);

The above code loads a sprite from an external source and stores the new index in the variable "spr". The code then sets the new sprite to have a precise collision mask for each of its sub-images.

Back: Sprites
Next: sprite_set_offset

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_create_from_surface

Creates a sprite by copying an area from a surface.

Syntax:

sprite_create_from_surface(index, x, y, w, h, removeback, smooth, xorig, yorig);

Argument | Description
index | The index of the surface to create from.
x | The x position to copy from.
y | The y position to copy from.
w | The width of the area to be copied (from the x position).
h | The height of the area to be copied (from the y position).
removeback | Indicates whether to make all pixels with the background colour (left-bottom pixel) transparent.
smooth | Indicates whether to smooth the edges.
xorig | Indicates the x position of the origin in the sprite.
yorig | Indicates the y position of the origin in the sprite.

Returns: Real

Description

With this function you can create a sprite from a previously initialised surface. The x and y coordinates that you input are relative to the (0,0) position of the surface (the top left corner) and not the game window, nor the view if you have one active. The width and height arguments are in pixels and define the width and height of the part of the surface to use.

Setting the "removeback" argument to true will remove a colour from the sprite, by checking the bottom left pixel of the sprite for the colour there and then using that as the colour to be removed.

If you choose the "removeback" option, you may also want GameMaker: Studio to smooth the edges of the sprite by setting the "smooth" argument to true. All this does is create a semi-transparent border around the edges of the sprite after it has had its background removed.

Finally you can also specify the x and y origin for the sprite. This is the point where the sprite is "fixed" onto the instance that uses it, and is always calculated as relative to the 0,0 top left corner of one sprite sub-image. So, for example, a sprite that is 32 x 32 pixels with these values set to (16,16) will have its origin in the center.

By default all new sprites have their bounding boxes calculated automatically (the exact bbox will depend on the size and transparency of the sprite), however you may wish to customise this, in which case you should also use the function sprite_collision_mask.

NOTE: When you create a sprite in GameMaker: Studio with this method you must remember to remove it again (with sprite_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

var surf;
surf = surface_create(32, 32);
surface_set_target(surf);
draw_clear_alpha(c_black, 0);
draw_sprite(spr_Body, 0, 0, 0);
draw_sprite(spr_Clothes, 0, 0, 0);
draw_sprite(spr_Hair, 0, 0, 0);
spr_custom = sprite_create_from_surface(surf, 0, 0, 32, 32, true, true, 16, 16);
surface_reset_target();
surface_free(surf);

The above code creates a surface and stores its index in the local variable "surf". It then targets that surface, clears it and draws several sprites on top of each other. Finally it creates a new sprite from the composite image drawn on the surface and assigns its index to "spr_Custom" before freeing up the memory used by the surface.

Back: Sprites
Next: sprite_add_from_surface

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_delete

Deletes the sprite from memory, freeing the memory used.

Syntax:

sprite_delete(index);

Argument | Description
index | The index of the sprite to be deleted.

Returns: N/A

Description

This function will delete a sprite from the game, freeing any memory that was reserved for it. This is a permanent removal, and if the asset that you delete was included as part of the game's resources, not even restarting the game (unless you close the application first) will recover it. This is a very important function for those moments when you need to create and change sprites from external resources and should always be used to remove those assets that are no longer needed by a game, or to clear an indexed asset from a variable before re-assigning another asset to that variable.

Example:

var spr = sprite_create_from_surface(application_surface, 0, 0, 32, 32, false, false, 16, 16);
sprite_merge(spr_Player, spr);
sprite_delete(spr);

The above code creates a local variable and then stores the index of the sprite created from the application surface. This sprite is then merged with the asset indexed in the variable "spr_Player" before being removed from memory again.

Back: Sprites
Next: sprite_set_alpha_from_sprite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_duplicate

Creates a duplicate of the sprite with the given index.

Syntax:

sprite_duplicate(index);

Argument | Description
index | The index of the sprite to duplicate.

Returns: Real

Description

This function will return the index of a newly created sprite that is a duplicate (copy) of the one input as the "index" argument. If the function fails, -1 is returned. This function must be used to copy any sprites from the original assets before any transformations can be done on them. For example, if you wish to change the bounding box for a sprite, or set its alpha from another sprite, you must first duplicate it, then perform the operation on the duplicated sprite and use that.

NOTE: When you duplicate a sprite in GameMaker: Studio you must remember to remove it again (with sprite_delete) when no longer needed, otherwise there is risk of a memory leak which will slow down and eventually crash your game.

Example:

new_spr = sprite_duplicate(sprite_index)

The above code duplicates the sprite currently being used as the sprite index of the instance and stores the index for this new sprite in the variable "new_spr".

Back: Sprites
Next: sprite_assign

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_exists

Determines whether a sprite exists or not.

Syntax:

sprite_exists(index);

Argument | Description
index | The index of the sprite to check.

Returns: N/A

Description

This function returns whether a sprite with the specified index exists or not. Please note, that the value used for checking must have been initialised previously or else you will get an error causing GameMaker: Studio to close.

Example:

if sprite_exists(spr_array[0])
{
sprite_index = spr_array[0];
}
else
{
sprite_index = spr_BaseSprite;
}

The above code checks an array to see if it contains a valid sprite index and if so it assigns that sprite to the instance, but if not, it assigns a sprite from the included resources.

Back: Sprites
Next: sprite_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_flush

Flush a sprite asset (and the texture page it's on) from memory.

Syntax:

sprite_flush(ind);

Argument | Description
ind | The index (resource name) of the sprite asset to flush

Returns: N/A

Description

With this function you can remove the given sprite texture - and the texture page it is on - from video memory (the texture page will be reloaded on next use). You supply the sprite index (as defined when creating the sprite resource) and it will be removed from the texture memory. It is worth noting that by default on the Windows platforms (YYC and standard) all textures will always be loaded into memory on start-up. If you are making a cross platform game, then you can leave this function in your code for the Windows target as it will not give any error and just not do anything. However you can also force the Windows target to not load any textures on startup and so use the flush and prefetch functions as you would on all other platforms (the setting can be found in the Windows Global Game Settings window).

NOTE: There is a performance hit as the texture is uploaded to texture memory on most devices, so you can call sprite_prefetch on any required graphics at the start of a level to avoid any stalls.

Example:

sprite_flush(spr_Player_Aura);

The above code flushes the sprite "spr_Player_Aura" from memory.

Back: Sprites
Next: sprite_flush_multi
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_flush_multi

Flush multiple sprite assets (and their assigned texture pages) from memory.

Syntax:

sprite_flush(array);

Argument | Description
array | Array with the sprite indices to flush

Returns: N/A

Description

With this function you can remove any number of sprite textures - and the texture pages they are assigned to - from video memory (their texture pages will be reloaded on next use of any sprite from them). You supply an array of sprite asset indices and they will be removed from memory when the function is called. It is worth noting that by default on the Windows platforms (YYC and standard) all textures will always be loaded into memory on start-up. If you are making a cross platform game, then you can leave this function in your code for the Windows target as it will not give any error and just not do anything. However you can also force the Windows target to not load any textures on startup and so use the flush and prefetch functions as you would on all other platforms (the setting can be found in the Windows Global Game Settings window).

Example:

spr_a[0] = spr_Player_Aura1;
spr_a[1] = spr_Player_Aura2;
spr_a[2] = spr_Player_Aura3;
spr_a[3] = spr_Player_Aura4;
sprite_flush_multi(spr_a);

The above code creates an array where each element holds a sprite index. This array is then used to clear those sprite textures from memory.

Back: Sprites
Next: sprite_prefetch
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_bbox_bottom

Returns the relative position of the bottom of the bounding box of the given sprite.

Syntax:

sprite_get_bbox_bottom(ind);

Argument | Description
ind | The index of the sprite to check.

Returns: Real

Description

This function returns the relative position of the bottom of the sprite bounding box. This value is given as a relative value based on the upper left corner of the base sprite asset being (0,0). it is the same value as can be found in the sprite editor for the collision mask properties. The image below shows how it is calculated:

Example:

var ww, hh;
ww = sprite_get_bbox_left(sprite_index) - sprite_get_bbox_right(sprite_index);
hh = sprite_get_bbox_bottom(sprite_index) - sprite_get_bbox_top(sprite_index);

The above code calculates the width and height of the collision mask based on the relative bounding box side positions.

Back: Sprites
Next: sprite_get_bbox_left

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_bbox_left

Returns the relative position of the left of the bounding box of the given sprite.

Syntax:

sprite_get_bbox_left(ind);

Argument | Description
ind | The index of the sprite to check.

Returns: Real

Description

This function returns the relative position of the left of the sprite bounding box. This value is given as a relative value based on the upper left corner of the base sprite asset being (0,0). it is the same value as can be found in the sprite editor for the collision mask properties. The image below shows how it is calculated:

Example:

var ww, hh;
ww = sprite_get_bbox_left(sprite_index) - sprite_get_bbox_right(sprite_index);
hh = sprite_get_bbox_bottom(sprite_index) - sprite_get_bbox_top(sprite_index);

The above code calculates the width and height of the collision mask based on the relative bounding box side positions.

Back: Sprites
Next: sprite_get_bbox_right

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_bbox_right

Returns the relative position of the right of the bounding box of the given sprite.

Syntax:

sprite_get_bbox_right(ind);

Argument | Description
ind | The index of the sprite to check.

Returns: Real

Description

This function returns the relative position of the right of the sprite bounding box. This value is given as a relative value based on the upper left corner of the base sprite asset being (0,0). it is the same value as can be found in the sprite editor for the collision mask properties. The image below shows how it is calculated:

Example:

var ww, hh;
ww = sprite_get_bbox_left(sprite_index) - sprite_get_bbox_right(sprite_index);
hh = sprite_get_bbox_bottom(sprite_index) - sprite_get_bbox_top(sprite_index);

The above code calculates the width and height of the collision mask based on the relative bounding box side positions.

Back: Sprites
Next: sprite_get_bbox_top

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_bbox_top

Returns the relative position of the top of the bounding box of the given sprite.

Syntax:

sprite_get_bbox_top(ind);

Argument | Description
ind | The index of the sprite to check.

Returns: Real

Description

This function returns the relative position of the top of the sprite bounding box. This value is given as a relative value based on the upper left corner of the base sprite asset being (0,0). it is the same value as can be found in the sprite editor for the collision mask properties. The image below shows how it is calculated:

Example:

var ww, hh;
ww = sprite_get_bbox_left(sprite_index) - sprite_get_bbox_right(sprite_index);
hh = sprite_get_bbox_bottom(sprite_index) - sprite_get_bbox_top(sprite_index);

The above code calculates the width and height of the collision mask based on the relative bounding box side positions.

Back: Sprites
Next: sprite_get_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_height

Finds the height of a sprite.

Syntax:

sprite_get_height(index);

Argument | Description
index | The index of the sprite to find the height of.

Returns: Real

Description

With this function you can find the height of the base resource sprite, with no transforms, in pixels.

Example:

if sprite_height != sprite_get_height(sprite_index)
{
image_yscale = 1;
}

The above code checks the height of the sprite as it is in the current instance and if there is a difference between that and the original base sprite, it resets the y axis scale.

Back: Sprites
Next: sprite_get_xoffset

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_name

Gets the name of a sprite.

Syntax:

sprite_get_name(index);

Argument | Description
index | The index of the sprite to get the name of.

Returns: String

Description

This function will return the name as a string of the specified sprite. This name is the one that has been specified for the sprite in the resource tree of the main GameMaker: Studio window. Please note that this is only a string and cannot be used to reference the sprite directly - for that you would need the sprite index. You can, however, use this string to get the sprite index using the returned string along with the function asset_get_index().

Example:

str = sprite_get_name(sprite_index);

The above code will get the name of the sprite index for the instance running the code and store the return value in the variable "str".

Back: Sprites
Next: sprite_get_number

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_number

Returns the number of sub-images in a sprite.

Syntax:

sprite_get_number(index);

Argument | Description
index | The index of the sprite.

Returns: Real

Description

A sprite has to have at least one sub-image and this function will return just how many it has. Remember, a sprite sub-image starts being numbered from 0, so if this function returns 3 (the sprite being checked has 3 sub-images) they will be numbered 0, 1 and 2.

Example:

image_index = floor(random(sprite_get_number(sprite_index)));

The above code will set the image index to a random frame based on the number of sub-images that the sprite has.

Back: Sprites
Next: sprite_get_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_texture

Returns the texture id for the given sprite and sub-image.

Syntax:

sprite_get_texture(spr, subimg);

Argument | Description
spr | The index of the sprite to use.
subimg | The sub-image of the sprite to use.

Returns: pointer

Description

This function returns a special pointer for the sprite texture page. This value can then be used in other draw functions, particularly in general 3D and some of the 2D primitive functions, as well as the Shader functions. You can get more information about the returned texture page using the different texture_ functions found here.

Example:

var tex;
tex = sprite_get_texture(spr_Wall, 0);
draw_primitive_begin_texture(pr_trianglestrip, tex);
draw_vertex_texture(0, 0, 0, 0);
draw_vertex_texture(480, 0, 1, 0);
draw_vertex_texture(480, 640, 1, 1);
draw_vertex_texture(0, 640, 0, 1);
draw_primitive_end();

The above code will draw a 4 vertex triangle strip textured with the texture held in the "tex" variable.

Back: Sprites
Next: sprite_get_uvs

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_tpe

Returns a value for the texture page entry of the sprite.

Syntax:

sprite_get_tpe(sprite, index);

Argument | Description
sprite | The index of the sprite to find the texture page entry of.
index | The image index of the sprite.

Returns: Real

Description

This function will return a special value that relates to the position of the given sprite and sub-image on the texture page used by your game. In this way you can pass the value to extensions for use outside of the compiled game, effectively bypassing the GameMaker: Studio drawing functions and permitting the sprite to be used in DOM content which can then be drawn anywhere within the window that contains the game canvas. This function is of particular interest to those that wish to create buttons and other interactive media outside of the GameMaker: Studio canvas element on their host page using the function clickable_add.

NOTE: this function is for HTML5 only.

Example:

home_but = clickable_add(32, 32, sprite_get_tpe(spr_MS_Home, 0), "http://macsweeney_games.com", "_blank", "width=700, height=500, menubar=0, toolbar=0, scrollbars=0");

The above code creates a DOM button at the position (32, 32) of the page that the game canvas is running on. The button uses the sprite referenced from the texture page as "spr_MS_Home" and when clicked the button will open a new window for the specified URL and with the defined properties for that window.

Back: Sprites
Next: sprite_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_uvs

Returns the texture coordinates of the sprite within the texture page as an array.

Syntax:

sprite_get_uvs(sprite, subimage);

Argument | Description
sprite | The index of the sprite to use.
subimage | The sub-image of the sprite to use.

Returns: Array

Description

This function returns an array with the UV coordinates and other data for the texture of the sprite sub-image on the texture page. The function returns an array with the following 8 elements:

  • [0] = left
  • [1] = top
  • [2] = right
  • [3] = bottom
  • [4] = amount of pixels the asset compiler has trimmed from the sprites left side
  • [5] = amount of pixels the asset compiler has trimmed from the sprites top side
  • [6] = normalised percentage of pixel data from the original sprites width that has been saved to the texture page
  • [7] = normalised percentage of pixel data from the original sprites height that has been saved to the texture page

This value can then be used in other draw functions, particularly in general 3D and some of the 2D primitive functions, as well as the Shader functions.

NOTE: This function will not work with vector sprites or skeleton animation sprites.

Example:

var tex = sprite_get_uvs(sprite, 0);
tex_left = tex[0];
tex_top = tex[1];
tex_right = tex[2];
tex_bottom = tex[3];

The above code will store the UV coordinates for the given sprite in a local array and then assign the values to instance variables.

Back: Sprites
Next: sprite_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_width

Finds the width of a sprite.

Syntax:

sprite_get_width(index);

Argument | Description
index | The index of the sprite to find the width of.

Returns: Real

Description

With this function you can find the width of the base resource sprite, with no transforms, in pixels.

Example:

if sprite_width != sprite_get_width(sprite_index)
{
image_xscale = 1;
}

The above code checks the width of the sprite as it is in the current instance and if there is a difference between that and the original base sprite, it resets the x axis scale.

Back: Sprites
Next: sprite_get_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_xoffset

Finds the xoffset of a sprite.

Syntax:

sprite_get_xoffset(index);

Argument | Description
index | The index of the sprite to find the xoffset of.

Returns: Real

Description

When you define a sprite in the sprite editor, you need to set the origin for that sprite. This is the point at which the sprite will be "attached" or "drawn" when used with an instance. This function returns the relative offset for the x-axis of the origin based on the upper left corner being the 0,0 position, with a +x being right and a -x being left of this. The following image illustrates this:

Example:

if x - sprite_get_xoffset(sprite_index) < 0
{
x = sprite_get_xoffset(sprite_index);
}

The above code will ensure that an instance is maintained within the room based on the sprite (so the sprite is always visible).

Back: Sprites
Next: sprite_get_yoffset

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_get_yoffset

Finds the yoffset of a sprite.

Syntax:

sprite_get_yoffset(index);

Argument | Description
index | The index of the sprite to find the yoffset of.

Returns: Real

Description

When you define a sprite in the sprite editor, you need to set the origin for that sprite. This is the point at which the sprite will be "attached" or "drawn" when used with an instance. This function returns the relative offset for the y-axis of the origin based on the upper left corner being the 0,0 position, with a +y being down and a -y being up from this. The following image illustrates this:

Example:

if y - sprite_get_yoffset(sprite_index) < 0
{
y = sprite_get_yoffset(sprite_index);
}

The above code will ensure that an instance is maintained within the room based on the sprite (so the sprite is always visible).

Back: Sprites
Next: sprite_get_bbox_bottom

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_merge

Merges the images from one sprite into another.

Syntax:

sprite_merge(ind1, ind2);

Argument | Description
ind1 | The index of the sprite to merge.
ind2 | The index of the sprite that ind1 is to be merged with.

Returns: N/A

Description

This function will merge the sprite indexed in argument1 ("ind2") with that which is indexed in argument0 ("ind1"). The images themselves are NOT merged together, but rather the image indices are merged, with the sub images from sprite "ind2" appended onto those of sprite "ind1", ie: they are added on at the end. Note that if the sprites are different sizes, then the appended sprites are stretched to fit the image size for "ind1".
This change is permanent, and from the moment you use this function until the game is closed or the sprite deleted, the sprite that is being merged into will be changed, however the sprite that it is being merged with will remain the same.

NOTE: Neither the image asset that is being merged into, nor the image asset that is for merging, can be one of the original game resources. You must use sprite_duplicate first to create two new resources (if you are merging included game assets) and then merge those.

NOTE: This function is only useful for bitmap sprites and will not work with SWF or JSON (Spine) sprites.

Example:

var tspr;
tspr[0] = spr_add(working_directory + "\Sprite Assets\explode1.png", 16, true, true, 0, 0);
tspr[1] = sprite_duplicate(spr_Explosion);
sprite_merge(tspr[0], tspr[1]);
sprite_index = t_spr[0];
sprite_delete(tspr[1]);

The above code loads a sprite into a local variable then merges it with another sprite that has been duplicated. Finally the merged sprite is assigned to the instance sprite_index while the loaded sprite is removed to free the memory it uses. Note that at some point after this operation, like in the Destroy or Room End events, you will also need to use sprite_delete to remove the merged sprite from memory too.

Back: Sprites
Next: sprite_create_from_surface

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_prefetch

Fetch the texture page for a given sprite asset.

Syntax:

sprite_prefetch(ind);

Argument | Description
ind | The sprite index to fetch

Returns: N/A

Description

This function can be used to prefetch (place into texture memory) a texture page with the given sprite. You supply the sprite index as defined when you created the sprite asset, and the texture page it is on will be loaded into memory.

NOTE: There is a performance hit as the texture is uploaded to texture memory on most devices, so it's recommended that you call sprite_prefetch on any required graphics at the start of a level to avoid any stalls.

Example:

sprite_prefetch(spr_Player_Aura);

The above code will place the referenced sprite into texture memory ready for use.

Back: Sprites
Next: sprite_prefetch_multi
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_prefetch_multi

Fetch multiple texture pages for a number of sprite assets.

Syntax:

sprite_prefetch_multi(array);

Argument | Description
array | Array with the sprite indices to fetch

Returns: N/A

Description

This function can be used to prefetch (place into texture memory) a number of texture pages that contain the sprites given. You supply an array populated with the sprite indices (as defined when you created the sprite asset) and the texture pages that they are on will be loaded into memory.

NOTE: There is a performance hit as the texture is uploaded to texture memory on most devices, so it's recommended that you call sprite_preftech_multi on any required graphics at the start of a level to avoid any stalls.

Example:

spr_a[0] = spr_Player_Aura1;
spr_a[1] = spr_Player_Aura2;
spr_a[2] = spr_Player_Aura3;
spr_a[3] = spr_Player_Aura4;
sprite_prefetch_multi(spr_a);

The above code creates an array where each element holds a sprite index. This array is then used to place those sprite textures into memory.

Back: Sprites
Next: sprite_exists
© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_replace

Replace a sprite resource with an external one.

Syntax:

sprite_replace(ind, fname, imgnumb, removeback, smooth, xorig, yorig);

Argument | Description
ind | The index of the sprite to permanently replace.
fname | The filename of the image to make the new sprite.
imgnumb | The number of frames the sprite will be cut up into horizontally. 1=one single image.
removeback | Indicates whether to make all pixels with the background colour (left-bottom pixel) transparent.
smooth | Indicates whether to smooth the edges.
xorig | The x coordinate of the origin, relative to the sprite's top left corner.
yorig | The y coordinate of the origin, relative to the sprite's top left corner.

Returns: N/A

Description

This function works in almost the exact same manner as sprite_add, only instead of returning the index of the sprite you are importing, it overwrites a previously created sprite index. You must use a sprite index that has been created and stored in a variable using other functions like sprite_add or sprite_create_from_surface, and not one from the resource tree as you cannot replace built-in assets.

The image file to be loaded should always be in *.png format and all images that are to be turned into animated sprites should have a "strip" format (see the image below). They will be split into the number of sub-images specified following the rule sprite width = strip width / sub images. As you can see in the above image, the sprite has been placed on a dark purple background, and this can be removed by setting the "removeback" argument to true. This works by checking the bottom left pixel of the sprite for the colour there and then uses that as the colour to be removed. For example, in the above image, if we had the bottom left pixel colour as green, all the green parts of the sprite would have been removed and the rest of the purple background ignored.

If you choose the "removeback" option, you may also want GameMaker: Studio to smooth the edges of the sprite by setting the "smooth" argument to true. All this does is create a semi-transparent border around the edges of the sprite after it has had its background removed.

Finally you can also specify the x and y origin for the sprite. This is the point where the sprite is "fixed" onto the instance that uses it, and is always calculated as relative to the 0,0 top left corner of one sprite sub-image. So, for example, a sprite that is 32 x 32 pixels with these values set to (16,16) will have its origin in the center.

By default all new sprites have their bounding boxes calculated automatically (the exact bbox will depend on the size and transparency of the sprite), however you may wish to customise this, in which case you should also use the function sprite_collision_mask.

NOTE: Depending on the target platform that is chosen you are limited as to where you can save and load files from. See Reference - Files for more information.

NOTE: You should be aware that if you are using this function in your HTML5 target game to load resources from an external server, then, due to XSS protection in browsers, attempts to load resources from across domains can be blocked and may appear to return blank results.

Example:

sprite_replace(spr_banner, "gravemaker.png", 1, false, false, 0, 0);

The above code will replace the image asset indexed in "spr_banner" with another one loaded from an external source.

Back: Sprites
Next: sprite_duplicate

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_save

Save a sprite to disc.

Syntax:

sprite_save(ind, subimg, fname);

Argument | Description
ind | The index of the sprite to save.
subimg | The sub-image of the sprite to save.
fname | The filename for the saved sprite.

Returns: N/A

Description

This function can be used to save any sub-image of any sprite to disc, giving it the specified filename. This image must be a *.png file.

NOTE: Depending on the target platform that is chosen you are limited as to where you can save and load files from. See Reference - Files for more information.

Example:

var surf, spr_custom;
surf = surface_create(32, 32);
surface_set_target(surf);
draw_clear_alpha(c_black, 0);
draw_sprite(spr_Body, 0, 0, 0);
draw_sprite(spr_Clothes, 0, 0, 0);
draw_sprite(spr_Hair, 0, 0, 0);
spr_custom = sprite_create_from_surface(surf, 0, 0, 32, 32, true, true, 16, 16);
surface_reset_target();
surface_free(surf);
sprite_save(spr_custom, 0, "Player_Custom_Sprite.png");
sprite_delete(spr_Custom);

The above code creates a surface and stores its index in the local variable "surf". It then targets that surface, clears it and draws several sprites on top of each other. It creates a new sprite from the composite image drawn on the surface and assigns its index to the local variable "spr_Custom" before freeing up the memory used by the surface. Finally, the resulting sprite is saved to a file and then removed from memory too.

Back: Sprites
Next: sprite_save_strip

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_save_strip

Saves a sprite to disc as a strip image.

Syntax:

sprite_save_strip(ind, filename);

Argument | Description
ind | The index of the sprite to change the transparency map of.
filename | The filename for the saved sprite strip.

Returns: N/A

Description

This function will create a strip image of all sub-images from a sprite. You can specify the name of the file to be saved, but the actual file type must be *.png.

NOTE: Depending on the target platform that is chosen you are limited as to where you can save and load files from. See Reference - Files for more information.

Example:

var spr, i;
spr = sprite_create_from_surface(0, 0, 32, 32, true, true, 16, 16);
for (i = 1; i < 8; i +=1)
{
sprite_add_from_surface(spr, i, 0, 32, 32, true, true, 16, 16);
}
sprite_save_strip(spr, "Custom_Player_Sprite.png");
sprite_delete(spr);

The above code creates a sprite from the surface indexed in the variable "surf", assigning its index to the local variable "spr_Custom", and then uses a for loop to move across the surface and capture various sections which are added into the sprite as sub-images. this new sprite is then saved as a png strip before being removed from memory.

Back: Sprites
Next: sprite_flush

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_set_alpha_from_sprite

Changes the alpha (transparency) of one given sprite based on the intensity/value map of another.

Syntax:

sprite_set_alpha_from_sprite(ind, spr);

Argument | Description
ind | The index of the sprite to change the transparency map of.
spr | The index of the sprite to take the transparency map data from.

Returns: N/A

Description

This function uses the value/saturation of one sprite and multiplies it with the alpha of the target sprite. Ideally the sprite being used to generate the new alpha map should be greyscale, with the white areas having an equivalent alpha value of 1 (opaque), the black areas being equivalent to alpha 0 (transparent), and the grey areas being an alpha in between 0 and 1. The sprite that you are setting the alpha of cannot be a permanent resource, nor can the sprite you use to set the alpha, as this will give an error. This means that you must create two completely new sprites "on the fly" in some way for the function to work correctly. This can be achieved by using surfaces, or by creating a sprite from the screen (the code example below shows how the effect can be achieved with surfaces).

NOTE: This function is only useful for bitmap sprites and will not work with SWF or JSON (Spine) sprites.

Below is an image that illustrates how this function works:

Extended Example:

In this extended example we show how you can create a special effect sprite from two sprite resources. To start with we need to have a controller variable in the Create Event of the instance. This variable is to ensure that the sprite is only created once:

spr_create = true;

Once that is done we need to then go to the Draw Event and add in this code:

if spr_create
{
spr_create = false;
var surf, spr;
surf = surface_create(sprite_get_width(spr_Explosion_Alpha), sprite_get_height(spr_Explosion_Alpha));
surface_set_target(surf);
draw_clear_alpha(c_black, 0);
draw_sprite(spr_Gradient, 0, 0, 0);
sprite_index = sprite_create_from_surface(surf, 0, 0, sprite_width, sprite_height, false, false, sprite_get_xoffset(spr_Gradient), sprite_get_xoffset(spr_Gradient));
draw_clear_alpha(c_black, 0);
draw_sprite(spr_Explosion_Alpha, 0, sprite_get_xoffset(spr_Gradient), sprite_get_xoffset(spr_Gradient));
spr = sprite_create_from_surface(surf, 0, 0, sprite_width, sprite_height, false, false, sprite_get_xoffset(spr_Gradient), sprite_get_xoffset(spr_Gradient));
surface_reset_target();
surface_free(surf);
sprite_set_alpha_from_sprite(sprite_index, spr);
sprite_delete(spr);
}
draw_sprite(sprite_index, 0, x, y);

The above code first checks to see if the control variable is true or not, and if it is, it then runs the code to set the sprite alpha, setting the variable to false to prevent the code from running more than once. In this case, it creates a surface the size of the alpha mask that we wish to use, then draws the sprite that is to have its alpha changed onto the surface and creates a new sprite from it, assigning it as the sprite_index of the object. The code then clears the surface and draws the alpha map sprite to it and creates another new sprite, storing its index in a local variable. Finally, the new sprite assigned to the object gets its alpha set from this temporary sprite, the surface is freed and the temporary sprite is removed.

There is one final thing to do here, and that is remove the sprite that has been created for the object from memory when not in use. This would either be done in the Destroy Event or the Room End Event like this:

sprite_delete(sprite_index);

Back: Sprites
Next: sprite_set_cache_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_set_cache_size

Sets the size of the cache for a given sprite.

Syntax:

sprite_set_cache_size(ind, max);

Argument | Description
ind | The index of the sprite to change the cache size of.
max | The maximum number of cached copies of the sprite that can be stored.

Returns: N/A

Description

When performing image blending, HTML5 cannot do it dynamically in the same way an executable could be performed. Therefore GameMaker: Studio has to temporarily save a blended copy of the image and load it in. This function sets how many blended copies of the given sprite can be cached before old ones are overwritten. Default is 4. This is applied to all subimages of the sprite.

Example:

sprite_set_cache_size(sprite0, 2);

This will set the sprite cache of all subimages of sprite0 to 2 copies.

Back: Sprites
Next: sprite_set_cache_size_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_set_cache_size_ext

Sets the size of the cache for a given sub-image of a sprite.

Syntax:

sprite_set_cache_size_ext(ind, index, max);

Argument | Description
ind | The index of the sprite to change the cache size of.
index | The subimage of ind to change the cache size of.
max | The maximum number of cached copies of the sprite that can be stored.

Returns: N/A

Description

When performing image blending, HTML5 cannot do it dynamically in the same way an executable could be performed. Therefore GameMaker: Studio has to temporarily save a blended copy of the image and load it in. This function sets how many blended copies of the given sprite can be cached before old ones are overwritten. Default is 4. This is applied to one single given subimage of the sprite.

Example:

sprite_set_cache_size_ext(sprite0, 0, 2);

This will set the sprite cache of the first subimage of sprite0 to 2 copies.

Back: Sprites
Next: sprite_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_set_offset

Change the x and y offset (origin) of the given sprite asset.

Syntax:

sprite_set_offset(ind, xoff, yoff);

Argument | Description
ind | The index of the sprite to change the offset of.
xoff | The x position of the origin.
yoff | The y position of the origin.

Returns: N/A

Description

This function can be used to set the x and y origin of a sprite, and takes relative values based on the (0,0) position being the upper left corner of the sprite. The following image illustrates this:

NOTE: This function affects the sprite resource so that all further instances with this sprite will have the same offset.

Example:

sprite_assign(spr_Custom, spr_Base);
sprite_set_offset(spr_Custom, sprite_get_xoffset(spr_Base), sprite_get_yoffset(spr_Base));

The above code assigns the sprite indexed in "spr_Base" to the sprite indexed in "spr_Custom" and then uses the x and y offset values of "spr_Base" to set the new sprite's origin.

Back: Sprites
Next: sprite_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Skeletal Animations

This section deals with the functions relating to sprite assets.

The functions found in this section are only for use with sprites that have been imported from a skeletal animation file (like the JSON files that Spine exports) and can be used to get information about an animation asset in your game, as well as for setting certain properties within an animation. These functions can to be used along with the regular sprite functions and variables, permitting you to (for example) mix two skeleton animations using these special functions while setting the image scale using the normal sprite instance variables. For more information on the sprite instance variables see the section on Instance Properties.

NOTE: For further information on importing skeletal animation sprites made with Spine, please see the section Importing Skeletal Animations.
IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

The functions available are:

  1. skeleton_animation_get
  2. skeleton_animation_set
  3. skeleton_animation_get_ext
  4. skeleton_animation_set_ext
  5. skeleton_animation_get_duration
  6. skeleton_animation_mix
  7. skeleton_animation_list
  8. skeleton_animation_clear
  9. skeleton_animation_get_frames
  10. skeleton_animation_get_frame
  11. skeleton_animation_set_frame
  12. skeleton_get_minmax
  13. skeleton_get_num_bounds
  14. skeleton_get_bounds
  15. skeleton_skin_get
  16. skeleton_skin_set
  17. skeleton_skin_list
  18. skeleton_attachment_get
  19. skeleton_attachment_set
  20. skeleton_attachment_create
  21. skeleton_bone_data_get
  22. skeleton_bone_data_set
  23. skeleton_bone_state_get
  24. skeleton_bone_state_set
  25. skeleton_slot_data
  26. skeleton_collision_draw_set

You can also use various draw routines designed specifically for these types of sprite (apart from the regular draw_sprite() functions). These functions give you more control over what is being drawn and permit you to change animation specific features, such as timing and skins:

  1. draw_skeleton
  2. draw_skeleton_collision
  3. draw_skeleton_time

Back: Sprites

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_clear

Clear the given animation track.

Syntax:

skeleton_animation_clear(track);

Argument | Description
track | The animation track to clear.

Returns: N/A

Description

This function will clear the specified animation track of all animations, ready to be re-assigned.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if mouse_check_button(mb_right)
{
skeleton_animation_clear(1);
}

The above code will clear the animation track 1 if the right mouse button is pressed.

Back: Skeletal Animations
Next: skeleton_animation_get_frames

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_get

Get the animation set being used currently.

Syntax:

skeleton_animation_get();

Returns: String

Description

With this function you can get the current animation set being used by your skeletal animation sprite. The return value is a string, which will be the name of the set as you defined it in your skeletal animation program.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if keyboard_check_pressed(vk_space)
{
if skeleton_animation_get() != "jump"
{
skeleton_animation_set("jump");
}
}

The above code will change the animation set being used to the "jump" set when the space key is pressed, but only if the current set being used is not already "jump".

Back: Skeletal Animations
Next: skeleton_animation_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_get_duration

Get the time, in seconds, that a given animation set requires to play.

Syntax:

skeleton_animation_get_duration(animname);

Argument | Description
animname | The name (a string) of the animation set to use.

Returns: Real

Description

This function will return the time required for the given animation set to run before looping back to the beginning. The return value is in seconds.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example1:

time += delta_time / 1000000;
var duration = skeleton_animation_get_duration(skeleton_animation_get());
var frame = floor((image_number * (mTime / duration)) + 0.5) % image_number;
image_index = frame;
draw_self();

The above code will set the image_index to the correct value for the currently assigned skeletal animation sprite.

Example2:

time += delta_time / 1000000;
var d = skeleton_animation_get_duration("walk");
if time > d time -= d;
draw_skeleton_time(sprite_index, "walk", "skin1", time, x, y, image_xscale, image_yscale, image_angle, c_white);

The above code will draw the given skeletal animation sprite using delta-time to set the frame being drawn.

Back: Skeletal Animations
Next: skeleton_animation_mix

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_get_ext

Get the animation set used by the given track.

Syntax:

skeleton_animation_get_ext(track);

Argument | Description
track | The track number to get the animation set name of.

Returns: String

Description

A single skeletal animation sprite can have various animation sets, and these sets can be assigned different tracks so that you can "mix and match" animation sets. This function will return the name of the animation set currently used by the given track number (as set by the function skeleton_animation_set_ext).

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if skeleton_animation_get_ext(1) != "bodyfight"
{
skeleton_animation_set_ext("bodyfight", 1);
}

The above code will change the animation set being used by track 1 to "bodyfight" if it is not already.

Back: Skeletal Animations
Next: skeleton_animation_set_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_get_frame

Returns the frame number of the animation on the specified track

Syntax:

skeleton_animation_get_frame(track);

Argument | Description
track | The animation track to get the frame of.

Returns: Integer

Description

This function will return the frame number of the animation on the specified animation track. The function will return -1 if no animation is assigned to the specific track given.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var frame = skeleton_animation_get_frame(0);
if frame > 0 && frame < 2
{
var box = skeleton_get_minmax();
var ww = (box[2] - box[0]) / 2;
var hh = (box[3] - box[1]) / 2;
part_particles_create(global.p_sys, box[0] + ww, box[1] + hh, global.Stars, 10);
}

The above code will check the current frame of the animation assigned to track 0 and then burst some particles from a point in the middle of the total bounding box for the sprite.

Back: Skeletal Animations
Next: skeleton_animation_set_frame

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_get_frames

Returns the total number of frames for the specified animation.

Syntax:

skeleton_animation_get_frames(anim_name);

Argument | Description
anim_name | The animation name to get the frames of.

Returns: Integer

Description

This function can be used to retrieve the number of frames that any given skeleton animation has. You supply the skeleton animation name (as a string, as defined in the program used to make the animation, or as returned by using the function skeleton_animation_get, and the function returns the frames that it has as an integer value. The function will return 0 if the specified animation does not exist.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var num = skeleton_animation_get_frames(skeleton_animation_get());
image_index = num -1;
image_speed = 0;

The above code will get the number of frames in the animation and then set the sprite to the last frame and stop animating.

Back: Skeletal Animations
Next: skeleton_animation_get_frame

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_list

Populate a DS list with the names for all animations included in the sprite.

Syntax:

skeleton_animation_list(sprite, list);

Argument | Description
sprite | The sprite index of the Spine skeletal animation to get the list from.
list | The ID of the DS list to populate with the animation names.

Returns: N/A

Description

With this function you can populate a (pre-created) ds_list with all the names of the animations included as part of the skeletal animation sprite. The names will be strings and can then be used in the other animation functions for these types of sprite.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var list = ds_list_create();
skeleton_animation_list(sprite_index, list);
for (var i = 1; i < ds_list_size(list); i++;)
{
skeleton_animation_mix(list[| 0], list[| i], 0.5);
}
ds_list_destroy(list);

The above code creates a ds_list of all the animation names for the sprite being used by the instance. It then loops through these and sets the mix value for all of them with the first animation to 0.5.

Back: Skeletal Animations
Next: skeleton_animation_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_mix

Set the time period used to interpolate from one animation set to another.

Syntax:

skeleton_animation_mix(animfrom, animto, duration);

Argument | Description
animfrom | The name (a string) of the first animation set to interpolate from.
animto | The name (a string) of the second animation set to interpolate to.
duration | The duration of the interpolation (from 0 to 1)

Returns: N/A

Description

You can switch animation sets easily using the skeleton_animation_set function, but this may cause a skip or stutter as one animation is swapped for another. To prevent this, you can set the mix value between two animation sets and the sprite will interpolate between them. normally you would want to do this in the Create Event of the instance with the skeletal animation as it only needs set once, and GameMaker: Studio will interpolate all further changes to the sprite using the animation sets in that instance. Note that the duration value is from 0 to 1, where a value of 0.5 would have a "half and half" interpolation from one set to the other.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

skeleton_animation_set("walk");
skeleton_animation_mix("walk", "jump", 0.2);
skeleton_animation_mix("jump", "walk", 0.4);

The above code would go in the Create Event of an instance with a skeletal animation sprite and sets the animation mix durations for interpolating between the two animations sets "walk" and "jump".

Back: Skeletal Animations
Next: skeleton_animation_list

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_set

Set the currently selected skeletal animation sprite to use the given animation set.

Syntax:

skeleton_animation_set(animname);

Argument | Description
animname | The name (a string) of the animation set to use.

Returns: N/A

Description

Once you have assigned a skeletal animation sprite to your instance, you can then define which animation set it should use at any given time with this function. When you created your sprite (in Spine) you will have defined multiple animations sets for different states and named each of them appropriately. These names are what you will use to tell GameMaker: Studio which animation set to use at any time in your game. For example, if your sprite is for a platform game, then you may have a "jump" set, a "run" set and an "idle" set all contained within the one sprite and you can switch between them in your game using this function.

Note that setting a new animation in this way will reset the image_index to 0, starting the new animation set from the beginning of its animation loop. If this is not the desired behaviour, then you can set a "mix" value using skeleton_animation_mix and when you set a new animation it will be smoothly interpolated with the previous set. You should also make sure to have a keyframe at the beginning of every animation to prevent data from being held-over from previous animations, unless you plan on using separate animation tracks.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if keyboard_check_pressed(vk_space)
{
if skeleton_animation_get() != "jump"
{
skeleton_animation_set("jump");
}
}

The above code will change the animation set being used to the "jump" set when the space key is pressed, but only if the current set being used is not already "jump".

Back: Skeletal Animations
Next: skeleton_animation_get_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_set_ext

Set the currently selected skeletal animation sprite to use multiple animation sets.

Syntax:

skeleton_animation_set_ext(animname, track);

Argument | Description
animname | The name (a string) of the animation set to use.
track | The track for the animation set to use.

Returns: N/A

Description

When you set an animation set for your skeletal animation sprite, it is assigned track 0 internally. However, you can assign further sets to further tracks (1 and above) and in this way have your sprite play two (or more) animations at the same time. Note that the sprite should have been designed in your animation program with this in mind, such that the "base" animation in track 0 only has keyframes for certain bones, while the next tracks have keyframes for the others. For example, if you have a "walk" animation and its keyframes only affect the legs of the sprite, you can then have a set of head animations and arm animations which you can set in tracks 1 and 2 respectively, permitting you to have a base movement and adapt on it in real-time while the game is being played.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if mouse_check_button(mb_left)
{
skeleton_animation_set_ext("bodyfight", 1);
}
else
{
skeleton_animation_set_ext("bodywalk", 1);
}

The above code will change the animation set being used by track 1 to the "bodyfight" set or the "bodywalk" set when the left mouse button is pressed.

Back: Skeletal Animations
Next: skeleton_animation_get_duration

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_animation_set_frame

Sets an animation frame for the given track.

Syntax:

skeleton_animation_set_frame(track, index);

Argument | Description
track | The animation track to set the frame of.
index | The new index for the animation frame.

Returns: N/A

Description

This function will set the animation assigned to the given track to the frame you supply. The frame index should be an real value between 0 and the number of frames for the animation (which you can get using the function skeleton_animation_get_frames). If you supply a value outside of this range, the animation will be looped to make up the difference, for example if the animation has 5 frames and you set the frame to 8, the actual frame shown will be 3.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if global.pause
{
skeleton_animation_set_frame(0, -image_speed);
}

The above code will set the frame index for the animation in track 0 to the negative image speed when the global "pause" variable is true (essentially pausing the animation).

Back: Skeletal Animations
Next: skeleton_get_minmax

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_attachment_create

Set an attachment image for the given slot.

Syntax:

skeleton_attachment_create(name, sprite, ind, xorigin, yorigin, xscale, yscale, rot);

Argument | Description
name | The name (as a string) of the attachment to create.
sprite | The sprite_index to get the attachment image from.
ind | The image_index to get the attachment image from.
xorigin | The x origin for the image being used.
yorigin | The y origin for the image being used.
xscale | The horizontal scaling of the image, as a multiplier: 1 = normal scaling, 0.5 is half etc...
yscale | The vertical scaling of the image, as a multiplier: 1 = normal scaling, 0.5 is half etc...
rot | The rotation of the image. 0=normal, 90=turned 90 degrees counter-clockwise etc.

Returns: 1, -1

Description

When you create you skeletal animation sprite, you can assign attachment slots and attachments to go in them. These are simply images that are apart from the animation but when attached will move along with the bone they are attached to. Normally you would assign these attachments in your animation program (Spine), but with this function you can create your own at run-time using a sprite asset from your game. the function requires that you give the attachment a name (as a string) and then set the sprite_index and image_index to use, as well as the x and y origin (which can be different to that defined by the sprite in the sprite properties), and you can also set any transforms that you wish to be applied to the image when attached. If the attachment was successfully created the function will return 1 and if it was not (you supplied an invalid sprite index, or the base sprite is not a Spine sprite) then it will return -1.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

skeleton_attachment_create("sword", spr_Weapons, 0, 0, 80, 1, 1, 90);
skeleton_attachment_create("knife", spr_Weapons, 1, 0, 45, 1, 1, 90);
skeleton_attachment_create("crossbow", spr_Weapons, 0, 10, 30, 1, 1, 0);
skeleton_attachment_set("slot_leftHand", choose("sword", "knife", "crossbow"));

The above code would check the currently assigned attachment name for the slot named "slot_leftHand" and if an empty string is returned, a new sprite is attached.

Back: Skeletal Animations
Next: skeleton_bone_data_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_attachment_get

Get the current attachment for the given slot.

Syntax:

skeleton_attachment_get(slot);

Argument | Description
slot | The slot name (a string) to get the attachment of.

Returns: String

Description

A skeletal animation sprite may have other sprites added as attachments, with these sprites being added to a named slot (the name is given when you create the attachment slot in your animation program) and they will be drawn along with the animation of the current sprite. With this function you can get the name (as a string) of the attachment for the given slot of the currently assigned sprite. Note that attached sprites are referenced through their name string as assigned in Spine, or when you called skeleton_attachment_create.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if skeleton_attachment_get("slot_leftHand") == ""
{
skeleton_attachment_set("slot_leftHand", choose("sword", "spear", "knife"));
}

The above code would check the currently assigned attachment name for the slot named "slot_leftHand" and if an empty string is returned, a new sprite is attached.

Back: Skeletal Animations
Next: skeleton_attachment_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_attachment_set

Set an attachment image for the given slot.

Syntax:

skeleton_attachment_set(slot, attachment);

Argument | Description
slot | The slot name (a string) to get the attachment of.
attachment | The name (as a string or a sprite_index) of the attachment image.

Returns: String

Description

A skeletal animation sprite may have other images added as attachments, with these images being added to a named slot (the name is given when you create the attachment slot in your animation program) and they will be drawn along with the animation of the current sprite. With this function you can set an attachment to a given slot, where you are required to give the names (as strings) of the slot and the attachment. These names are defined by the animation program used, or (in the case of the attachment) when you call skeleton_attachment_create.

Note that you can also pass a sprite_index in as the attachment, and that sprite will be used, or you can use -1 to remove the attachment from the slot. When you pass a sprite index in as an argument, it will create an attachment slot using the name of the sprite as the string to name the slot (so using spr_sword, for example, will create an attachment slot "spr_sword"), and the slot will use the first image index (0) of the the sprite, as well as its x and y origin offset, with a scale of (1,1) and a rotation of 0.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if skeleton_attachment_get("slot_leftHand") == ""
{
skeleton_attachment_set("slot_leftHand", choose("sword", "spear", "knife"));
}

The above code would check the currently assigned attachment name for the slot named "slot_leftHand" and if an empty string is returned, a new sprite is attached.

Back: Skeletal Animations
Next: skeleton_attachment_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_bone_data_get

Provides access to the bone data used for the default pose of the skeletal animation.

Syntax:

skeleton_bone_data_get(bone, map);

Argument | Description
bone | The name (as a string) of the bone.
map | The (previously created) ds_map that stores the bone data.

Returns: N/A

Description

Your skeletal animation is made up of a number of "bones", which you will have defined and given names to in your animation program. This function can be used to get information on the named bone at any time and store the data in an empty ds_map, which you must have created previously. Note that this data refers to the default pose for the skeleton, and not the current pose that is being drawn. If you need the data from the current pose, use skeleton_bone_state_get.

When you call this function the map will be populated with the following keys:

  • "x": The local x position of the bone relative to the parent bone.

  • "y": The local y position of the bone relative to the parent bone.

  • "angle": The local rotation of the bone relative to the parent bone.

  • "xscale": The local horizontal scale of the bone, in reference to the parent bone.

  • "yscale": The local vertical scale of the bone, in reference to the parent bone.

  • "parent": The name (a string) of the parent bone.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

bone_map = ds_map_create();
skeleton_bone_data_get("leftarm", bone_map);

The above code creates a ds_map and then populates it with the data from the bone named "leftarm".

Back: Skeletal Animations
Next: skeleton_bone_data_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_bone_data_set

Permits you to modify the bone data used for the default pose of the skeletal animation.

Syntax:

skeleton_bone_data_set(bone, map);

Argument | Description
bone | The name (as a string) of the bone.
map | The (previously created) ds_map that stores the bone data.

Returns: N/A

Description

Your skeletal animation is made up of a number of "bones", which you will have defined and given names to in your animation program, and this function can be used to set certain data for the named bone at any time. Note that this data refers to the default pose for the skeleton, and not the current pose that is being drawn (for that use the function skeleton_bone_state_set), and must be set from a previously created ds_map, which should have the following keys and their equivalent values:

  • "x": The local x position of the bone relative to the parent bone.

  • "y": The local y position of the bone relative to the parent bone.

  • "angle": The local rotation of the bone relative to the parent bone.

  • "xscale": The local horizontal scale of the bone.

  • "yscale": The local vertical scale of the bone.

  • "parent": The name (a string) of the parent bone.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var bone_map = ds_map_create();
skeleton_bone_data_get("head", bone_map);
ds_map_replace(bone_map, "parent", "body");
skeleton_bone_data_set("head", bone_map);
ds_map_destroy(bone_map);

The above code creates a ds_map and then populates it with the data from the bone named "head". It then replaces the "parent" bone key in the map with a new value and sets the "head" bone again with the new set of data.

Back: Skeletal Animations
Next: skeleton_bone_state_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_bone_state_get

Provides access to the bone data as calculated from the current set animation.

Syntax:

skeleton_bone_state_get(bone, map);

Argument | Description
bone | The name (as a string) of the bone.
map | The (previously created) ds_map that stores the bone data.

Returns: N/A

Description

Your skeletal animation is made up of a number of "bones", which you will have defined and given names to in your animation program, and this function can be used to get certain data for the named bone at any time. Note that this data refers to the current pose for the skeleton, depending on the animation set used, and the function requires a previously created ds_map, which will then have the following keys and their equivalent values after calling the function:

  • "x": The local x position of the bone relative to the parent bone.

  • "y": The local y position of the bone relative to the parent bone.

  • "angle": The local rotation of the bone relative to the parent bone.

  • "xscale": The local horizontal scale of the bone, in reference to the parent bone.

  • "yscale": The local vertical scale of the bone, in reference to the parent bone.

  • "worldX": The x position of the bone relative to the root of the animation (this is a read only value).

  • "worldY": The y position of the bone relative to the root of the animation (this is a read only value).

  • "worldScaleX": The horizontal scale of the bone in "global" space (ignoring any transforms by GameMaker: Studio), as opposed to the scale with reference to its parent bone (this is a read only value).

  • "worldScaleY": The vertical scale of the bone in "global" space (ignoring any transforms by GameMaker: Studio), as opposed to the scale with reference to its parent bone (this is a read only value).

  • "worldAngle": The rotation of the bone relative to the root of the animation (this is a read only value).

  • "parent": The name (a string) of the parent bone.

The map data returned is similar to that returned for the default pose when you use skeleton_bone_data_get, only now you have the extra "world" keys. These refer to the position of the bone relative to the root (origin) of the skeletal animation sprite, and the returned values do not take into consideration any scaling or rotation that has been done by setting the built-in sprite variables like image_xscale or image_angle. The world values are read only and cannot be set.

This function is provided so that you can "intercept" animation data and modify it before it is drawn on the screen, and as such you would want to use it in the Animation Update event, since this event is triggered just before the Draw Events.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var map = ds_map_create();
skeleton_bone_state_get("head", map);
var xx = ds_map_find_value(map, "worldX");
var yy = ds_map_find_value(map, "worldY");
var deltax = mouse_x - (x + xx);
var deltay = mouse_y - (y + yy);
var angle = -radtodeg(arctan2(deltay, deltax));
ds_map_replace(map, "angle", angle);
skeleton_bone_state_set("head", map);
ds_map_destroy(map);

The above code creates a ds_map and then populates it with the data from the bone named "head". It then extracts the world position for the bone, and uses that data to set the "angle" of the bone to track the mouse position in the game.

Back: Skeletal Animations
Next: skeleton_bone_state_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_bone_state_set

Permits you to modify the bone data used for the current pose of the skeletal animation.

Syntax:

skeleton_bone_state_set(bone, map);

Argument | Description
bone | The name (as a string) of the bone.
map | The (previously created) ds_map that stores the bone data.

Returns: N/A

Description

Your skeletal animation is made up of a number of "bones", which you will have defined and given names to in your animation program, and this function can be used to set certain data for the named bone at any time. Note that this data will set the current pose for the skeleton, depending on the animation set used, and the function requires a previously created ds_map, which should have the following keys and their required values:

  • "x": The local x position of the bone relative to the parent bone.

  • "y": The local y position of the bone relative to the parent bone.

  • "angle": The local rotation of the bone relative to the parent bone.

  • "xscale": The local horizontal scale of the bone.

  • "yscale": The local vertical scale of the bone.

  • "parent": The name (a string) of the parent bone.

This function is provided so that you can "intercept" animation data and modify it before it is drawn on the screen, and as such you would want to use it in the Animation Update event, since this event is triggered just before the Draw Events.

Note that you can use the same map you filled out using the skeleton_bone_state_get function, even though it contains the additional "World" keys and values. Since these refer to read-only values, setting them with this function will have no affect.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var map = ds_map_create();
skeleton_bone_state_get("head", map);
var xx = ds_map_find_value(map, "worldX");
var yy = ds_map_find_value(map, "worldY");
var deltax = mouse_x - (x + xx);
var deltay = mouse_y - (y + yy);
var angle = arctan2(deltay, deltax);
var angle = point_direction(xx, yy, mouse_x, mouse_y);
ds_map_replace(map, "angle", -angle * 180 / pi);
skeleton_bone_state_set("head", map);
ds_map_clear(map);

The above code creates a ds_map and then populates it with the data from the bone named "head". It then extracts the world position for the bone, and uses that data to set the "angle" of the bone to track the mouse position in the game.

Back: Skeletal Animations
Next: skeleton_slot_data

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_collision_draw_set

Toggle on or off the drawing of collision data for the skeletal animation sprite.

Syntax:

skeleton_collision_draw_set(flag);

Argument | Description
flag | Set to true to turn on drawing, and false to turn it off.

Returns: N/A

Description

With this function, you can toggle on (true) or off (false) drawing the collision data for the current skeletal animation sprite being used by the instance. If this is switched on, the bounding box and the precise collision mask will be drawn as outlines around the sprite.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if debug_mode == true
{
skeleton_collision_draw_set(true);
}

The above code checks to see if the game is being run in debug mode and if it is, it toggles the skeletal collision data for the instance to be shown.

Back: Skeletal Animations
Next: skeleton_animation_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_get_bounds

Retrieve data about a specific bounding box associated with a skeleton animation sprite.

Syntax:

skeleton_get_bounds(index);

Argument | Description
index | The bounding box index to get the values of.

Returns: Array (minimum 2 elements: numPoints, name [, xPos, yPos, etc...])

Description

This function will return an array of values associated with any given bounding box for the currently assigned skeleton animation sprite. You supply the index number for the bounding box to get the details of (you can retrieve the total number of bounding boxes for the sprite using the function skeleton_get_num_bounds) and the functin will return an array with the following elements:

  • [0] - the number of points on the bounding box (a real)
  • [1] - the name of the bounding box (a string)
  • [2] - the x position of the first point
  • [3] - the y position of the first point
  • [etc...] - further x/y position data up to the number of points on the bounding box
IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var num = skeleton_get_num_bounds();
var yy = 60;
for(var i = 0; i < num; i++;)
{
var b_info = skeleton_get_bounds(i);
if b_info[0] > 0
{
var data = b_info[1] + ":";
for(var j = 0; j < b_info[0]; j++;)
{
data += " (" + string(b_info[(j * 2) + 2]) + ", " + string(b_info[(j * 2) + 2 + 1]) + ")";
}
draw_text(20, yy, data);
yy += 20;
}
}

The above code will loop through each of the bounding boxes associated with the currently assigned sprite and then draw that data as a string to the screen.

Back: Skeletal Animations
Next: skeleton_skin_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_get_minmax

Get the total bounding box position for the sprite

Syntax:

skeleton_get_minmax();

Returns: Array (4 elements: xMin, yMin, xMax, yMax)

Description

This function will return an array with the total bounding box value for all the individual bounding boxes assigned to a skeleton animation sprite. The returned array will have 4 elements:

  • [0] - the minimum x position for all bounding boxes
  • [1] - the minimum y position for all bounding boxes
  • [2] - the maximum x position for all bounding boxes
  • [3] - the maximum y position for all bounding boxes
IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var frame = skeleton_animation_get_frame(0);
if frame > 0 && frame < 2
{
var box = skeleton_get_minmax();
var ww = (box[2] - box[0]) / 2;
var hh = (box[3] - box[1]) / 2;
part_particles_create(global.p_sys, box[0] + ww, box[1] + hh, global.Stars, 10);
}

The above code will check the current frame of the animation assigned to track 0 and then burst some particles from a point in the middle of the total bounding box for the sprite.

Back: Skeletal Animations
Next: skeleton_get_num_bounds

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_get_num_bounds

Returns the number of bounding boxes attached to the current spine skeleton.

Syntax:

skeleton_get_num_bounds();

Returns: Integer

Description

This function will return the number of bounding boxes associated with the skeleton animation sprite assigned to the instance running the code. This can then be used along with the function skeleton_get_bounds to retrieve data about each of the bounding boxes.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var num = skeleton_get_num_bounds();
var yy = 60;
for(var i = 0; i < num; i++;)
{
var b_info = skeleton_get_bounds(i);
if b_info[0] > 0
{
var data = b_info[1] + ":";
for(var j = 0; j < b_info[0]; j++;)
{
data += " (" + string(b_info[(j * 2) + 2]) + ", " + string(b_info[(j * 2) + 2 + 1]) + ")";
}
draw_text(20, yy, data);
yy += 20;
}
}

The above code will loop through each of the bounding boxes associated with the currently assigned sprite and then draw that data as a string to the screen.

Back: Skeletal Animations
Next: skeleton_get_bounds

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_skin_get

Get the name of the skin that the skeletal animation sprite is being drawn with.

Syntax:

skeleton_skin_get();

Returns: String

Description

With skeletal animation sprites, you can assign separate textures (called "skins") to the animation, thereby using one animation for multiple different things. This function will return the name of the skin (as a string) that is currently assigned to the skeletal animation sprite your instance is using. The name returned is that which you set when you created the sprite in your animation program.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if skeleton_skin_get() == "skin_Enemy1"
{
skeleton_skin_set(choose("skin_Enemy1", "skin_Enemy2", "skin_Enemy3");
}

The above code would check the currently assigned skin for the animation and if it is "skin_Enemy1", it chooses and sets a new skin from one of three options.

Back: Skeletal Animations
Next: skeleton_skin_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_skin_list

Populate a DS list with the names for all skins included in the sprite.

Syntax:

skeleton_skin_list(sprite, list);

Argument | Description
sprite | The sprite index of the Spine skeletal animation to get the list from.
list | The ID of the DS list to populate with the animation names.

Returns: N/A

Description

With this function you can populate a (pre-created) ds_list with all the names of the skins included as part of the skeletal animation sprite. The names will be strings and can then be used in the other skeleton animation skin functions for these types of sprite.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var list = ds_list_create();
skeleton_skin_list(sprite_index, list);
var num = ds_list_size(list);
skeleton_skin_set(list[| irandom(num - 1));
ds_list_destroy(list);

The above code creates a DS list then populates it with the skin names. A random one is then chosen and applied to the instance before the list is destroyed.

Back: Skeletal Animations
Next: skeleton_attachment_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_skin_set

Set the skin that the skeletal animation sprite should be drawn with.

Syntax:

skeleton_skin_set(skinname);

Argument | Description
skinname | The name (a string) of the skin to use.

Returns: N/A

Description

A skeletal animation sprite can be drawn with a variety of textures (called "skins"), permitting you to use one single animation for multiple different purposes. For example, you may have a generic walk animation and this can be used by your NPC characters, enemies, etc... in a game simply by changing the skin it is drawn with. These skins need to have been previously created and named in your animation program, and this name is passed into the function (as a string) to set the sprite to use that skin when being drawn.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

if skeleton_skin_get() == "skin_Enemy1"
{
skeleton_skin_set(choose("skin_Enemy1", "skin_Enemy2", "skin_Enemy3");
}

The above code would check the currently assigned skin for the animation and if it is "skin_Enemy1", it chooses and sets a new skin from one of three options.

Back: Skeletal Animations
Next: skeleton_skin_list

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


skeleton_slot_data

Populate a DS list with a series of DS maps containing information about each available attachment slot.

Syntax:

skeleton_slot_data(sprite, list);

Argument | Description
sprite | The sprite index of the Spine skeletal animation to get the data from.
list | The ID of the DS list to populate with the DS maps.

Returns: N/A

Description

With this function you can populate a (pre-created) ds_list with data for each of the available attachment slots that an animation contains. This data is returned in the forum of a ds_map which contains the following key/value pairs:

  • "name": The name of the slot.

  • "bone": The name of the bone.

  • "attachment": The name of the attachment if one is used or "(none)" if there isn't one assigned.

The values for each key will be strings and can then be used in the other skeleton attachment functions for these types of sprite. Note that the ds_map created are not destroyed so you will need to loop through the ds_list and destroy each of the created maps yourself.

IMPORTANT: Spine integration in GameMaker: Studio is a Pro licence feature and will not work in the Free/Standard versions.

Example:

var list = ds_list_create();
var open = true;
slot_name = "";
skeleton_slot_data(sprite_index, list);
for (var i = 0; i < ds_list_size(list); i++;)
{
var map = list[| i];
if open
{
if map[? "attachment"] == "(none)"
{
open = false;
slot_name = map[? "name"];
}
}
ds_map_destroy(map);
}
ds_list_destroy(list);

The above code creates a DS list and then populates it with the slot data for the instance sprite. This data is then parsed to extract the individual DS maps with the slot data. This is then checked to see if there is an empty slot, and if so the variable "slot_name" is assigned the empty slot name before the DS map is destroyed. Finally we destroy the DS list as it is no longer required.

Back: Skeletal Animations
Next: skeleton_collision_draw_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


HTML5

These functions are provided specifically for the HTML5 platform.

The HTML5 module has some functions that are specifically designed to be used by the games that target it, although it should be noted that some of them may also work for other target platforms too.

The available functions for HTML5 are:

  1. url_open
  2. url_open_ext
  3. url_open_full
  4. url_get_domain
  5. browser_height
  6. browser_width
  7. browser_input_capture
  8. webgl_enabled
  9. clickable_exists
  10. clickable_add
  11. clickable_add_ext
  12. clickable_change
  13. clickable_change_ext
  14. clickable_set_style
  15. clickable_delete

Apart from these functions for the HTML5 target module, there is also a special JavaScript variable that can be used on those rare occasions when the contents of the html5game folder are stored in a completely different place (URL). Normally this path is hard-coded in the JavaScript file and is relative to the location from where the JavaScript is called, but you can set the variable g_GameMakerHTML5Dir before the call to the game script and the game will be run from the newly defined location. For example:

<script>var g_GameMakerHTML5Dir = "http://mygamealternatedirectory.com/";</script>

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


browser_height

This variable returns the height, in pixels, of the current area of the browser (if applicable).

Syntax:

browser_height

Returns: Real

Description

This variable holds the height (in pixels) of the browser the game is being run in. If no browser is present then the window size is returned. the following image illustrates how this variable relates to the rest of the positioning functions available through the Window Functions.

Example:

if browser_height > window_get_height() || browser_width > window_get_width()
{
var xx, yy;
if browser_width > window_get_width()
{
xx = (browser_width - window_get_width()) / 2;
}
else
{
xx = 0;
}
if browser_height > window_get_height()
{
yy = (browser_height - window_get_height()) / 2;
}
else
{
yy = 0;
}
window_set_position(xx, yy);
}

The above code checks the width and height of the browser to see if either is larger than the current window width and height. If either of them are, it then calculates a new position for the game window within the browser.

Back: HTML5
Next: browser_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


browser_input_capture

Set whether the GameMaker: Studio game should get input or the browser.

Syntax:

browser_input_capture(enable)

Returns: N/A

Description

With this function you can set whether the browser window should capture all input (set it to false) or whether the game should capture the input (set it to true). Note that this function is for use with the HTML5 module only.

Example:

browser_input_capture(true);

The above code sets the game to capture al browser input on the HTML5 target platform.

Back: HTML5
Next: webgl_enabled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


browser_width

This variable which returns the height, in pixels, of the current area of the browser (if applicable).

Syntax:

browser_width

Returns: Real

Description

This variable holds the width (in pixels) of the browser the game is being run in. If no browser is present then the window size is returned. the following image illustrates how this variable relates to the rest of the positioning functions available through the Window Functions.

Example:

if browser_height > window_get_height() || browser_width > window_get_width()
{
var xx, yy;
if browser_width > window_get_width()
{
xx = (browser_width - window_get_width()) / 2;
}
else
{
xx = 0;
}
if browser_height > window_get_height()
{
yy = (browser_height - window_get_height()) / 2;
}
else
{
yy = 0;
}
window_set_position(xx, yy);
}

The above code checks the width and height of the browser to see if either is larger than the current window width and height. If either of them are, it then calculates a new position for the game window within the browser.

Back: HTML5
Next: browser_input_capture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clickable_add

Creates a clickable DOM icon outside of the canvas element.

Syntax:

clickable_add(x, y, tpe, url, target, params);

Argument | Description
x | The x position within the window.
y | The y position within the window.
tpe | The texture page entry for the sprite to be used (use sprite_get_tpe).
url | The URL (website address) to link to, or the script to be run.
target | This is the target area to open the URL in (see description).
params | The various parameters for the icon (see description).

Returns: Real

Description

With this function you can create a custom, clickable, icon that acts as a "button" outside of the game canvas, but within the browser window itself. The function will return an id value which must be stored in a variable to be used in all further button functions that reference the new icon. This function is very useful to prevent the browser creating a pop-up window when clicking on the button as it is all done through GameMaker: Studio itself.

You must first set the position, which is relative to the (0,0) of the browser window (top left corner) and then give the texture page entry for the sprite you wish the button icon to have (see: sprite_get_tpe). You can then specify either a URL to open or a script (from the resource tree of GameMaker: Studio) to be opened or run. The "target" parameter that you specify is the same as the standard JavaScript "name" value when you use the open() method (be aware that all but '_self' may result in the browser blocking, or asking the user if they wish to allow it) and the "params" argument is the same as the JavaScript "specs" parameter for controlling what properties the new window/tab should display (not all browsers may support all features). If you are using the icon to run an internal script, these last two arguments can be left as empty strings "".

Valid targets are:

Target | Description
_blank | Opens the linked document in a new window or tab.
_self | Opens the linked document in the same frame as it was clicked (this is default).
_parent | Opens the linked document in the parent frame.
_top | Opens the linked document in the full body of the window.

Valid parameters are:

Parameters | Description
'height=[px]' | The height of the window, with the minimum value being 100.
'width=[px]' | The width of the window, with the minimum value being 100.
'left=[px]' | The left position of the window.
'top=[px]' | The top position of the window (IE only).
'location=[boolean]' | Whether or not to display the address field (default is 1).
'menubar=[boolean]' | Whether or not to display the menu bar (default is 1).
'resizable=[boolean]' | Whether or not the window is resizable (default is 1).
'scrollbars=[boolean]' | Whether or not to display scroll bars (default is 1).
'status=[boolean]' | Whether or not to add a status bar (default is 1).
'titlebar=[boolean]' | Whether or not to display the title bar. This is ignored unless the calling application is an HTML Application or a trusted dialog box (default is 1);
'toolbar=[boolean]' | Whether or not to display the browser toolbar (default is yes).

It is also worth noting that if the URL argument you pass in is the name of a script (ie: it doesn't start with "http://") AND the script is called gmcallback_* then you can get direct feeds into an html5 event. GameMaker: Studio function names are not obfuscated if they begin with gmcallback_.

Example:

home_but = clickable_add(32, 32, sprite_get_tpe(spr_MS_Home, 0), "http://macsweeney_games.com", "_blank", "width=700, height=500, menubar=0, toolbar=0, scrollbars=0");

The above code creates a clickable DOM icon at the position (32, 32) of the page that the game canvas is running on. The icon uses the sprite referenced from the texture page as "spr_MS_Home" and when clicked the icon will open a new window for the specified URL and with the defined properties for that window.

Back: HTML5
Next: clickable_add_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clickable_add_ext

Creates a clickable DOM icon outside of the canvas element with custom scale and alpha.

Syntax:

clickable_add_ext(x, y, tpe, url, target, params, scale, alpha);

Argument | Description
x | The x position within the window.
y | The y position within the window.
tpe | The texture page entry for the sprite to be used (use sprite_get_tpe).
url | The URL (website address) to link to, or the script to be run.
target | This is the target area to open the URL in (see description).
params | The various parameters for the icon (see description).
scale | The scale of the icon (default 1).
alpha | The image alpha of the icon (default 1).

Returns: Real

Description

With this function you can create a custom, clickable, icon that acts as a "button" outside of the game canvas, but within the browser window itself. The function will return an id value which must be stored in a variable to be used in all further button functions that reference the new icon. This function is very useful to prevent the browser creating a pop-up window when clicking on the button as it is all done through GameMaker: Studio itself.

This function works exactly the same as the clickable_add function, where you must set the position relative to the (0,0) of the browser window, give the texture page entry for the sprite you wish the button icon to have (see: sprite_get_tpe), specify either a URL to open or a script (from the resource tree of GameMaker: Studio) to be opened or run then set the target and parameters to use. However this function also has two additional options that permit you to set the icon alpha from 0 (fully transparent) to 1 (fully opaque) and the scale of the icon, which is a multiplier value applied to the sprite used. So a value of 1 is the default scale, while (for example) 0.5 would be half scale and 2 would be double.

It is also worth noting that if the URL argument you pass in is the name of a script (ie: it doesn't start with "http://") AND the script is called gmcallback_* then you can get direct feeds into an html5 event. GameMaker: Studio function names are not obfuscated if they begin with gmcallback_.

Example:

home_but = clickable_add_ext(32, 32, sprite_get_tpe(spr_MS_Home, 0), "http://macsweeney_games.com", "_blank", "width=700, height=500, menubar=0, toolbar=0, scrollbars=0", 2, 1);

The above code creates a clickable DOM icon at the position (32, 32) of the page that the game canvas is running on. The icon uses the sprite referenced from the texture page as "spr_MS_Home" and when clicked the icon will open a new window for the specified URL and with the defined properties for that window. the button will also be scaled to twice the original sprite size and half an image alpha of 1.

Back: HTML5
Next: clickable_change

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clickable_change

Changes the sprite used for a clickable icon.

Syntax:

clickable_change(index, tpe, x, y)

Argument | Description
index | The index of the clickable icon to change.
tpe | The texture page entry for the sprite to be used (use sprite_get_tpe).
x | The new x position within the window.
y | The new y position within the window.

Returns: N/A

Description

With this function you can change the sprite and position of a clickable icon previously created with clickable_add. Please note that the position is based on the window, not the canvas, (0,0) position and that the sprite must be referenced directly from the texture page (see: sprite_get_tpe).

Example:

switch (room)
{
case rm_Menu: clickable_change(global.Help_Icon, sprite_get_tpe(spr_MS_Help, 1), 32, 32); break;
case rm_Game: clickable_change(global.Help_Icon, sprite_get_tpe(spr_MS_Help, 0), 200, 32); break;
}

The above code will change the image index and position of the clickable icon indexed in the variable "global.Help" depending on the current room.

Back: HTML5
Next: clickable_change_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clickable_change_ext

Changes the sprite and the sprite properties for a clickable icon.

Syntax:

clickable_change_ext(index, tpe, x, y, alpha, scale)

Argument | Description
index | The index of the clickable icon to change.
tpe | The texture page entry for the sprite to be used (use sprite_get_tpe).
x | The new x position within the window.
y | The new y position within the window.
scale | The scale of the icon (default 1).
alpha | The image alpha of the icon (default 1).

Returns: N/A

Description

With this function you can change the sprite and position of a clickable icon previously created with clickable_add. Bear in mind that the position is based on the window, not the canvas, (0,0) position and that the sprite must be referenced directly from the texture page (see: sprite_get_tpe). This function also permits you to change the scale of the sprite used (as a multiplier so that 1 is the default, 0.5 would be half and 2 would be double) and the alpha value from 0 (fully transparent) to 1 (fully opaque) for the final icon on the screen.

Example:

switch (room)
{
case rm_Menu: clickable_change_ext(global.Help_Icon, sprite_get_tpe(spr_MS_Help, 1), 32, 32, 2, 1); break;
case rm_Game: clickable_change_ext(global.Help_Icon, sprite_get_tpe(spr_MS_Help, 0), 200, 32, 1, 0.5); break;
}

The above code will change the image index and position of the clickable icon indexed in the variable "global.Help" depending on the current room, changing the icon scale and alpha too.

Back: HTML5
Next: clickable_set_style

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clickable_delete

Removes a clickable icon from the window.

Syntax:

clickable_delete(index);

Argument | Description
index | Index of the clickable icon to remove.

Returns: N/A

Description

This function must be used to remove a clickable icon previously created with clickable_add from the game window.

Example:

clickable_delete(global.Help_Icon);

The above code removes the clickable icon indexed in the global variable "Help_Icon" from the game window.

Back: HTML5
Next: url_open

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clickable_exists

Checks to see if a clickable DOM icon exists.

Syntax:

clickable_exists(index);

Argument | Description
index | The index of the clickable to check.

Returns: Boolean

Description

This function returns whether a clickable DOM icon has been created with the specified index exists or not. Please note, that the value used for checking must have been initialised previously or else you will get an error causing GameMaker: Studio to close.

Example:

if !clickable_exists(home_but)
{
home_but = clickable_add(32, 32, sprite_get_tpe(spr_MS_Home, 0), "http://macsweeney_games.com", "_blank", "width=700, height=500, menubar=0, toolbar=0, scrollbars=0");
}

The above code checks the variable "home_but" to see if it already exists, and if it does not it creates a clickable DOM icon at the position (32, 32) of the page that the game canvas is running on. The icon uses the sprite referenced from the texture page as "spr_MS_Home" and when clicked the icon will open a new window for the specified URL and with the defined properties for that window.

Back: HTML5
Next: clickable_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clickable_set_style

Set the button style from a ds_map.

Syntax:

clickable_set_style(index, map)

Argument | Description
index | The index of the clickable icon to style.
map | The index of the ds_map to set the style from.

Returns: N/A

Description

This function lets you set the CSS style properties for the given button via the key/value pairs in the provided ds_map. You need to have previously created the both the button element (using clickable_add()) and the ds_map previously and supply the stored indices as arguments.

Example:

var map = ds_map_create();
ds_map_add(map, "opacity", "0.5");
clickable_set_style(button, map);
ds_map_destroy();

The above code will change the style of the clickable button with the index stored in the variable "button".

Back: HTML5
Next: clickable_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


url_get_domain

Returns the domain where the game is being hosted (HTML5 only).

Syntax:

url_get_domain();

Returns: string

Description

You can use this to get the domain where your HTML5 game is being played.

Example:

dom_name=url_get_domain();

This will store the domain of your game in the variable "dom_name".

Back: HTML5
Next: browser_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


url_open

Opens a URL on a browser.

Syntax:

url_open(url);

Argument | Description
url | The URL (website address) to link to.

Returns: N/A

Description

This will open the specified URL on the browser of the chosen target device, or, if you are using the HTML5 module, in the currently open browser.

Example:

url_open( 'http://yoyogames.com' );

This would open the YoYo Games homepage in the current window.

Back: HTML5
Next: url_open_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


url_open_ext

Opens a URL on a browser with a specific target.

Syntax:

url_open_ext(url, target);

Argument | Description
url | The URL (website address) to link to.
target | This is the target area to open the URL in.

Returns: N/A

Description

This will open the specified URL on the browser of the chosen target device, or, if you are using the HTML5 module, in the currently open browser. The "target" parameter that you specify is the same as the standard JavaScript "name" value when you use the open() method, and you should be aware that all but '_self' may result in the browser blocking, or asking the user if they wish to allow it.

Valid targets are:

"_self": Opens the linked document in the same frame as it was clicked (this is default).
"_blank": Opens the linked document in a new window or tab (this will not work if pop-ups are being blocked by the user, in which case you can use the clickable_* functions instead).
"_parent": Opens the linked document in the parent frame.
"_top": Opens the linked document in the full body of the window.

Example:

url_open_ext( 'http://yoyogames.com', '_blank');

This would open the YoYo Games homepage in a new window.

Back: HTML5
Next: url_open_full

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


url_open_full

Opens a URL on a browser, with a specific target and formatting.

Syntax:

url_open_full(url, target, options);

Argument | Description
url | The URL (website address) to link to.
target | This is the target area to open the URL in (see description).
options | Standard browser options (see description).

Returns: N/A

Description

This will open the specified URL on the browser of the chosen target device, or, if you are using the HTML5 module, in the currently open browser. The "target" parameter that you specify is the same as the standard JavaScript "name" value when you use the open() method (be aware that all but '_self' may result in the browser blocking, or asking the user if they wish to allow it) and the "options" is the same as the JavaScript "specs" parameter for controlling what properties the new window/tab should display (not all browsers may support all features).

Valid targets are:

"_self": Opens the linked document in the same frame as it was clicked (this is default).
"_blank": Opens the linked document in a new window or tab (this will not work if pop-ups are being blocked by the user, in which case you can use the clickable_* functions instead).
"_parent": Opens the linked document in the parent frame.
"_top": Opens the linked document in the full body of the window.

Valid options are:

"height=[px]": The height of the window, with the minimum value being 100.
"width=[px]": The width of the window, with the minimum value being 100.
"left=[px]": The left position of the window.
"top=[px]": The top position of the window (IE only).
"location=[boolean]": Whether or not to display the address field (default is 1).
"menubar=[boolean]": Whether or not to display the menu bar (default is 1).
"resizable=[boolean]": Whether or not the window is resizeable (default is 1).
"scrollbars=[boolean]": Whether or not to display scroll bars (default is 1).
"status=[boolean]": Whether or not to add a status bar (default is 1).
"titlebar=[boolean]": Whether or not to display the title bar. This is ignored unless the calling application is an HTML Application or a trusted dialog box (default is 1);
"toolbar=[boolean]": Whether or not to display the browser tool-bar (default is yes).

Example:

url_open_full( 'http://yoyogames.com', '_blank', 'resizable=0, height=200, scrollbars=0');

This would open the YoYo Games homepage in a new window that can't be resized, has a height of 200 pixels and no scrollbars.

Back: HTML5
Next: url_get_domain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


webgl_enabled

Returns whether the browser supports WebGL functionality and hardware acceleration.

Syntax:

webgl_enabled

Returns: Boolean

Description

This read-only variable will return whether WebGL is enabled (true) or not (false) for your game. It will only work for those games running through a browser (ie: HTML5), and for all other platforms it will return true.

Example:

if webgl_enabled global.quality = 1 else global.quality = 0;

The above code checks the WebGL flag and then sets the global variable "quality" accordingly.

Back: HTML5
Next: clickable_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


In App Purchases

This section deals with setting up in app purchases for your game.

In App Purchases are an important part of modern, cross platform games, permitting you to have "freemium" content where your game is free, but certain content is only available through a purchase from within the game itself. For example, your puzzle game is free, but the extra levels are going to cost the user 0.99$. This app model is very common and can be set up with a minimum amount of work from within GameMaker: Studio, and this section of the manual has details of all the available functions that enable you to do just that, as well as some advice for setting up and information on how to test on the different platforms.

NOTE: This functionality is limited to the Professional Version of GameMaker: Studio, and only those versions that have the Mac, iOS, or Android target modules. For Android you will have to have downloaded and installed the Google Play Services extension along with the Google Play In App Purchases extension from the YoYo Games Marketplace. Once you have added the extensions to the project you can go to the Android Global Game options and select the Social tab, then check the appropriate check-boxes.

Getting Started

Setting up in app purchases within your game is relatively simple with GameMaker: Studio, but it still requires some amount of knowledge of the target platform setup as well as careful planning before starting to create your game, so it is not recommended that you use this functionality if you are just starting with GameMaker: Studio or if you are not sure how the different stores for each target platform are set up.

Before doing anything else you will have to make sure that in app purchases are enabled in the Global Game Settings before they will be functional in your game (more information can be found on the page Global Game Settings - In App Purchases Tab). You will also need to have set up the purchase details on the target store for each platform that you wish to support, taking careful note of each of the Product IDs that you define, as these ID strings are how GameMaker: Studio identifies each product and purchase.

To help those of you that have never worked with any type if IAP services and to explain the different ways that IAP can be tested on different devices, please see the following pages:

  1. IAP Example
  2. IAP Testing

NOTE: GameMaker: Studio currently permits up to 128 purchases per title, except if you are using the Amazon Store (for Android) where it is limited to 100.

WARNING: You will not be able to make purchases when debugging titles using the GameMaker IDE. Instead you will need to create final executables to ensure the title can correctly communicate with the respective store servers.

GameMaker: Studio Functions

Below are listed the functions that are integrated in GameMaker: Studio to enable in app purchases on iOS and Android target devices (this is the ability to buy extra credits, items, levels and other things from within the game itself). Many of these functions will trigger an asynchronous IAP Event, which contains a special ds_map with an initial key "type". This can then be queried to get the type of IAP event that has been triggered, which will then permit you to get further data from the map.

The available in app purchase functions are:

  1. iap_activate
  2. iap_status
  3. iap_enumerate_products
  4. iap_restore_all
  5. iap_acquire
  6. iap_consume
  7. iap_product_details
  8. iap_purchase_details
  9. iap_is_purchased

You should also be aware that GameMaker: Studio does not persist active purchase state across multiple plays of the game (and thus iap_is_purchased() is unreliable if a store has not successfully loaded). This means that you will have to store this information yourself and retrieve it again on each start-up of your game. You can use the special "secure" save and load functions provided for ds_maps for this purpose:

  1. ds_map_secure_save
  2. ds_map_secure_load

GameMaker: Studio does not persist purchase state across multiple plays of the game because it is not appropriate for us to provide a secure method of verifying whether or not an individual purchase is valid and therefore any automatically stored purchase state would be presumptuous. On most platforms "receipt" data will be available through iap_purchase_details() which users can use to verify a purchase, although Google Play uses "token" data instead.

GameMaker: Studio requires the Google Play Public Key for simple local purchase verification and you may check that the "payload" data returned with a purchase result matches that used with the matching call to iap_acquire().

Deprecated Functions

With the update to version 1.3, the In App Purchasing routines were made more secure and also simplified somewhat, meaning that some functions have been made obsolete and will no longer do anything. These functions are listed below for reference only and should not be used. Any games created with these that you wish to update on a store will need to be re-written using the newer system.

  1. iap_store_status
  2. iap_event_queue
  3. iap_product_status
  4. iap_is_downloaded
  5. iap_product_files
  6. iap_files_purchased

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_acquire

This requests acquisition of the given product.

Syntax:

iap_acquire(purchase_id, payload);

Argument | Description
purchase_id | The product ID string for the purchase.
payload | This is a string that can be used for purchase verification on Google Play (use an empty string, "", on all other platforms).

Returns: Real

Description

This function is the one that you use to acquire a purchase through the target store for the device running your game. This product ID string is that which you specify when activating the IAP using iap_activate, and should be the same as that which you used to identify the product on the target store. This function will return an value as it's "index" so that it can be identified when the purchase data comes through and calling the function will trigger an IAP Event of the "type" iap_ev_purchase, which will contain the following additional key:

  • "index" - The purchase ID for the activated product.

This purchase ID can then be used to check which purchase has triggered the event (comparing it to the returned index value that you stored), so you can deal with it accordingly. If you are developing for Google Play (on the Android target), then you can also set the "Payload" string. This is used by Google to verify the product and is sent along with the purchase request to Google Play. When a purchase is successfully completed the game will receive the payload used as part of the purchase information. By generating a payload with each purchase you can therefore provide a simple form of purchase verification.

Example:

if mouse_check_button_pressed(mb_left)
{
iap_acquire("noads", "")
}

The above code will send a purchase request when the mouse button is pressed.

Back: In App Purchases
Next: iap_consume

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_activate

Enables support for making in app purchases.

Syntax:

iap_activate(product_index);

Argument | Description
product_index | The index of the ds_list that contains the available purchases.

Returns: N/A

Description

This function enables support for making in-app purchases and prepares GameMaker: Studio by supplying the product ds_list that holds a series of ds_maps with the information on each available purchase. This means that you will need to tell GameMaker: Studio all the available purchase options by setting them in individual ds_maps (one for each available purchase), which are then stored within a ds_list, which is then "activated" with this function.

The individual purchase maps that are to be stored in the ds_list should have the following format of key-value pairs:

  • "id" - The product ID for the purchase, eg: "LevelPack".

  • "title" - The name of the purchase, eg: "Level Pack 1".

  • "description" - The description of the purchase, eg: "Level Pack 1 for Catch The Clown".

  • "price" - The price of the purchase, eg: "$1.00".

It is worth noting that the only essential keys for any target store setup (per product ID) is the "id".

Activating purchases will also trigger an IAP Event, which creates a special iap_data ds_map of the event type iap_ev_product. This ds_map will have the following additional key:

  • "index" - The product ID for the activated product.

If you are activating multiple products, then each product will trigger its own IAP Event of the type iap_ev_product where you can then get the product ID. It is worth noting that the Google Play store (for Android) can only process details for products 20 at a time which can lead to quite long load times for applications with a significant number of products.

NOTE: All the key/value pairs that comprise a purchase map are strings!

Example:

var purchaseList, purchase1;
purchaseList = ds_list_create();
purchase1 = ds_map_create();
ds_map_add(purchase1, "id", "LevelPack");
ds_map_add(purchase1, "title", "ExtraLevels1");
ds_map_add(purchase1, "description", "Level Pack 1 for Catch The Clown");
ds_map_add(purchase1, "price", "$1.00");
ds_list_add(purchaseList, purchase1);
iap_activate(purchaseList);
ds_map_destroy(purchase1);
ds_list_destroy(purchaseList);

The above code will create a ds_list and a ds_map, which is then populated by the information for making a purchase. This map is added to the list and then activated as an available purchase for the game. Finally the ds_list and ds_map are removed to prevent memory leaks as they are no longer needed.

Back: In App Purchases
Next: iap_status

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_consume

Clears the purchase status of unmanaged purchases.

Syntax:

iap_consume(purchase_id);

Argument | Description
purchase_id | The product ID string for the purchase.

Returns: N/A

Description

This function can be used for clearing the purchase status of any unmanaged (consumable) purchases. The "purchase_id" is the product ID string which you specified when activating the IAP using iap_activate, and should be the same as that which you used to identify the product on the target store. This function will trigger an IAP Event of the "type" iap_ev_consume, which will contain the following additional keys:

  • "product" - The product ID for the consumed product.

This product ID can then be used to check which purchase has triggered the event, and you can deal with it accordingly.

WARNING: You cannot purchase a consumable product multiple times in a row without consumption - you must perform a consume operation between subsequent purchases.

Example:

if mouse_check_button_pressed(mb_left)
{
iap_consume("noads")
}

The above code will clear the purchase status when the mouse button is pressed.

Back: In App Purchases
Next: iap_product_details

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_enumerate_products

Populate a ds_list with all the currently available IAP products from the target store.

Syntax:

iap_enumerate_products();

Returns: N/A

Description

This function retrieves the list of in app purchase product ids encountered. On most platforms this will simply return the set of product ids provided through iap_activate(), but on platforms where the store provides the facility to retrieve a complete list of available products for a title then this set of product ids will include any and all available product ids for the game. The function requires that you supply a previously made ds_list (which you should clear first if it has been used for other purposes) which will be populated by the function call. Regardless of platform, if the target store is not available then it will get the product IDs from those supplied when you activated purchases using iap_activate.

Example:

var status = iap_status();
var iap_list = ds_list_create();
if status == iap_status_available
{
iap_enumerate_products(iap_list);
}

The above code checks the status of the target IAP store, and if it is available it will populate the created list with the available product IDs for future use.

Back: In App Purchases
Next: iap_restore_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_event_queue

Creates a ds_queue of purchase information.

Syntax:

iap_event_queue();

Returns: ds_queue

Description

WARNING! This function has been deprecated.

The purpose of this function is to get all store changes or to receive confirmation when a purchase has gone through correctly. Note that the confirmation of purchase only means that the payment for the in app purchase has succeeded, it does not mean that any downloadable content associated with it has been received by the game. To check for that you should use the iap_product_files or iap_is_downloaded functions.

This function is only available in the IAP Event and will return a ds_queue with the following values (where appropriate):

  • -1 indicating that the event was a store state change.
  • A product index NUMBER. i.e. the value you’d use for iap_aquire or iap_consume.

NOTE: When we talk about the index NUMBER, we are not talking about the purchase id, but rather the position in the initial list that was used to activate purchases. For example, if you have activated 3 different items for purchase, and the player buys item number 2, the index number returned by this function would be 1 (numbering starts at 0, so product 1 is index 0, product 2 is index 1 and product 3 is index 2).

NOTE: The ds_queue created by the function is automatically removed by GameMaker: Studio at the end of the event, so there is no need for you to manually "clean up" and remove it from memory.

Example:

var q;
q = iap_event_queue();
if !ds_queue_empty(q))
{
store_status = ds_queue_dequeue(q);
}

The above code will query the returned ds_queue to see if it contains data and if so, store (and remove from the queue) the first value found in the variable "store_status". For an extended example of use please see the function iap_store_status.

Back: In App Purchases

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_files_purchased

Returns all information about any products that have been purchased.

Syntax:

iap_files_purchased();

Returns: Real

Description

WARNING! This function has been deprecated.

This function returns all the information about any products that have been purchased for the game on the device in the form of a ds_map. The key for each entry in the map is the product id and its value is a ds_list which itself contains a set of strings indicating the files that were extracted for the purchase.

NOTE: The ds_map returned is created by this function and maintained by GameMaker: Studio for all further calls. This means that you should not remove it from memory.

Example:

p_details = iap_files_purchased();
p_list = ds_map_find_value(p_details, "com.MacSweeney Games.CatchTheClown");
var i;
for (i = 0; i < ds_list_size(p_list); i += 1)
{
f_name = ds_list_find_value(p_list, i);
draw_text(32, 32 + (i * 32), f_name);
}
ds_map_destroy(p_details);

The above code gets the purchase details for the game with the given product index and then draws them one by one down the side of the screen.

Back: In App Purchases

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_is_downloaded

Checks to see if the purchase has been downloaded.

Syntax:

iap_is_downloaded(purchase_id);

Argument | Description
purchase_id | This can either be the Apple Store/Google Play id string, an URL id, or an index into the available purchases ds_list.

Returns: Boolean

Description

WARNING! This function has been deprecated.

This function can be used for checking to see if a purchase has been downloaded correctly (returns true) or not (returns false). The purchase_id can be either an integer index into the main purchases list, the explicit Apple Store/Google Play id string, or you can pass through the actual identifier name(eg: ".extralevels"), similar to the way that iap_acquire works. Please note that for consumables (ie: purchases that require no downloadable content) this function will always return true.

Extended Example:

We can use this function to check and see if the paid-for purchase has finished downloading or not. To start with we need to check the data returned from the function iap_event_queue which you would get from the asynchronous IAP Event. In the Create Event of the instance you would prepare a variable to store the returned value of this function and then in the IAP event itself have something like this:

var q;
q = iap_event_queue();
if !ds_queue_empty(q))
{
downloaded = ds_queue_dequeue(q);
}
else
{
downloaded = 0;
}

We can then use this value in other IAP functions, or simply check it to draw a status message for our user to see so they know that the download has been completed:

if iap_is_downloaded(downloaded)
{
draw_text(x, y, "Files downloaded:");
}

The above code will now use the iap_is_downloaded function to display a message to the user when the product they have bought has been downloaded correctly.

Back: In App Purchases

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_is_purchased

iap_is_purchased (deprecated)

Indicates whether or not a product has been purchased.

Syntax:

iap_is_purchased(product_id);

Argument | Description
product_id | The product ID string for the purchase.

Returns: Boolean

Description

WARNING!: This function has been deprecated and is no longer used.

With this function you can find out if the product you are checking has been bought previously or not, and has not yet been consumed. It will return true if the purchase exists and has not yet been consumed, or it will return false if the product does not exist, has not been purchased, or has already been consumed.

NOTE: This function is only valid if communication with the target store has been established.

Example:

if iap_status() == iap_status_available
{
var purchased;
purchased = iap_is_purchased(p_id);
if purchased
{
iap_consume(p_id)
}
}

The above the product ID to test and see if it the associated consumable product been bought or not, and if it has it calls the iap_consume() function.

Back: In App Purchases
Next: iap_activate

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_product_details

Add details of a single product to a ds_map.

Syntax:

iap_product_details(product_id, ds_map);

Argument | Description
purchase_id | The product ID string for the purchase.
ds_map | The ds_map that will store the product information.

Returns: N/A

Description

With this function you can populate a previously created ds_map with a number of key/value pairs that describe the given purchase. The following data is returned within the map:

  • "id" - The product ID string.

  • "title" - The title of the product.

  • "description" - The description of the product.

  • "price" - The price of the product, where available (not all stores support this).

  • "type" - The type of product, which will be either "Consumable" or "Durable", where available (not all stores support this).

  • "verified" - Will be either true or false (ie: real numbers 0 or 1) depending on whether or not your game has received details of this product from the store and thus believes this product to be available for purchase.

NOTE: The ds_map used is not created by the function, meaning that you must create it previously and remove it again from memory when not in use using the appropriate function.

Example:

var p_map = ds_map_create();
iap_product_details(ds_map_find_value(iap_data, "index"), p_map);
p_title = " + string(ds_map_find_value(p_map, "title")));
p_description = " + string(ds_map_find_value(p_map, "description")));
ds_map_destroy(p_map);

The above code will create a ds_map and then populate it with the product details for the product taken from the special iap_data ds_map which is created exclusively in the IAP Event. The "title" and "description" are then added to variables so that they can later be drawn on the screen.

Back: In App Purchases
Next: iap_purchase_details

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_product_files

Add product files to a ds_list.

Syntax:

iap_product_files(purchase_id, ds_list);

Argument | Description
purchase_id | This can either be the Apple Store/Google Play id string, an URL id, or an index into the available purchases ds_list.
ds_list | The ds_list that will store the product information.

Returns: N/A

Description

WARNING! This function has been deprecated.

With this function you can generate a ds_list containing all the files associated with the given product id.

NOTE: The ds_list used is not created by the function, meaning that you must create it previously and remove it again from memory when not in use using the appropriate function.

Example:

if iap_product_status(p_id) == "Purchased"
{
var list, i;
list = ds_list_create();
iap_product_files(p_id, list);
for (i = 0; i < ds_list_size(list); i += 1)
{
draw_text(x, y + (i * 32), ds_list_find_value(list, i));
}
ds_list_destroy(list);
}

The above code checks the previously stored product id to see if it has been purchased, and if it has it then creates and displays a list of product files that have been downloaded.

Back: In App Purchases

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_product_status

Indicates whether or not a product has been purchased.

Syntax:

iap_product_status(product_id);

Argument | Description
product_id | The Apple Store/Google Play product id for the purchase in reverse URL format, eg: "com.MacSweeney Games.CTC.LevelPack".

Returns: String

Description

WARNING! This function has been deprecated.

This function is similar to the iap_status function, but instead of a ds_map with detailed information, this function returns a string with the current status of the purchase specified by the purchase id. The following text can be returned by this function:

  • "Purchased"
  • "Available"
  • "Unavailable"

Example:

if iap_product_status(p_id) == "Purchased"
{
var list, i;
list = ds_list_create();
iap_product_files(p_id, list);
for (i = 0; i < ds_list_size(list); i += 1)
{
draw_text(x, y + (i * 32), ds_list_find_value(list, i));
}
ds_list_destroy(list);
}

The above code checks the previously stored product id to see if it has been purchased, and if it has it then creates and displays a list of product files that have been downloaded.

Back: In App Purchases

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_purchase_details

Add purchase details of a single product to a ds_map.

Syntax:

iap_purchase_details(product_id, ds_map);

Argument | Description
product_id | The product ID string for the purchase.
ds_map | The ds_map that will store the purchase information.

Returns: N/A

Description

With this function you can populate a previously created ds_map with a number of key/value pairs that describe the purchase details of the given product. The following data is returned within the map:

  • "product" - The product ID string.

  • "order" - The unique order ID, where available (not all stores support this).

  • "token" - The purchase token string, where available (not all stores support this).

  • "payload" - The payload returned by the target store, where available (not all purchases require this, and not all stores support this).

  • "receipt" - The receipt string, where available (not all stores support this).

  • "response" - A response value (as a real number), where available, based on the response values from Google Play (see here for details).

The map will also contain one further key, "status", which can be use to check the current status of the purchase. This key will have one of the following constants as it's value:

Constant | Description
iap_available | Product is available or the game is waiting for the result of a purchase.
iap_failed | The purchase attempt failed.
iap_purchased | The product was successfully purchased.
iap_canceled | The user cancelled the purchase.
iap_refunded | The purchase has been rescinded.

The following notes are related to the "token" and "receipt" keys of the map returned in reference to the target store being used:

  1. For the Amazon Store the purchase "token" and "receipt" entries are treated as one and the same.

  2. For Google Play there is no "receipt" data and you are expected to verify purchases via the returned "payload" (should you be verifying via a payload it is recommended that you do not use hard coded values). gameMaker: Studio will still verify the data signature returned with a purchase by Google Play against the public key provided in the IAP tab of the Global Game Settings.

  3. For Google Play the "token" provided with a purchase is intended for use with consuming purchases.

  4. For iOS and MacOSX target stores there is "receipt" data available for purchases but the associated "token" is generated internally for developer purposes.

NOTE: The ds_map used is not created by the function, meaning that you must create it previously and remove it again from memory when not in use using the appropriate function.

Example:

var p_map = ds_map_create();
var p_index = ds_map_find_value(iap_data, "index");
iap_purchase_details(p_index, p_map);
if ds_map_find_value(p_map, "status") == iap_purchased
{
global.Gold += 100000;
}
ds_map_destroy(p_map);

The above code will create a ds_map and then populate it with the key/value pairs for the purchase with the product ID stored in the variable "p_index", which we get from the special iap_data ds_map which is created exclusively in the IAP Event. If the "status" key returns the constant iap_purchased, it will then set a global variable.

Back: In App Purchases
Next: iap_is_purchased

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_restore_all

Restores all purchases for the game.

Syntax:

iap_restore_all();

Returns: N/A

Description

Restores all purchases to their default status for the game and user. This would be applicable if (for example) the user has changed device or removed the title from their current device and has re-installed the title. This will trigger an IAP Event, of the type iap_ev_restore, and the ds_map iap_data will have the following extra key which can then be checked to make sure that the products and purchases have been successfully restored:

  • "result" - The result as a boolean value, where true indicates a successful restore and false some kind of error.

NOTE: Only the Mac and iOS stores currently provide restore functionality.

Example:

iap_restore_all();

This would request that the target store restores all purchases for the game on the device running it, and it will trigger an IAP Event with the result of the call stored in the special iap_data ds_map.

Back: In App Purchases
Next: iap_acquire

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_status

Allows you to track the status of the in app purchasing system.

Syntax:

iap_status();

Returns: Constant

Description

This function allows you to track the status of the GameMaker: Studio in app purchasing system and returns one of the following constants:

Constant | Description
iap_status_uninitialised | in app purchases have not been activated for your game.
iap_status_unavailable | There is no connection available to the target store.
iap_status_loading | A connection to the target store exits and is being activated.
iap_status_available | Purchases have been activated and the target store is available.
iap_status_processing | There is currently communication between the game and the target store, like when (for example) making a purchase or when restoring a purchase, etc...
iap_status_restoring | On the iOS target, this can be returned while your game is attempting to restore purchases.

Example:

status = iap_status();

The above code requests the store status for the current game, and stores it in a variable for checking.

Back: In App Purchases
Next: iap_enumerate_products

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


iap_store_status

Allows you to quickly check the store status of the IAP system.

Syntax:

iap_store_status();

Returns: String

Description

WARNING! This function has been deprecated.

This function is similar to the iap_status function, but instead of a ds_map with detailed information, this function returns a string with the current status of the store being used by your game. The following text can be returned by this function:

  • "Not Enabled"
  • "Not Available"
  • "Loading"
  • "Available"
  • "Processing Order"
  • "Error" (This means that something went wrong with the transaction itself.)
  • "Failed" (This means that the attempt to retrieve the content_url went wrong.)

Extended Example:

We can use this function to draw the store status in real-time using the data returned from the function iap_event_queue which you would use in the special asynchronous IAP Event. In the Create Event of the instance you would prepare a variable to store the returned value of this function and then in the IAP event have:

var q;
q = iap_event_queue();
if !ds_queue_empty(q))
{
store_status = ds_queue_dequeue(q);
}
else
{
store_status = 0;
}

This will catch any store changes and set a variable to the value returned, and this variable can then be used in the Draw Event:

if store_status == -1
{
draw_text(32, 32, "Store status updated: " + iap_store_status());
}

The above code will now use the iap_store_status function to display to the user the current state of the store.

Back: In App Purchases

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Maths

This section lists the mathematical functions

GameMaker: Studio contains a large number functions to deal with different areas of mathematics. Most of these functions can be found in the sections listed below:

  1. Real Number Functions
  2. Vector Functions

GameMaker: Studio also accepts the boolean constants of true (1) and false (0) and the constant pi (3.141592653589793280(etc)...).

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Real Number Functions

The following functions exist that deal with real numbers.

Real numbers in GameMaker: Studio are considered double-precision floating-point numbers, that is to say that they have a decimal point in them with no fixed number of digits either before or after the point. 2, for example, is a binary integer but 2.0 is a floating point real. This distinction between integers and floats is very important when dealing with cross platform development as the precision of calculations made on a Windows pc is not the same as the precision of those same calculations when made on a mobile device. This means that you should pay particular attention when making comparisons, for example:

if image_index == 1 {do something...}

Now that may appear to work, but due to the way that floating point maths works, it may mean that image_index actually equals 1.00000000001, in which case the comparison will never result in a true result and the code running. These types of errors can be quite hard to debug and so it is always good to be aware of them and to plan ahead and use other means of checking values or to use the appropriate flooring or rounding functions (listed below) to convert the number to check into an integer. For example the above code could be written as:

if floor(image_index) == 1 {do something...}

NOTE: On the YoYo Compiler target platforms (those marked (YYC)), expressions and functions are evaluated from left to right, while on all other target platforms they are evaluated from right to left, meaning that this:

val = max(num, ++num, num++);

will give different results depending on the platform.

We can also use a special function available in GameMaker: Studio to set the epsilon value for floating point maths. When a real number is rounded to the nearest floating point number, the epsilon (also know as "machine epsilon") forms an upper bound on the relative error, and you can set the epsilon value using this special function:

  1. math_set_epsilon
  2. math_get_epsilon

We can split the functions that GameMaker: Studio has for dealing with real numbers into various categories:

Random Functions

These functions all deal with using random numbers and values:

  1. choose
  2. random
  3. random_range
  4. irandom
  5. irandom_range
  6. random_set_seed
  7. random_get_seed
  8. random_use_old_version
  9. randomize

NOTE: When using the random functions, GameMaker: Studio maintains the same random seed every time you start the game. This makes debugging much easier as you are guaranteed that the random functions will always return the same value, however should you not wish this to happen, you must first set a new random seed at the very start of the game, either using randomize or random_set_seed.

Trigonometric Functions

These are all trigonometric functions:

  1. arccos
  2. arcsin
  3. arctan
  4. arctan2
  5. sin
  6. tan
  7. cos
  8. darccos
  9. darcsin
  10. darctan
  11. darctan2
  12. dsin
  13. dtan
  14. dcos
  15. degtorad
  16. radtodeg
  17. lengthdir_x
  18. lengthdir_y

Rounding Functions

These are all functions that round or select values:

  1. round
  2. floor
  3. frac
  4. abs
  5. sign
  6. ceil
  7. max
  8. mean
  9. median
  10. min
  11. lerp
  12. clamp

Miscellaneous Functions

These are various different mathematic functions:

  1. exp
  2. ln
  3. power
  4. sqr
  5. sqrt
  6. log2
  7. log10
  8. logn
  9. int64

Back: Maths
Next: Vector Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


abs

Returns the absolute value of a value.

Syntax:

abs(val)

Argument | Description
val | The number to turn absolute.

Returns: Real

Description

This function returns the absolute value of the input argument, so if it's a positive value then it will remain the same, but if it's negative it will be multiplied by -1 to make it positive.

Example:

x += abs (x - mouse_x)

This will add an amount equal to the absolute value of the current x position of the instance and the mouse x position.

Back: Real Number Functions
Next: sign

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


arccos

Returns the inverse cosine of x.

Syntax:

arccos(x)

Argument | Description
x | The angle (in radians) to return the inverse cosine of.

Returns: Real

Description

Returns the inverse cosine of x, in that if cos(val)=n, arccos(n)=val, and the resulting number will be between pi and 0.

NOTE: This will only accept a number between -1 and 1 (anything else will throw an error).

Example:

val = arccos(0);

This will set val to pi/2.

Back: Real Number Functions
Next: arcsin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


arcsin

Returns the inverse sine of x.

Syntax:

arcsin(x);

Argument | Description
x | The angle (in radians) to return the inverse sine of.

Returns: Real

Description

Returns the inverse sine of x, in that if sin(x)=n, arcsin(n)=x, and the resulting number will be between -pi/2 and pi/2.

NOTE: This will only accept a value between -1 and 1 (anything else will throw an error).

Example:

val = arcsin( 0 );

This will set val to 0.

Back: Real Number Functions
Next: arctan

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


arctan

Returns the inverse tangent of x.

Syntax:

arctan(x);

Argument | Description
x | The angle (in radians) to return the inverse tangent of.

Returns: Real

Description

Returns the inverse tangent of x. This will accept any number as, unlike tan, arctans asymptotes are on the y axis so it just means you'll never get returned a number greater than pi/2 or less than -pi/2.

Example:

val = arctan( 0 );

This will set val to 0.

Back: Real Number Functions
Next: arctan2

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


arctan2

Calculates arctan(y/x) and returns an angle in the correct quadrant.

Syntax:

arctan2(y, x);

Argument | Description
y | The y coordinate to calculate.
x | The x coordinate to calculate.

Returns: Real

Description

This function returns the inverse tangent of an angle y/x, where y = Opposite side of triangle and x = Adjacent side of triangle. Unlike arctan(x) the function arctan2(y, x) is valid for all angles and so may be used to convert a vector to an angle without risking division by zero, and it also returns a result in the correct quadrant.

NOTE: The value returned is in radians, not degrees.

Example:

val = arctan2(1, 1);

This will set val to the correct angle, in this case 0.79.

Back: Real Number Functions
Next: sin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ceil

Returns the given number rounded up to the nearest integer.

Syntax:

ceil(val);

Argument | Description
x | The number to change.

Returns: Integer

Description

This function takes any real number and rounds it up to the nearest integer. Care should be taken with this function as one common mistake is to use it round up a random value and expect it always to be greater than 1, ie:

int = ceil(random(5));

Now, you would expect this code to always give an integer between 1 and 5, but this may not always be the case as there is a very small possibility that the random function will return 0, and rounding up 0 still gives you 0. This is a remote possibility but should be taken into account when using this function.

Example:

val = ceil( 3.4 );

This will set val to 4.

Back: Real Number Functions
Next: max

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


choose

Randomly chooses one of of a set of arguments.

Syntax:

choose(val0, val1, val2... max_val);

Argument | Description
val0... max_val | An input value that can be string, integer, variable or constant.

Returns: One of the given arguments.

Description

Sometimes you want to specify something other than numbers for a random selection, or the numbers you want are not in any real order or within any set range. In these cases you would use choose() to generate a random result. For example, say you want to create an object with a random sprite at the start, then you could use this function to set the sprite index to one of a set of sprites. Note that you can have as many as you require (more arguments will mean that the function will be slower to parse).

NOTE: This function will return the same value every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game.

Example:

sprite_index = choose(spr_Cactus, spr_Flower, spr_Tree, spr_Shrub);
hp = choose(5, 8, 15, 32, 40);
name = choose("John", "Steven", "Graham", "Jack", "Emily", "Tina", "Jill", "Helen");

The above code uses choose to set a number of properties for the instance.

Back: Real Number Functions
Next: random

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clamp

Returns a value clamped between the specified minimum and maximum.

Syntax:

clamp(val, min, max)

Argument | Description
val | The value to clamp.
min | The minimum value to clamp between.
max | The maximum value to clamp between.

Returns: Real.

Description

With this function you can maintain an input value between a specified range.

Example:

speed = clamp(speed, 1, 10);

The above code will clamp the speed so that it never falls below 1 or goes over 10.

Back: Real Number Functions
Next: exp

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


cos

Returns the cosine of val.

Syntax:

cos(val);

Argument | Description
val | The angle (in radians) to return the cosine of.

Returns: Real

Description

In a right angled triangle cos(val) = Adjacent / Hypotenuse where val is one of the three angles. This function will always return a number between 1 and -1.

Example:

val = cos( 0 );

This will set val to 1.

Back: Real Number Functions
Next: darccos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


darccos

Returns the inverse cosine of val, where val is in degrees.

Syntax:

darccos(val)

Argument | Description
x | The angle (in degrees) to return the inverse cosine of.

Returns: Real

Description

Returns the inverse cosine of x, in that if dcos(val)=n, darccos(n)=val, and the resulting number will be between 180 and 0.

NOTE: This will only accept a number between -1 and 1 (anything else will throw an error).

Example:

val = arccos(-1);

This will set "val" to 180.

Back: Real Number Functions
Next: darcsin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


darcsin

Returns the inverse sine of val, where val is in degrees.

Syntax:

darcsin(x);

Argument | Description
val | The angle (in degrees) to return the inverse sine of.

Returns: Real

Description

Returns the inverse sine of x, in that if dsin(x)=n, darcsin(n)=x, and the resulting number will be between -90 and 90.

NOTE: This will only accept a number between -1 and 1 (anything else will throw an error).

Example:

val = darcsin(-1);

This will set "val" to -90.

Back: Real Number Functions
Next: darctan

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


darctan

Returns the inverse tangent of val, where val is in degrees.

Syntax:

darctan(x);

Argument | Description
val | The angle (in degrees) to return the inverse tangent of.

Returns: Real

Description

Returns the inverse tangent of x. This will accept any number as, unlike dtan, darctans asymptotes are on the y axis so it just means you'll never get returned a number greater than 90 or less than -90.

Example:

val = darctan(1);

This will set "val" to -45.

Back: Real Number Functions
Next: darctan2

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


darctan2

Calculates arctan(y/x) and returns an angle in the correct quadrant.

Syntax:

darctan2(y, x);

Argument | Description
y | The y coordinate to calculate.
x | The x coordinate to calculate.

Returns: Real

Description

This function returns the inverse tangent of an angle y/x, where y = Opposite side of triangle and x = Adjacent side of triangle. Unlike darctan(x) the function darctan2(y, x) is valid for all angles and so may be used to convert a vector to an angle without risking division by zero, and it also returns a result in the correct quadrant.

NOTE: The value returned is in degrees, not radians.

Example:

val = darctan2(1, 1);

This will set "val" to the correct angle.

Back: Real Number Functions
Next: dsin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


dcos

Returns the cosine of val, where val is in degrees.

Syntax:

dcos(val);

Argument | Description
val | The angle (in degrees) to return the cosine of.

Returns: Real

Description

In a right angled triangle cos(val) = Adjacent / Hypotenuse where val is one of the three angles. This function will always return a number between 1 and -1.

Example:

val = dcos(45);

This will set "val" to 0.71.

Back: Real Number Functions
Next: degtorad

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


degtorad

Converts the given degrees to radians.

Syntax:

degtorad(deg);

Argument | Description
deg | The degrees to convert.

Returns: Real

Description

In GM all the trigonometric functions work in radians, but most people work in degrees and this means that to convert your degrees into radians you need to use this function. For example, degtorad(180) returns 3.14159265 radians. This function translates degrees into radians using the formula:

angle_radians = angle_degrees * pi / 180

Example:

val = degtorad(90);

This will set val to pi/2.

Back: Real Number Functions
Next: radtodeg

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


dsin

Returns the sine of val, where val is in degrees.

Syntax:

dsin(val);

Argument | Description
val | The angle (in degrees) to return the sine of.

Returns: Real

Description

In a right angled triangle dsin(val) = Opposite / Hypotenuse where "val" is one of the three angles.

Example:

val = dsin(90);

This will set "val" to 1.

Back: Real Number Functions
Next: dtan

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


dtan

Returns the tangent of val, where val is in degrees.

Syntax:

dtan(val);

Argument | Description
val | The angle (in degrees) to return the tangent of.

Returns: Real

Description

In a right angled triangle dtan(val) = Opposite / Adjacent where "val" is one of the three angles.

NOTE: A vast number of values (90, or -90 for example) will error with this function due to their returning infinity, a graph representation of this would produce asymptotes at these values.

Example:

val = dtan(45);

This will set "val" to 1.

Back: Real Number Functions
Next: dcos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


exp

The exponential function.

Syntax:

exp(n);

Argument | Description
n | The power of e.

Returns: Real

Description

This is the function power(e,n), where e is approximately 2.718281828 (also known as Euler's Number), and n is the number of times it should be multiplied by itself. This basically says "how much growth do I get after n units of time (and 100% continuous growth)?". So exp(3) would return 20.08, which means that after 3 time units we have 20.08 times the amount we started with.

Example:

val = exp(2);

This will set val to e^2, around 7.4.

Back: Real Number Functions
Next: ln

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


floor

Returns the given number rounded down to the nearest integer.

Syntax:

floor(n);

Argument | Description
n | The number to floor.

Returns: Real

Description

Returns the floor of n, that is, n rounded down to an integer. This is similar to the round() function, but it only rounds down, no matter what the decimal value, so floor(5.99999) will return 5, as will floor(5.2), floor(5.6457) etc...

Example:

val = floor( 3.9 );

This will set val to 3.

Back: Real Number Functions
Next: frac

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


frac

Returns the decimal part of the given number.

Syntax:

frac(n);

Argument | Description
n | The number to change.

Returns: Real

Description

This function returns the fractional part of n, that is, the part behind the decimal dot. It will return only the decimals behind the dot of a value, so frac(3.125) will return 0.125, frac(6.921) will return 0.921, etc...

Example:

val = frac(3.4);

This will set val to 0.4.

Back: Real Number Functions
Next: abs

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


int64

Attempts to convert a value into a 64bit integer.

Syntax:

int64(val);

Argument | Description
val | The value to convert.

Returns: 64bit integer

Description

This function will attempt to convert a given value into a 64bit integer, where the value must be either a real, a string, an int64, an int32, or a ptr. Anything else will cause the game to crash with an error message. You can check to see if a variable holds an int64 using the function is_int64.

Example:

steam_handle = int64(global.fileReadString);

The above code converts the value held in the global variable to a 64bit integer.

Back: Real Number Functions
Next: exp

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


irandom

Returns a random integer between 0 and n. This includes n if n itself is an integer value.

Syntax:

irandom(n);

Argument | Description
n | The upper range from which the random number will be selected.

Returns: Integer

Description

This very useful function only returns integers (whole numbers). So, for example, to get a random number from 0 to 9 you can use irandom(9) and it will return a number from 0 to 9 inclusive... real numbers can also be used but the upper value will be excluded, so irandom(9.7) will return a value from 0 to 9 only. The function has an upper bound of $7fffffffffffffffLL, so care should be taken if using very large numbers.

NOTE: This function will return the same value every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game.

Example:

if irandom(9) = 1
{
score += 100;
}

This will produce a one in ten (since 0 is included) chance of adding 100 to the score.

Back: Real Number Functions
Next: irandom_range

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


irandom_range

Returns a random integer between n1 and n2.

Syntax:

irandom_range(n1, n2);

Argument | Description
n1 | The low end of the range from which the random number will be selected.
n2 | The high end of the range from which the random number will be selected.

Returns: Integer

Description

This function is similar to random_range() only with integer values as the input. So irandom_range(10, 35) will return an integer between 10 and 35. As with the irandom() function, real numbers can be used, in which case they will be rounded down to the nearest integer EG: irandom_range(6.2,9.9) will give a value between 6 and 9.

NOTE: This function will return the same value every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game.

Example:

score += irandom_range(500, 600);

This will add anywhere between 500 and 600, an integer value, to the total score.

Back: Real Number Functions
Next: random_set_seed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


lengthdir_x

Returns the horizontal x-component of the vector determined by the indicated length and direction.

Syntax:

lengthdir_x(len, dir);

Argument | Description
len | The length away of the point to return.
dir | The direction of the point to return.

Returns: Real

Description

This function seems confusing at first, but it's not really. It is used to get the x component of a position "len" pixels from the starting point and in direction "dir". Imagine a circle around your instance, then imagine a point anywhere on that circle. To move to that point we need to move the object so many pixels in that direction... so this function (when used with lengthdir_y) gets the position of that point on the circle to be used in code by the instance. See the image below for details:

Example:

instance_create(x + lengthdir_x(64, image_angle), y + lengthdir_y(64, image_angle), obj_bullet);

This will create a bullet instance at (x,y), but with 64 pixels added in the direction of image_angle. This is typically used for syncing a bullets start position with the end of a gun in game.

Back: Real Number Functions
Next: lengthdir_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


lengthdir_y

Returns the horizontal y-component of the vector determined by the indicated length and direction.

Syntax:

lengthdir_y(len, dir);

Argument | Description
len | The length away of the point to return.
dir | The direction of the point to return.

Returns: Real

Description

This function seems confusing at first, but it's not really. It is used to get the y component of a position "len" pixels from the starting point and in direction "dir". Imagine a circle around your instance, then imagine a point anywhere on that circle. To move to that point we need to move the object so many pixels in that direction... so this function (when used with lengthdir_x) gets the position of that point on the circle to be used in code by the instance. See the image below for details:

Example:

instance_create(x + lengthdir_x(64, image_angle), y + lengthdir_y(64, image_angle), obj_bullet);

This will create a bullet instance at (x,y), but with 64 pixels added in the direction of image_angle. This is typically used for syncing a bullets start position with the end of a gun in game.

Back: Real Number Functions
Next: round

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


lerp

Returns the linear interpolation of two input values by the given amount.

Syntax:

lerp(a, b, amt)

Argument | Description
a | The first value.
b | The second value.
amt | The amount to interpolate.

Returns: Real.

Description

With this function you can find the value that equates to the position between two other values for a given percentage. So if you do, for example:

lerp(0, 10, 0.5)

you would get the return value of 5, which is 50% of the input values. You can extrapolate using this function too, by supplying a positive or negative value for the interpolation amount so that doing something like:

lerp(0, 10, 2)

will return a value of 20.

Example:

xx = lerp(x, x + hspeed, room_speed);
yy = lerp(y, y + vspeed, room_speed);

The above code uses the linear interpolation function to predict where an instance would have moved to after one second of game time.

Back: Real Number Functions
Next: clamp

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ln

Returns the natural logarithm of the input value.

Syntax:

ln(n);

Argument | Description
n | The input value.

Returns: Real

Description

The natural logarithm ln(n) is the amount of time needed to reach a certain level of continuous growth, where n is the level reached. So if we want to find out how many time units we need to get 20 growth we would use ln(20) which returns 2.99 units of time to get that amount of growth.

Example:

alarm[0] = ln(age) * room_speed;

The above code uses the natural logarithm of the value stored in the variable "age" to set an alarm.

Back: Real Number Functions
Next: power

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


log10

Returns the log base 10 of n.

Syntax:

log10(n);

Argument | Description
n | The input value.

Returns: Real

Description

This function is similar to the log2(n) function, only that log10(n) gets the number of 10's that we need to multiply together to get n. So log10(100) returns 2, as multiplying 10 by itself gives 100, log10(1000) returns 3 as 10x10x10=1000 etc... The number does not have to be divisible by ten, however, but this will still return an appropriate value, for example if we have log10(101) we get 2.00432137... which is how many times you could divide 101 by 10.

Example:

logval = log10(num);

The above code gets the log10 of the value stored in "num".

Back: Real Number Functions
Next: logn

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


log2

Returns the log base 2 of n, the number 2 must be powered by to equal n.

Syntax:

log2(n);

Argument | Description
n | The input value.

Returns: Real

Description

This function basically asks "how many 2's do you need to multiply to get n?". A common example of use in programming would be to calculate the number of bits that are needed to represent a number. To do this we calculate the log2(x) of the number, round it down and add 1 - for example log2(100) returns 6.643856, which rounded down is 6, to which we add one and it gives us 7. So we need 7 bits to represent 100. It can also be used for describing exponential growth or decay, and is often called a binary logarithm.

Example:

colourbits = floor(log2(colour)) - 1;

The above code stores the number of bits needed to represent the value stored in the variable "colour".

Back: Real Number Functions
Next: log10

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


logn

Returns the log base n of val.

Syntax:

logn(n, val);

Argument | Description
n | The log base.
val | The input value.

Returns: Real

Description

This function is similar to the log2(n) and log10(n)functions, only you stipulate the log base value. For example, logn(5,25) will return how many 5's we need to multiply to get 25 (which is 2).

Example:

logval = logn(5, num);

The above code gets the log5 of the value stored in "num".

Back: Real Number Functions
Next: int64

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


math_get_epsilon

Get the "machine epsilon" for floating point calculations.

Syntax:

math_get_epsilon();

Returns: Real

Description

This function will return the current epsilon value for the target platform. For more information on epsilon, please see the function math_set_epsilon().

Example:

var e = math_get_epsilon();

This will retrieve the current epsilon value and store it in a local variable.

Back: Maths
Next: math_set_epsilon

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


math_set_epsilon

Set the "machine epsilon" for floating point calculations.

Syntax:

math_set_epsilon(epsilon);

Argument | Description
epsilon | The new epsilon value (from 0 to 0.999999999).

Returns: Real

Description

Epsilon is a value used to determine whether two numbers subject to rounding error are close enough to be considered "equal". It is useful when dealing with floating point maths as it can reduce the "rounding errors" that make certain operations return values that appear incorrect or contrary to what we expect. For example, we may have added a value to the image index of a sprite and expect the result to be a single integer, but due to the nature of floating point maths, the actual final value ends up being something like 5.0000002, so when we have the following check:

if image_index == 5 {do something}

The code does not behave as expected and returns false. However, if we set the epsilon value to 0.000001, the image_index value will be rounded to the nearest real number that is +/- 0.000001 of the original value, making the above comparison return true.

The epsilon value will be used for all the following integer operators:

  • <: Less than
  • >: Greater than
  • ==: Equal to
  • <=: Less than or equal to
  • >=: Greater than or equal to
  • !=: Not equal to

Note that setting an epsilon value of 0 will disable all rounding, and using a value of 1 will give an error.

Example:

math_set_epsilon(0.0001);

This will set the epsilon value for all further floating point operations.

Back: Maths
Next: math_get_epsilon

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


max

Returns the largest of a set of real value arguments.

Syntax:

max(val1, val2, ... max_val);

Argument | Description
val0 ... max_val | The values to compare.

Returns: Real

Description

This function returns the maximum of the input values, of which it can have as many as you require (note that more arguments will mean that the function will be slower to parse). For example max(12, 96, 32, 75) will return 96 as that is the highest of all the input values.

Example:

x = max(x, 0);

This will stop the player from exiting the left of the room. This works by constantly setting its x to either itself or 0, whichever is larger. If the player exits the left, its x would be smaller than 0 (ie negative), so it'll get set straight back.

Back: Real Number Functions
Next: mean

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mean

Returns the mean (average) of of a set of real value arguments.

Syntax:

mean(val1, val2, ... max_val);

Argument | Description
val0 ... max_val | The values to compare.

Returns: Real

Description

This function works by adding up all the input values and then dividing them by their own number. You can have as many arguments as you require (note that more arguments will mean that the function will be slower to parse). So, mean(2, 6, 9, 32) returns 12.25 as 2+6+9+32=49 and 49/4=12.25.

Example:

xmiddle = mean(obj_player1.x, obj_player2.x, obj_player3.x);
ymiddle = mean(obj_player1.y, obj_player2.y, obj_player3.y);

This will set xmiddle and ymiddle to the x and y coordinates of the average of the coordinates of three player objects, obj_player1, obj_player2 and obj_player3. You could, for instance, use this to keep the game camera focused on all three players instead of just one.

Back: Real Number Functions
Next: median

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


median

Returns the median (middle number) of a set of real value arguments.

Syntax:

median(val1, val2, ... max_val);

Argument | Description
val0 ... max_val | The values to compare.

Returns: Real

Description

This function returns the median of the input values, that is, the middle value. When the number of arguments is even, the smaller of the two middle values is returned and the function can have as many (real number) arguments as you require (note that more arguments will mean that the function will be slower to parse). This means that, for example, median(43, 12, 25, 19, 6) would return 19 as it is the middle value between all the rest.

Example:

x = median( 0, x, room_width );
y = median( 0, y, room_height );

This will stop the player from exiting any side of the room, by using median as a clamp. If the player, for instance, moves to the left of the room boundary, its x will be smaller than 0. This will mean the middle number of the first of the medians will be 0, so the player will be jumped to (0,y).

Back: Real Number Functions
Next: min

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


min

Returns the smallest of a set of real value arguments.

Syntax:

min(val1, val2, ... max_val);

Argument | Description
val0 ... max_val | The values to compare.

Returns: Real

Description

This function returns the minimum of the input values, of which it can have as many as you require (note that more arguments will mean that the function will be slower to parse). For example min(12, 96, 32, 75) will return 12 as that is the lowest of all the input values.

Example:

x = min(x, room_width);

This will stop the player from exiting the right of the room. This works by constantly setting its x to either itself or the room_width variable, whichever is smaller. If the player exits the right, its x would be larger than room_width, so it'll get set straight back.

Back: Real Number Functions
Next: lerp

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


power

Returns the given number to the given power; the number x multiplied by itself n number of times.

Syntax:

power(x, n);

Argument | Description
x | The number to change.
n | How many times to multiply x by itself.

Returns: Real

Description

This will return the value of a number multiplied by itself "n" number of times. For example, power(5,3) will multiply 5 by itself 3 times and return 125, which is the same as saying 5*5*5=125. Please note that the "x" value (the number to change) cannot be a negative value.

Example:

score += power(dmg, 3);

This will add the value of held in the variable "dmg" to the power of 3 to the score variable.

Back: Real Number Functions
Next: sqr

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


radtodeg

Converts radians to degrees.

Syntax:

radtodeg(rad);

Argument | Description
rad | The radians to convert.

Returns: Real

Description

Once you have done your calculations using sin, or cos etc... the result is in radians. This may not always be what you want and so to turn the radians into degrees we use this function. For example, radtodeg(sin(180)) will return -45 degrees. This function translates radians into degrees using the formula:

angle_degrees = angle_radians * 180 / pi;

Example:

val = radtodeg( pi );

This will set val to 180.

Back: Real Number Functions
Next: lengthdir_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


random

Returns a random real number between 0 and n.

Syntax:

random(n);

Argument | Description
n | The upper range from which the random number will be selected.

Returns: Real

Description

This function is good for probabilities where returning an integer (whole number) is not necessary. For example, random(100) will return a value from 0 to 99, but that value can be 22.56473! You can also use real numbers and not integers in this function like this - random(0.5), which will return a value between 0 and 0.4999999.

NOTE: This function will return the same value every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game.

Example:

if random(10) >= 9
{
score += 100;
}

This will produce approximately a one in ten chance of adding 100 to the score.

Back: Real Number Functions
Next: random_range

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


random_get_seed

Returns the current random seed.

Syntax:

random_get_seed();

Returns: Real

Description

To generate a random number GameMaker: Studio starts with a random seed number. With this function you can retrieve that seed, which can then be stored to reproduce a specific series of random events. For example, say you have a procedurally generated game, but want the player to be able to go back to previously discovered areas. Well, at the start of each area, you can store the random seed with this function and so every time you need to go back there, you can use random_set_seed to set the seed to what it was previously and so force GameMaker: Studio to reproduce the same set of "random" functions that it used previously.

Example:

ini_open("Save.ini")
ini_write_real("Levels", string(level), random_get_seed());
ini_close();

The above code will get the random seed and store it in an ini file.

Back: Real Number Functions
Next: random_use_old_version

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


random_range

Returns a random real number between n1 and n2.

Syntax:

random_range(n1, n2);

Argument | Description
n1 | The low end of the range from which the random number will be selected.
n2 | The high end of the range from which the random number will be selected.

Returns: Real

Description

This function returns a random number between the specified range, and this return value does not need to be an integer. For example, random_range(20,50) will return a random number from 20 to 50, but the value may be a real number like 38,65265. Real numbers can also be used as input arguments.

NOTE: This function will return the same value every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game.

Example:

score += random_range(500, 600);

This will add anywhere between 500 and 600, to the total score.

Back: Real Number Functions
Next: irandom

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


random_set_seed

Sets the seed from which random numbers and outcomes are taken.

Syntax:

random_set_seed(val);

Argument | Description
val | The seed to set.

Returns: N/A

Description

To generate a random number GameMaker: Studio starts with a random seed number. With this function you can set that seed to a known value and so "force" the outcome of all random events afterwards to be the same every time the program is run. For example, this function can be used in conjunction with random_get_seed to create procedurally generated content and save the results without having huge savegames (you save the seed only, no need for anything else). Should you need truly random results for everything, you should be using the randomize() function.

NOTE: While this seed will give consistent results on each target platform, results may vary between platforms due to the different way each target works.

Example:

if debug random_set_seed(1);

The above code sets the random seed to 1 only if the variable "debug" is true.

Back: Real Number Functions
Next: random_get_seed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


random_use_old_version

Use the deprecated random number generator or the regular one.

Syntax:

random_use_old_version(flag);

Argument | Description
flag | Use the deprecated seed generator (true) or the regular one (false).

Returns: Real

Description

The GameMaker: Studio random number generation was improved and the previous generator deprecated from use. However if you have a game that requires seeds generated from the old generator, then you will need to use this function to switch the regular generator off and use the deprecated version instead.

Example:

random_use_old_version(true);

The above code will set the random number generator to use the deprecated version.

Back: Real Number Functions
Next: randomize

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


randomize

Sets the seed to a random value.

Syntax:

randomize();

Returns: Real (unsigned 32 bit value)

Description

This function sets the seed to a random value. Should you need to keep a consistent value over a number of runs of a game, you should be using random_set_seed(). Please note, that when using the random number functions in GameMaker: Studio the initial seed is always the same, as this makes tracing errors and debugging far easier. Should you wish to test with true random, you should call this function at the start of your game.

Example:

randomize();

The above code will randomize the seed.

Back: Real Number Functions
Next: arccos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


round

Returns the given number rounded to the nearest integer.

Syntax:

round(n);

Argument | Description
n | The number to round.

Returns: Integer

Description

Just as it says, round() takes a real number and rounds it up or down to the nearest integer. In the special case where the number supplied is exactly a half-integer (1.5, 17.5, -2.5, etc), the number will be rounded to the nearest even value, for example, 2.5 would be rounded to 2, while 3.5 will be rounded to 4. This type of rounding is called bankers rounding and over large numbers of iterations or when using floating point maths, it gives a statistically better rounding than the more traditional "round up if over .5 and round down otherwise" approach.

What this means is that if the fraction of a value is 0.5, then the rounded result is the even integer nearest to the input value. So, for example, 23.5 becomes 24, as does 24.5, while -23.5 becomes -24, as does -24.5. This method treats positive and negative values symmetrically, so is therefore free of sign bias, and, more importantly, for reasonable distributions of values, the expected (average) value of the rounded numbers is the same as that of the original numbers.

Example:

score += round(hp / 5);

The above code will add a rounded integer onto the score value.

Back: Real Number Functions
Next: floor

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sign

Returns the sign of n.

Syntax:

sign(n);

Argument | Description
n | The number to get the sign of.

Returns: Integer

Description

This function returns whether a number is positive, negative or neither and returns 1, -1, 0 respectively. For example - sign(458) will return 1, sign(-5) will return -1 and sign(0) will return 0.

Example:

y += sign(y - mouse_y);

The above code will add 1, -1 or 0 onto y depending on the result of y - mouse_y.

Back: Real Number Functions
Next: ceil

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sin

Returns the sine of val (val in radians).

Syntax:

sin(val);

Argument | Description
val | The angle (in radians) to return the sine of.

Returns: Real

Description

In a right angled triangle sin(val) = Opposite / Hypotenuse where val is one of the three angles.

Example:

val = sin( pi/2 );

This will set val to 1.

Back: Real Number Functions
Next: tan

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sqr

Returns val*val.

Syntax:

sqr(val);

Argument | Description
val | The number to square.

Returns: Real

Description

Multiplies a number by itself and so returns the square of that number. EG: sqr(5) would return 25 since 5*5=25.

Example:

score += sqr(dmg);

The above code will add on the square of the variable "dmg" to the score.

Back: Real Number Functions
Next: sqrt

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sqrt

Returns the square root of val. Val cannot be a negative value.

Syntax:

sqrt(val);

Argument | Description
val | The number to get the square root of.

Returns: Real

Description

If you multiply a number with itself, you get the square of that number, but sometimes you want to do the reverse and get the square root of a number. So to find what number has been multiplied with itself to get any given positive value we use this function. For example: sqrt(9) will return 3 since 3*3=9.

Example:

num = sqrt(exp);

The above code will set the variable "num" to hold the square root of the value contained in "exp".

Back: Real Number Functions
Next: log2

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


tan

Returns the tangent of val.

Syntax:

tan(val);

Argument | Description
val | The angle (in radians) to return the tangent of.

Returns: Real

Description

In a right angled triangle tan(val) = Opposite / Adjacent where val is one of the three angles.

NOTE: The value returned is in radians, not degrees.

Note: Pi/2, (3 pi/2), -pi/2 and a vast number of other values will error with this function due to their returning infinity, a graph representation of this would produce asymptotes at these values.

Example:

val = tan( pi );

This will set val to 0.

Back: Real Number Functions
Next: cos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Vector Functions

This section explains vectors and lists some vector based functions

For an explanation of vectors and normalised vectors you can read the following two sections which give a brief overview of what is a vector and how it can be used in making games:

  1. What Is A Vector?
  2. Normalised Vectors

GameMaker: Studio also has a number of vector-based functions, listed below:

  1. point_direction
  2. point_distance
  3. point_distance_3d
  4. dot_product
  5. dot_product_normalised
  6. dot_product_3d
  7. dot_product_3d_normalised
  8. angle_difference

Back: Maths

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


angle_difference

Returns the difference between two angles.

Syntax:

angle_difference(ang1, ang2)

Argument | Description
ang1 | The first angle to use.
ang2 | The second angle to use.

Returns: Real

Description

This function will return the smallest angle difference between two angles as a value between -180 and 180 degrees (where a positive angle is anti-clockwise and a negative angle clockwise).

Example:

var pd = point_direction(x, y, mouse_x, mouse_y);
var dd = angle_difference(image_angle, pd);
image_angle -= min(abs(dd), 10) * sign(dd);

The above code will get the angle of direction from the instance to the mouse cursor, then get the difference between that angle and the current image_angle, using this value to slowly rotate towards the mouse.

Back: Vector Functions
Next: point_direction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


dot_product

Returns the dot_product of the vectors x1,y1 and x2,y2.

Syntax:

dot_product(x1, y1, x2, y2)

Argument | Description
x1 | The x coordinate of the first vector.
y1 | The y coordinate of the first vector.
x2 | The x coordinate of the second vector.
y2 | The y coordinate of the second vector.

Returns: Real

Description

The dot product is a value expressing the angular relationship between two vectors and is found by taking two vectors, multiplying them together and then adding the results. The name "dot product" is derived from the centered dot "·" that is often used to designate this operation (the alternative name "scalar product" emphasizes the scalar rather than vector nature of the result).

The actual mathematical formula can be written like this:

So, in 2D the dot product of vectors a[x1,y1] and b[x2,2] is x1x2 + y1y2, meaning that the dot_product in GameMaker: Studio is calculated as:

a · b = (x1*x2)+(y1*y2);

The curious thing about the dot product is the relationship it has to the angle formed by the input vectors which can be expressed as:

a · b = (length of a) * (length of b) * cos(angle)

That is to say, the dot product of two vectors will be equal to the cosine of the angle between those vectors, multiplied by the lengths of each of them. Here is an image to illustrate:

There are a few things that we can now state from any two vectors in relation to the result of their dot product:

  • If a and b are perpendicular (at 90 degrees to each other), the result of the dot product will be zero, because cos(ang) will be zero
  • If the angle between a and b are less than 90 degrees, the dot product will be positive (greater than zero), as cos(ang) will be positive
  • If the angle between a and b are greater than 90 degrees, the dot product will be negative (less than zero), as cos(ang) will be negative

So what does this mean for those of us that make games? Well, this mathematical relationship can be used in quite a few circumstances, but the best way to see it is to build an actual scenario and see for yourself what is going on. One of the simplest ways to do this is to generate a simple "line of sight" check for an enemy in, say, a platform game so that the enemy will "see" the player if they are within 90� of either side of their vector normal.

Basically, we have to get the vector normal from the enemy (ie: comprised of a direction and sight distance) and then we need to get the vector of the player to the enemy. We will then get the dot_product of these vectors, and if the result is positive the player has been seen, and if it is negative he hasn't. The actual code to get this working is supplied in the example below.

Example:

var x1, y1, x2, y2;
x1 = lengthdir_x(1, image_angle);
y1 = lengthdir_y(1, image_angle);
x2 = o_Player.x - x;
y2 = o_Player.y - y;
if dot_product(x1, y1, x2, y2) > 0 seen=true else seen=false;

The above code creates a vector using the instances image angle, and then gets the vector of the player object "o_Player" to itself. Finally it calculates the dot product of these two vectors and if it is greater than 0 it sets the variable "seen" to true, and if it is equal to or less than 0 it sets it to "false".

Back: Vector Functions
Next: dot_product_3d

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


dot_product_3d

Returns the dot_product of the vectors x1,y1,z1 and x2,y2,z2.

Syntax:

dot_product_3d(x1, y1, z1, x2, y2, z2)

Argument | Description
x1 | The x coordinate of the first vector.
y1 | The y coordinate of the first vector.
z1 | The z coordinate of the first vector.
x2 | The x coordinate of the second vector.
y2 | The y coordinate of the second vector.
z2 | The z coordinate of the second vector.

Returns: Real

Description

The dot product is a value expressing the angular relationship between two vectors and is found by taking two vectors, multiplying them together and then adding the results. The name "dot product" is derived from the centered dot "·" that is often used to designate this operation (the alternative name "scalar product" emphasizes the scalar rather than vector nature of the result).

The actual mathematical formula can be written like this:

In 2D, the dot product of vectors a[x1,y1] and b[x2,y2] is x1x2 + y1y2, so in 3D, the dot product of vectors a[x1,y1,z1] and b[x1,y1,z1] is x1x2 + y1y2 + z1z2. So, the dot_product_3d in GameMaker: Studio is calculated as:

a · b = (x1*x2) + (y1*y2) + (z1*z2);

The curious thing about the dot product is the relationship it has to the angle formed by the input vectors which can be expressed as:

a · b = (length of a) * (length of b) * cos(angle)

That is to say, the dot product of two vectors will be equal to the cosine of the angle between those vectors, multiplied by the lengths of each of them. Here is an image to illustrate:

There are a few things that we can now state from any two vectors in relation to the result of their dot product:

  • If a and b are perpendicular (at 90 degrees to each other), the result of the dot product will be zero, because cos(ang) will be zero
  • If the angle between a and b are less than 90 degrees, the dot product will be positive (greater than zero), as cos(ang) will be positive
  • If the angle between a and b are greater than 90 degrees, the dot product will be negative (less than zero), as cos(ang) will be negative

So what does this mean for those of us that make games? Well, this mathematical relationship can be used in quite a few circumstances, but the best way to see it is to build an actual scenario and see for yourself what is going on. One of the simplest ways to do this is to generate a simple "height" check for an enemy in, say, a platform game so that the enemy will "see" the player if they are above the plane formed by the enemy normal vector and the 3d floor.

Basically, we are getting the vector normal from the enemy perpendicular to the floor and then we are getting the vector of the player to the enemy. We will then get the dot_product of these vectors, and if the result is positive the player is "above" the enemy floor plane and if it is negative he is below. The actual code to get this working is supplied in the example below.

Example:

var x1, y1, x2, y2;
x1 = 0;
y1 = 1;
z1 = 0;
x2 = o_Player.x - x;
y2 = o_Player.y - y;
z2 = o_Player.z - z;
if dot_product_3d(x1, y1, z1, x2, y2, z2) > 0 above=true else above=false;

The above code creates a vector normal along the instances y (up) axis, and then gets the vector of the player object "o_Player" to itself. Finally it calculates the dot product of these two vectors and if it is greater tan 0 it sets the variable "above" to true, and if it is less than or equal to 0 it sets it to "false".

Back: Vector Functions
Next: dot_product_normalised

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


dot_product_3d_normalised

Returns the normalised dot_product of the vectors x1, y1, z1 and x2, y2, z2.

Syntax:

dot_product_3d_normalised(x1, y1, z1, x2, y2, z2)

Argument | Description
x1 | The x coordinate of the first vector.
y1 | The y coordinate of the first vector.
z1 | The z coordinate of the first vector.
x2 | The x coordinate of the second vector.
y2 | The y coordinate of the second vector.
z2 | The z coordinate of the second vector.

Returns: Real

Description

The dot product is a value expressing the angular relationship between two vectors and is found by taking two vectors, multiplying them together and then adding the results. The name "dot product" is derived from the centered dot "·" that is often used to designate this operation (the alternative name "scalar product" emphasizes the scalar rather than vector nature of the result).

The actual mathematical formula can be written like this:

In 2D, the dot product of vectors a[x1,y1] and b[x2,y2] is x1x2 + y1y2, so in 3D, the dot product of vectors a[x1,y1,z1] and b[x1,y1,z1] is x1x2 + y1y2 + z1z2. So, the dot_product_3d in GameMaker: Studio is calculated as:

a · b = (x1*x2) + (y1*y2) + (z1*z2);

What about the normalised dot product? The normalised dot product has been corrected in such a way as to bring the return value into the range of -1 and 1 (see Normalised Vectors for more detailed information), which is exceptionally useful in many circumstances, particularly when dealing with lighting and other 3D functions.

Example:

var x1, y1, x2, y2;
x1 = 0;
y1 = 1;
z1 = 0;
x2 = o_Player.x - x;
y2 = o_Player.y - y;
z2 = o_Player.z - z;
if dot_product_3d_normalised(x1, y1, z1, x2, y2, z2) > 0 above=true else above=false;

The above code creates a vector normal along the instances y (up) axis, and then gets the vector of the player object "o_Player" to itself. Finally it calculates the dot product of these two vectors and if it is greater tan 0 it sets the variable "above" to true, and if it is less than or equal to 0 it sets it to "false".

Back: Vector Functions
Next: angle_difference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


dot_product_normalised

Returns the normalised dot_product of the vectors x1,y1 and x2,y2.

Syntax:

dot_product_normalised(x1, y1, x2, y2)

Argument | Description
x1 | The x coordinate of the first vector.
y1 | The y coordinate of the first vector.
x2 | The x coordinate of the second vector.
y2 | The y coordinate of the second vector.

Returns: Real

Description

The dot product is a value expressing the angular relationship between two vectors and is found by taking two vectors, multiplying them together and then adding the results. The name "dot product" is derived from the centered dot "·" that is often used to designate this operation (the alternative name "scalar product" emphasizes the scalar rather than vector nature of the result).

The actual mathematical formula can be written like this:

So, in 2D the dot product of vectors a[x1,y1] and b[x2,2] is x1x2 + y1y2, meaning that the dot_product in GameMaker: Studio is calculated as:

a · b = (x1*x2)+(y1*y2);

What about the normalised dot product? The normalised dot product has been corrected in such a way as to bring the return value into the range of -1 and 1 (see Normalised Vectors for more detailed information), which is exceptionally useful in many circumstances, particularly when dealing with lighting and other 3D functions.

Example:

var x1, y1, x2, y2;
x1 = lengthdir_x(1, image_angle);
y1 = lengthdir_y(1, image_angle);
x2 = o_Player.x - x;
y2 = o_Player.y - y;
if dot_product_normalised(x1, y1, x2, y2) > 0 seen=true else seen=false;

The above code creates a vector using the instances image angle, and then gets the vector of the player object "o_Player" to itself. Finally it calculates the dot product of these two vectors and if it is greater than 0 it sets the variable "seen" to true, and if it is equal to or less than 0 it sets it to "false".

Back: Vector Functions
Next: dot_product_3d_normalised

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Normalised Vectors

This section explains what a normalised vector is and how it can be used.

Ordinarily, vectors can be used in many situations but sometimes you want to constrain their value (like when dealing with angles) which is why we normalise them. This is essentially a mathematical trick that is used to convert a vector of length n to a vector of length 1, meaning that the vector components get normalised to be between 0 and 1. These vectors are also called unit vectors:

To calculate a normalised vector, we must first have the original vector components, then use them to get the length of the vector. We then divide each of the vector components by this length to get the normalised vector components which form the normalised vector in which the sum of the squares of all coordinates is equal to 1. Here's how:

First we take the coordinates of the vector and get the components:

vx = (x2 - x1) = (7 - 1) = 6
vy = (y2 - y1) = (4 - 1) = 3

We then use these values to calculate the length of the vector:

len = sqr(vx2 + vy2) = sqr(36 + 9) = sqr(45) = 6.708203932499369

Now, that gives us the exact length of the vector a, so let's use that to normalise the two vector components vx and vy:

vx = (vx/len) = (6 / 6.708203932499369) = 0.8944271909999159
vy = (vy/len) = (3 / 6.708203932499369) = 0.4472135954999579
a = 1

Great! We have now normalised the components of the vector! But of what practical use is that in the context of GameMaker: Studio? Okay, let's give you a practical example...

Say you have a game where the player has to shoot at an enemy and you need to know how much the bullet object has to move along the x and y axis each step to hit it:

For this you would use the player and enemy coordinates to get the vector components and the length, then you would normalise them to get a value between 0 and 1 which you would finally multiply by the speed you wish the bullet to travel at each step. These final two values you would then store and add onto the starting x and y coordinates each step. Sound complicated? It's not, look (values have been rounded to one decimal place for simplicity):

px = 100;
py = 425;
ex = 356;
ey = 83;
bullet_speed = 5;

vx = (ex - px) = 256
vy = (ey - py) = -342

len = sqrt(vx2 + vy2) = sqrt(65536 + 116964) = 427.2

vx = vx / len = 0.6
vy = vy / len = 0.8

speed_x = vx * bullet_speed = 3
speed_y = vy * bullet_speed = 4

So, to hit the target we need to add 3 to the bullets x coordinate and 4 to its y coordinate every step.

Back: Vector Functions
Next: What Is A Vector?


point_direction

Returns the direction, in degrees, of a vector comprised.

Syntax:

point_direction(x1, y1, x2, y2)

Argument | Description
x1 | The x coordinate of the first component of the vector
y1 | The y coordinate of the first component of the vector
x2 | The x coordinate of the second component of the vector
y2 | The y coordinate of the second component of the vector

Returns: Real

Description

This function returns the direction of a vector formed by the specified components [x1,y1] and [x2,y2] in relation to the fixed x/y coordinates of the room. For example, in the image below if we want to get the direction from the player ship position to the enemy position so that we can fire a missile at the enemy then we would use this function (the exact code is in the example below the image):

Example:

var ex, ey;
ex = instance_nearest(x, y, enemy).x;
ey = instance_nearest(x, y, enemy).y;
with (instance_create(x, y, obj_Missile))
{
direction = point_direction(x, y, ex, ey);
}

The above code will get the x and y coordinates of the nearest enemy and then pass them to a bullet object to use in the point_direction function to set its direction of travel correctly.

Back: Vector Functions
Next: point_distance

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


point_distance

Returns the length of a vector comprised of the specified components.

Syntax:

point_distance(x1, y1, x2, y2);

Argument | Description
x1 | The x coordinate of the first component of the vector
y1 | The y coordinate of the first component of the vector
x2 | The x coordinate of the second component of the vector
y2 | The y coordinate of the second component of the vector

Returns: Real

Description

This function returns the length of a vector formed by the specified components [x1,y1] and [x2,y2]. For example, in the image below if we want to get the distance between the player ship position and the enemy position so that we can calculate if the enemy is close enough to shoot at then we would use this function (the exact code is in the example below the image):

Example:

var ex, ey;
ex = instance_nearest(x, y, enemy).x;
ey = instance_nearest(x, y, enemy).y;
if point_distance(x, y, ex, ey) < 200
{
instance_create(x, y, obj_Missile)
}

The above code will get the x and y coordinates of the nearest enemy and then use them to check the distance (length) of the vector formed by them and the player coordinates. If the value is less than 200, the player object will create an instance of "obj_Missile".

Back: Vector Functions
Next: point_distance_3d

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


point_distance_3d

Returns the length of a vector comprised of the specified components.

Syntax:

point_distance_3d(x1, y1, z1, x2, y2, z2);

Argument | Description
x1 | The x coordinate of the first component of the vector
y1 | The y coordinate of the first component of the vector
z1 | The z coordinate of the first component of the vector
x2 | The x coordinate of the second component of the vector
y2 | The y coordinate of the second component of the vector
z2 | The z coordinate of the second component of the vector

Returns: Real

Description

This function takes the supplied components of the vector and returns the length (distance) of the vector. It works in exactly the same way as point_distance() but with the addition of factoring in the z value (depth) for use in 3D space.

Example:

var inst, ex, ey, ez;
inst = instance_nearest(x, y, enemy);
if inst
{
ex = inst.x;
ey = inst.y;
ez = inst.z;
if point_distance_3d(x, y, z, ex, ey, ez) < 200
{
instance_create(x, y, obj_Missile)
}
}

The above code will get the x and y and z coordinates of the nearest enemy and then use them to check the distance (length) of the vector formed by them and the player coordinates. If the value is less than 200, the player object will create an instance of "obj_Missile".

Back: Vector Functions
Next: dot_product

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


What Is A Vector?

This section explains what a vector is.

At some point when creating a game of any complexity you will probably have to deal with vectors. They are used in physics, in AI, in trigonometry and many other situations, but what is a vector? Well, to put it simply, a vector is a directed quantity. Let's start by looking at a 1 dimensional vector, which is just the same as a single number, by drawing a numbered line with an arrow starting at zero and ending at 5. This is the vector a which is equal to 5 and if we draw another arrow starting at the 5 and ending at the 8 we have vector b which is equal to 3.

You should realise that it doesn't matter where a vector starts, all that matters is how long it is and what direction it goes in. So vector b starts at 5, is 3 units long and points to the "right", making it identical to a vector starting at 0 and going to 3. Now, you can also add these vectors together, by putting the two vectors a and b end to end to get the vector c which is equal to 8. What about negative numbers? Well, if, in the above image, a vector that points to the "right" corresponds to a positive number, you can see that a vector pointing to the "left" would correspond to a negative number, making a one-dimensional vector nothing more than a signed (+/-) number. This explains the essential concept of a vector: only length and direction ("left" or "right" in this case) count, not position.

So, what about 2 dimensional vectors? Well, we can think of them as consisting not just of "left" and "right, but "up" and "down" too:

Now, those are not actually vectors yet as we still have to reduce them down using their start and end coordinates. Looking at vector a we can see it has a start coordinate of [2,2] and an end coordinate of [4,3] and so to get the vector from this we need to reduce it down by subtracting the end coordinates from the start coordinates like this: [(x2-x1), (y2-y1)] = [(4-2), (3-2)] = [2,1]. Let's do the same for vector b now: [(-1.2 -(-3.2)) ,(2.1 - 1.1)] = [2 ,1]. Notice something? Those two vectors are the same! This is yet another demonstration that a vector has no position, only direction and length, and we can draw those vectors relative to each other around a local [0,0] axis:

This means that a 2D vector is defined by two values, an x and a y position relative to the local [0,0] axis. And what about 3D vectors? Well, they have the added dimension of "depth" to contend with and would be calculated as positions x, y and z around a local axis something like this:

Back: Vector Functions
Next: Normalised Vectors

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Miscellaneous Functions

This section deals with un-categorised functions and constants.

The following functions and variables are special ones that GameMaker: Studio supports but which don't fit into any particular category:

  1. game_id
  2. game_save_id
  3. game_display_name
  4. game_project_name
  5. game_end
  6. game_restart
  7. game_load
  8. game_load_buffer
  9. game_save
  10. game_save_buffer
  11. script_exists
  12. script_get_name
  13. script_execute
  14. gml_release_mode
  15. gml_pragma
  16. parameter_count
  17. parameter_string
  18. environment_get_variable
  19. external_define
  20. external_call
  21. external_free
  22. cursor_sprite
  23. alarm_set
  24. alarm_get
  25. GM_build_date
  26. GM_version

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


alarm_get

Get the value of a given alarm.

Syntax:

alarm_get(index);

Argument | Description
index | The alarm index to get, from 0 to 11.

Returns: Real

Description

This function can be used to get the current value of the given alarm. You supply the alarm number from 0 to 11 and this function will return the value that the alarm is currently on. This is an alternative method to getting the alarm array value directly.

Example:

for (var i = 0; i < 12; i++)
{
if alarm_get(i) > 0 alarm_set(i, -1);
}

The above code checks all the alarms in the calling instance and if they are greater than 0 it sets them to -1, stopping them from counting down any further.

Back: Miscellaneous
Next: GM_build_date

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


alarm_set

Set an alarm to the given value.

Syntax:

alarm_set(index, value);

Argument | Description
index | The alarm index to set, from 0 to 11.
value | The value (an integer) to set the alarm to.

Returns: N/A

Description

This function can be used to set an alarm. You supply the alarm number from 0 to 11, and then the value to set the alarm to. The value must be an integer value, and you can set it to -1 to stop the alarm. This is an alternative method to setting the alarm array directly.

Example:

for (var i = 0; i < 12; i++)
{
if alarm_get(i) > 0 alarm_set(i, -1);
}

The above code checks all the alarms in the calling instance and if they are greater than 0 it sets them to -1, stopping them from counting down any further.

Back: Miscellaneous
Next: alarm_get

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


cursor_sprite

Assigns a sprite to act as a cursor.

Syntax:

cursor_sprite;

Returns: Real

Description

Setting this variable will instruct GameMaker: Studio to use the designated sprite as a cursor (basically setting it to the current mouse x/y position every step). The default value is -1 which is no sprite for the cursor, but you can assign any sprite index from the game assets or that has been imported from an external resource. Please note that there is no way to control the animation speed or image_index, so if the sprite has sub-images, these will be cycled at the same speed as the room speed. To remove the cursor sprite, you can set this variable to -1 again.

It is also worth noting that this variable does not replace the game window cursor, and that it will still be drawn as normal. To avoid this you can use the function window_set_cursor and set it to the constant cr_none which will make the standard cursor invisible.

Example:

cursor_sprite = spr_CustomCursor;

The above code will set the sprite indexed in the variable "spr_CustomCursor" to be the cursor sprite for the game.

Back: Miscellaneous
Next: alarm_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


environment_get_variable

Returns the value of the given environment variable.

Syntax:

environment_get_variable(name);

Argument | Description
name | The name (a string) of the environment variable to check.

Returns: String

Description

This function returns the value (a string) of the environment variable with the given name (also a string).

NOTE: This is a Windows only function.

Example:

e_str = environment_get_variable("APPDATA");

The above code will return the full path for the environment variable "%appdata%", which in Windows XP is normally "C:\Documents and Settings\{username}\Application Data" and in Windows Vista/7 "C:\Users\{username}\AppData\Roaming".

Back: Miscellaneous
Next: external_define

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


external_call

Call a previously defined external function.

Syntax:

external_call(id, args[0...15]);

Argument | Description
id | The name of the function that you want to call
args[0...10] | The different arguments that you want to pass through to the external function

Returns: Real or String

Description

If you have created an external function call to a dll or dylib using external_define, you can use this function to then call it. You supply the name of the previously defined function as well as each of the arguments it requires (each argument must be of the correct type, either real or string) and the function returns the result of the external call.

Example:

a = external_call("MyMin", x, y);

The above example code calls a previously defined external function and stores the returned value in a variable.

Back: Miscellaneous
Next: external_free

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


external_define

Defines an external function.

Syntax:

external_define(dll, name, calltype, restype, argnumb, argtype[0], argtype[1], ...argtype[10]) ;

Argument | Description
dll | The name of the dll file (string)
name | The name of the function (string)
calltype | The calling convention used
restype | The type of the result to expect
argnumb | The number of arguments (0 - 10)
argtype[0 ... 10] | The different types of arguments being used

Returns: N/A

Description

This function can be used to define an external function call to a specific dll (for Windows) or dylib (for Mac). This file can be either an included file or part of an extension. You supply the name (and path) of the file, then the name of the function that you wish to define. Next you need to define the calling convention to be used (see the constants list below) as well as the type of result to be expected (also a constant, as listed below). Finally you must give the number arguments that the function can take (from 0 to 15) and for each of the arguments you must specify its type too. Please note that for functions with 4 or more arguments, all of them must be of type ty_real.

NOTE: This is only for dll or dylib that have been added as "Included Files" to the GameMaker: Studio IDE. It will not work with those files added as extensions, since those require that you define the functions in the extension package itself.

Constant | Description
dll_cdecl | This is the default C, C++ call
dll_stdcall | This is the standard WinAPI call (Windows dll only)
ty_real | A real number argument
ty_string | a null-terminated string argument

Example:

external_define('MyDLL.dll', 'MyMin', dll_cdecl, ty_real, 2, ty_real, ty_real);

The above example code will define an external function called "MyMin" with two arguments.

Back: Miscellaneous
Next: external_call

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


external_free

Frees the DLL with the given name.

Syntax:

external_free(id);

Argument | Description
id | The name of the dll or dylib that you want to free

Returns: N/A

Description

This function frees the memory associated with the dll or dylib with the given name. This should be done whenever the file in question is no longer needed in the game, normally (for example) in an end of game event.

Example:

external_free("MyDLL.dll");

The above example code will free the memory associated with the given dll.

Back: Miscellaneous
Next: cursor_sprite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_display_name

Returns the game name string as defined in the Global Game Settings.

Syntax:

game_display_name

Returns: String

Description

This read only variable returns the display name of your game for the target platform, as set in the Global Game Settings.

NOTE: This is a Pro version only variable, and on the regular version it will always return "Made With GameMaker: Studio".

Example:

var name = game_display_name;
var ver = string(GM_version);
draw_text(32, 32, name + ":" + ver);

The above code gets the display name and the version number of the game and draws them.

Back: Miscellaneous
Next: game_project_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_end

Closes the game.

Syntax:

game_end();

Returns: N/A

Description

With this function you can end the game (and the Game End Event will be triggered). This will not happen instantaneously, but rather at the end of the current step, so any code you have in the same step after this function has been called will still run. Please note that this function has the following restrictions:

  • It will report an error on the iOS module as it is against the conditions of their respective Marketplaces.
  • It will silently fail on the HTML5 module.
  • It will work on Windows (including Steam Workshop), Android, Linux and Mac.

Example:

if keyboard_check_pressed(vk_escape) game_end();

This would end the game if the player presses the "escape" key.

Back: Miscellaneous
Next: game_restart

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_id

Returns the unique game identifier.

Syntax:

game_id

Returns: Real

Description

This read only variable returns the unique identifier for the game you have created. You can use this if you need a unique file name, or anything else that needs something to identify your game only. This can be set in the Global Game Settings.

Example:

ini_open("Score.ini");
ini_write_real("Scores","0",score + game_id);
ini_close();

The above code performs a very basic encryption on the score by adding the game_id to it before saving. On reading it back into the game you would deduct the game_id to get the correct value again.

Back: Miscellaneous
Next: game_save_id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_load

Loads a saved game from a file.

Syntax:

game_load(filename);

Argument | Description
filename | The name of the file to load.

Returns: N/A

Description

With this function you can load a game that has been saved previously (using game_save).

Example:

if keyboard_check_pressed(ord("L"))
{
if global.Save game_load("Save.dat");
}

The above code will load a previously saved game if the global variable is true when the player presses the "L" key.

Back: Miscellaneous
Next: game_load_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_load_buffer

Loads a saved game state from a buffer.

Syntax:

game_load_buffer(buffer);

Argument | Description
buffer | The buffer id to load from.

Returns: N/A

Description

With this function you can load a game state that has been saved previously. The game is loaded from a previously created "grow" buffer (see Buffers) and the buffer must have had a game state saved to it using game_save_buffer function.

Example:

if keyboard_check_pressed(ord("L"))
{
if global.Checkpoint game_load_buffer(save_buff);
}

The above code will load a previously saved game state from the buffer indexed in the variable "save_buff", only if the global variable is true, when the player presses the "L" key.

Back: Miscellaneous
Next: game_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_project_name

Returns a safe version of the game display name.

Syntax:

game_project_name

Returns: String

Description

This read only variable returns the display name of your game for the target platform in a "save-friendly" format for the target platform. If the display name contains any characters that are not permitted for a file name, they will be replaced automatically with "_". The display name can be set in the Global Game Settings. Note that since there are no restrictions on file names for HTML5, this string will probably be the same as that returned by game_display_name.

Example:

var file = game_project_name + ".ini";
ini_open(file);
ini_write_real("Scores", "Highscore", score);
ini_close();

The above code gets the project name and uses this to open (or create) an ini file which is then written to.

Back: Miscellaneous
Next: game_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_restart

Restarts the game.

Syntax:

game_restart();

Returns: N/A

Description

With this function you can restart the game. This is essentially the same as running the game for the first time and so the Game Start Event will be triggered, as well as the Game End Event. However it should be noted that global variables will not be re-initialised unless explicitly coded as such - for example, the built-in global variable score will not start at zero after a game restart if it has been modified in the game already. This is also the case for GPU state (so if you have set the draw colour or alpha, for example, it will remain at the changed value).

Example:

if keyboard_check_pressed(ord("R")) game_restart();

This would restart the game when the player presses the "R" key.

Back: Miscellaneous
Next: game_load

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_save

Save a game to a file.

Syntax:

game_save(filename);

Argument | Description
filename | The name of the file to save the game to.

Returns: N/A

Description

With this function you can do a basic save of the game to a given file.

NOTE: This function is very limited and it is designed for the beginner to get a save system up and running quickly, but more advanced users may prefer to code their own system using the File functions, due to the fact that the game will not save any of the dynamic resources like data structures, surfaces, added backgrounds and sprites etc..

Example:

if keyboard_check_pressed(ord("S"))
{
global.Saved = true;
game_save("Save.dat");
}

The above code will set a global variable to true and then saves the game to the file "Save.dat" when the key "S" is pressed.

Back: Miscellaneous
Next: game_save_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_save_buffer

Saves a game state to a given buffer.

Syntax:

game_save_buffer(buffer);

Argument | Description
buffer | The buffer id to save to.

Returns: N/A

Description

With this function you can save the current state of the game to a previously created "grow" buffer (see Buffers) which can then be loaded again at any time using game_load_buffer function. This function is designed for use in a single room at a time (ie: it's not advised to do a buffer save in one room, then try and load the buffer from another one) and should ideally be used only for checkpoints or level restarts.

NOTE: This function is very limited and it is designed for the beginner to get a checkpoint system up and running quickly, but more advanced users may prefer to code their own system using the File functions, due to the fact that the game will not save any of the dynamic resources like data structures, surfaces, added backgrounds and sprites etc..

Example:

if keyboard_check_pressed(ord("S"))
{
global.Checkpoint = true;
game_save_buffer(save_buff);
}

The above code will set a global variable to true and then save the current game state to the buffer indexed in the variable "save_buff" when the key "S" is pressed.

Back: Miscellaneous
Next: script_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


game_save_id

Directory ID of the location where the game files are saved to.

Syntax:

game_save_id

Returns: String.

Description

This read-only variable will return the full path ID of the directory that is used by your game to save files to. This directory may or may not be visible to other applications, depending on the platform, and on the HTML5 target it will return an empty string.

NOTE: This variable purely for information and should not be used to get a file path or anything else similar, as it will not work correctly across all platforms.

Example:

save_dir = game_save_id;

This will store the directory for saving files to a variable for future use.

Back: Miscellaneous
Next: game_display_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


GM_build_date

Holds the date/time value generated when the executable was compiled.

Syntax:

GM_build_date;

Returns: Real

Description

This constant holds the date and time on which the executable being run was built by GameMaker: Studio. The value can be parsed using the Date and Time functions and is taken from the system UTC value at compile time.

Example:

draw_text(32, 32, date_time_string(GM_build_date));
draw_text(32, 64, "v" + GM_version);

The above code will draw the version number for the game and the date and time it was compiled on.

Back: Miscellaneous
Next: GM_version

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


GM_version

Holds the version number as defined in the Global Game Settings.

Syntax:

GM_version;

Returns: String

Description

This constant hold the version number as defined in the Global Game Settings for each target platform. The value is stored as a string.

Example:

draw_text(32, 32, date_time_string(GM_build_date));
draw_text(32, 64, "v" + GM_version);

The above code takes the GM date and version constants and draws them to the screen.

Back: Miscellaneous
Next: game_id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gml_pragma

Set the project to compile using the given command.

Syntax:

gml_pragma(command, [optional...]);

Argument | Description
command | A string with one of the commands listed below.
[optional...] | Some of the available commands require an optional argument or arguments. These are explained below for each command.

Returns: N/A

Description

The gml_pragma function affects how the YYC target compiles your code and should be called with the different commands to further optimise the final compilation of your project. These commands are effectively pre-processed before the game is compiled and so the function can be placed anywhere in your project and it will still be processed before the game is fully compiled. The available commands are as follows:

  • "forceinline" - When the function is called with the "forceinline" pragma in a script resource, the YYC will compile the project with the script inline, rather than referenced. This will give a further processing boost, but care must be taken when using it as it will also inflate the final executable file size, especially if the in-lined code is large and/or used in multiple different places, as well as greatly increase the compile time.

  • "global", "[gml code]" - The "global" pragma permits you to call some GML code before anything else and will execute the second GML string at a global scope, before the first room of the game executes. For example:

    gml_pragma("global", "scr_Init()");

    This will call the script "scr_Init" before the first room of the game is run.

  • "PNGCrush" - The "PNGCrush" pragma will use the PNGCrush program on each texture created. Note that this can add significantly to the time that it takes to compile the game, so you don't want it on all the time, although it can make significant savings on final file size.

  • "Texgroup.Scale", "[TextureGroupName]", "[Scale Divisor]" - The "Texgroup.Scale" will scale the given texture group on compile. You need to give an additional two arguments here: the "[TexGroupName]", which is the name (a string) of the texture group to scale, and the "[Scale Divisor]" (also a string), which is the divisor you wish to use for the scaling, i.e:

    gml_pragma("Texgroup.Scale", "level1", "2");

    This will half all the textures in the "level1" texture group.

Example:

gml_pragma("forceinline");

The above example code will force the script where it is used to be in-lined on compile.

Back: Miscellaneous
Next: parameter_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gml_release_mode

Set the compiler to use release mode or development mode.

Syntax:

gml_release_mode(flag);

Argument | Description
flag | Either true to set release mode or false for general development.

Returns: N/A

Description

When your game is compiled, it also includes certain internal functions to error check while running. These internal checks cover many aspects of a games code, including ranges, parameters and some general aspects of the internal GML compiler and are what spawn the final error messages in many cases. However this function can be used to switch these internal checks off (ie: remove them completely from the compiled game), giving a speed boost to your final project.

Please note that this means that should you do something in your game code that is incorrect, the compiled game may simply crash, or it may experience some very unexpected behaviour. For example, if a ds_grid is accessed at a coordinate outside of the defined size, in developer mode you would get a compiler window error message but the checks in place would permit the game to continue running. However in release mode these checks will not be there and so the code could return either a NULL pointer, or a bad pointer which in turn will point to some random memory. So at best you could get the wrong data returned, or at worst you could overwrite something in memory - data, graphics, or even code itself.

Example:

gml_release_mode(true);

The above example code will set the game to use release mode when compiled.

Back: Miscellaneous
Next: gml_pragma

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


parameter_count

Returns the number of command-line parameters.

Syntax:

parameter_count();

Returns: Real

Description

Command-line parameters are those extra commands that you can add to an exe to change how the program is run. You can find the number of parameters for the current game using this function, where the first parameter has index 1 and the last one has the index returned by the function (a value of 0 is special on that it is the filename of the game executable, including the path). It should be noted that this function will work for on the HTML5 platform, retrieving the url parameters.

Example:

p_num = parameter_count();

The above code will store the number of command-line parameters that have been used for the game in the variable "p_num".

Back: Miscellaneous
Next: parameter_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


parameter_string

Returns the specified command-line parameter.

Syntax:

parameter_string(n);

Returns: String

Description

Command-line parameters are those extra commands that you can add to an exe to change how the program is run and with this function you can get the chosen command-line parameter as a string. You can find the number of parameters for the current game using the function parameter_count, where the first parameter has index 1 and the last one has the index returned by the function (a value of 0 is special on that it is the filename of the game executable, including the path). It should be noted that this function will work for on the HTML5 platform, retrieving the url parameters.

Example:

var p_num;
p_num = parameter_count();
if p_num > 0
{
var i;
for (i = 0; i < p_num; i += 1)
{
p_string[i] = parameter_string(i + 1);
}
}

The above code will get the number of command-line parameters, and if there is 1 or more it will loop through them and store them as strings in an array.

Back: Miscellaneous
Next: environment_get_variable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


script_execute

Execute the script with index scr with the given arguments

Syntax:

script_execute(scr, arg0, arg1, arg2, ...);

Argument | Description
scr | the name of the script that you want to call
arg0 ... arg14 | The different arguments that you want to pass through to the script

Returns: Will depend on the return value from the script being called.

Description

There are times that you may want to pass a script to an instance in a dynamic way, and for these cases we provide the script_execute function. It will run a user created script resource and pass up to 15 arguments to that script. For more information about scripts, see Advanced Use: Scripts. If the script has a return value, then this function will also return that value when called.

Example:

script_execute(choose(scr_Up, scr_Down, scr_Left, scr_Right), irandom(5));

The above example code will use script_execute to choose one of four user created script resources (in this case related to movement) and pass a random integer to it as argument0.

Back: Miscellaneous
Next: gml_release_mode

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


script_exists

Returns whether a script with the given index exists.

Syntax:

script_exists(scr);

Argument | Description
scr | The name of the script that you want to check.

Returns: Boolean

Description

This function will return true or false depending on whether the script with the given index exists. Note, that this is not a string, but rather the asset name which holds the unique index for each script (as it would appear in the IDE). For more information on scripts, see Advanced Use: Scripts.

Example:

script[0] = -1;
script[1] = scr_AI_Left;
script[2] = scr_AI_Right;
var script_num = choose(0, 1, 2);
if script_exists(script[script_num])
{
script_execute(script[script_num]);
}

The above example adds two scripts and a value into an array, then proceeds to get a random number and use that to choose a script to run, unless the real is chosen in which case nothing will happen.

Back: Miscellaneous
Next: script_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


script_get_name

Returns the name of the script with the given index.

Syntax:

script_get_name(scr);

Argument | Description
scr | The index of the script that you want to get the name of.

Returns: String

Description

This function will return the name as a string of the specified script. This name is the one that has been specified for the script in the resource tree of the main GameMaker: Studio window. For more information about scripts, see Advanced Use: Scripts.

Example:

scr_name = script_get_name(scr_Help_File);

The above example code will store the name of the indicated script index in the variable "scr_name".

Back: Miscellaneous
Next: script_execute

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Mouse, Keyboard and Other Controls

This section of the manual has all the functions relating to user input from devices.

The fundamental thing that makes a game a game is the interaction with the player. This is achieved by a variety of means, with the keyboard and mouse on computers and through touch and tilting on mobile devices. The standard way of doing this in GameMaker is to put actions in mouse or keyboard events, but sometimes you need more control, especially when creating something for mobile devices or HTML5. For that you can use the mouse and keyboard functions to get which buttons have been pressed or released as well as simulating the touches on a screen, and there are a couple of specific functions relating to the tilt controls that most mobile devices have too.

The following sections deal with the main user input devices for developing games with GameMaker: Studio:

  1. Virtual Keys
  2. Keyboard Input
  3. Mouse Input
  4. Device Input
  5. GamePad Input

On the Windows target platform, you can also access the legacy joystick functions. However, unless you are porting an older game made with a previous version of GameMaker, it is recommended that you use the newer gamepad functions (above). The joystick functions can be found here:

  1. Joystick Input (Windows Only)

Finally, you also have haptics available to you if you are targeting Android devices. This is covered in the following section:

  1. Immersion Haptics (Android Only)

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Device Input

This section deals with multi touch input for devices.

When your game is being targeted at those platforms that permit multi-touch, you should be using these functions. They work the same way a PC would work if it had multiple mice attached and the constants that are being checked for are the same as those used for the standard mouse functions:

Constant | Description
mb_left | The left mouse button
mb_middle | The middle mouse button (this may not be valid for all target platforms)
mb_right | The right mouse button
mb_none | No mouse button
mb_any | Any of the mouse buttons

NOTE: On touch screen devices, a double tap is returned as the equivalent of a right mouse button event. So, if you need to detect multiple taps in quick succession, for example, you will need to check for both the mb_left and mb_right. This functionality can be toggled on or off using device_mouse_dbclick_enable.

Below you can find a list of all the device specific control functions:

  1. device_mouse_check_button
  2. device_mouse_check_button_pressed
  3. device_mouse_check_button_released
  4. device_mouse_dbclick_enable
  5. device_mouse_x
  6. device_mouse_y
  7. device_mouse_raw_x
  8. device_mouse_raw_y
  9. device_mouse_x_to_gui
  10. device_mouse_y_to_gui
  11. device_is_keypad_open
  12. device_get_tilt_x
  13. device_get_tilt_y
  14. device_get_tilt_z

Please note that on mobile devices (Android, iOS), you can use the back button at any time, as it is mapped to the keyboard backspace which is the GameMaker: Studio keyboard constant vk_backspace, so you can do checks for that key and perform actions on those devices as if the back button had been used.

Back: Mouse, Keyboard and Other Controls

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_get_tilt_x

This function returns the amount of tilt on the x axis of your device.

Syntax:

device_get_tilt_x()

Returns: Real

Description

This function returns a value between -1 and 1 depending upon the angle of "tilt" of the device. The actual correlation between degrees of tilt and the value returned depends on the device and OS that it uses, but generally a value of 1 or -1 is the same as +/-90°. The image below shows how each if the available functions relates to the device:

Example:

if display_get_orientation() = display_landscape
{
x += sign(device_get_tilt_y());
}
else
{
x += sign(device_get_tilt_x());
}

The above code checks the orientation of the display and then uses the corresponding tilt value to move the player along the x axis.

Back: Device Input
Next: device_get_tilt_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_get_tilt_y

This function returns the amount of tilt on the x axis of your device.

Syntax:

device_get_tilt_y()

Returns: Real

Description

This function returns a value between -1 and 1 depending upon the angle of "tilt" of the device. The actual correlation between degrees of tilt and the value returned depends on the device and OS that it uses, but generally a value of 1 or -1 is the same as +/-90°. The image below shows how each if the available functions relates to the device:

Example:

if display_get_orientation() = display_landscape
{
x += sign(device_get_tilt_y());
}
else
{
x += sign(device_get_tilt_x());
}

The above code checks the orientation of the display and then uses the corresponding tilt value to move the player along the x axis.

Back: Device Input
Next: device_get_tiltyz

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_get_tilt_z

This function returns the amount of tilt on the x axis of your device.

Syntax:

device_get_tilt_z()

Returns: Real

Description

This function returns a value between -1 and 1 depending upon the angle of "tilt" of the device. The actual correlation between degrees of tilt and the value returned depends on the device and OS that it uses, but generally a value of 1 or -1 is the same as +/-90°. The image below shows how each if the available functions relates to the device:

Example:

y += sign(device_get_tilt_z());

The above code uses the tilt value to move the player along the y axis.

Back: Device Input

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_is_keypad_open

Checks the device to see if a keypad is open or not.

Syntax:

device_is_keypad_open

Returns: Boolean

Description

This does a check of the device for a keypad and if one is available it returns true otherwise it returns false. Please note that this function is mainly for use with Android devices.

For those users with a Sony Xperia Play, there is a set button/key map setup within GameMaker: Studio, so you can use the keyboard constants vk_up, vk_down, vk_left, vk_right for the joypad keys and Triangle is ord('T'), Square is ord('S'), Circle is vk_alt + vk_backspace while the back button is simply vk_backspace, Cross is vk_space, Select is vk_return and Start is vk_rshift, the L Trigger is ord('L') and R Trigger is ord('R').

Example:

if device_is_keypad_open()
{
global.Setting = 2;
}
else
{
global.Setting = 1;
}

The above code checks for a keypad then changes a global variable depending on the returned value.

Back: Device Input
Next: device_get_tilt_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_check_button

Returns whether a given device button is currently down.

Syntax:

device_mouse_check_button(device, button);

Argument | Description
device | The device (from 0 - 4) that is being checked.
button | The button of the device that is being checked.

Returns: Boolean

Description

This function returns true (1) or false (0) depending on whether the device that you specify is being used or not. Now, the device refers to the mouse number, which can be from 0 to 4 and this event is triggered when the touch screen of a mobile device is touched, so in this way you can test for up to 5 different screen touches (or mouse devices). This function constantly updates every step, and the standard constants of mb_left and mb_right can be used to check for either button.

Example:

if device_mouse_check_button(0, mb_left) && device_mouse_check_button(1, mb_left) room_goto(rm_Menu);

The above code checks to see if the two devices are being held down at the same time and if they then it goes to another room.

Back: Device Input
Next: device_mouse_check_button_pressed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_check_button_pressed

Returns whether a given device button has been pressed.

Syntax:

device_mouse_check_button_pressed(device, button);

Argument | Description
device | The device (from 0 - 4) that is being checked.
button | The button of the device that is being checked.

Returns: Boolean

Description

This function returns true (1) or false (0) depending on whether the device that you specify has been pressed or not. Now, the device refers to the mouse number, which can be from 0 to 4 and this event is triggered when the touch screen of a mobile device is touched, so in this way you can test for up to 5 different screen touches. This function is only triggered once by the actual pressing action, and the standard constants of mb_left and mb_right can be used to check for either button.

Example:

if device_mouse_check_button_pressed(0, mb_left) press=true;

The above code checks to see if the device has been pressed and sets a variable to true if it has.

Back: Device Input
Next: device_mouse_check_button_released

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_check_button_released

Returns whether a given device button has been released.

Syntax:

device_mouse_check_button_released(device, button);

Argument | Description
device | The device (from 0 - 4) that is being checked.
button | The button of the device that is being checked.

Returns: Boolean

Description

This function returns true (1) or false (0) depending on whether the device that you specify has been released or not. Now, the device refers to the mouse number, which can be from 0 to 4 and this event is triggered when the touch screen of a mobile device is touched, so in this way you can test for up to 5 different screen touches. This function is only triggered once by the actual releasing action, and the standard constants of mb_left and mb_right can be used to check for either button.

Example:

if device_mouse_check_button_released(0, mb_left) press=false;

The above code checks to see if the device has been pressed and sets a variable to false if it has.

Back: Device Input
Next: device_mouse_dbclick_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_dbclick_enable

Sets whether a double left-click should be detected as mb_right or not.

Syntax:

device_mouse_dbclick_enable(bool);

Argument | Description
bool | Set double-click detection on (true) or off (false).

Returns: Boolean

Description

This function can be used to set the device to detect a double tap of the mb_left (left mouse button) as an mb_right (right mouse button) tap or not. By default this is set to true, meaning that every time the user taps the device screen twice quickly and consecutively, the return value is the same as if the right mouse button had been clicked. When this is on, the first tap will be detected as mb_left, and the second as mb_right, so make sure that any code you use takes this into account.

Example:

if os_type == os_windows || os_type == os_mac
{
device_mouse_dbclick_enable(false);
}

The above code checks to see if the device running the game is a Windows PC or a Mac and if it is either of them, it disables the double tap function.

Back: Device Input
Next: device_mouse_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_raw_x

Returns the x position of the device when pressed.

Syntax:

device_mouse_raw_x(device);

Argument | Description
device | The device (from 0 - 4) that is being checked.

Returns: Real

Description

This function returns raw x position of the device. What this means is that it returns the actual device definition of the x position that is being touched, not the GameMaker: Studio one, and as such will ignore things like view position and scaling.

Note: This function is very much device dependant and you should experiment first with the desired target module and device to see what exactly is returned.

Example:

if device_mouse_check_button(0, mb_left) && device_mouse_check_button(1, mb_left)
{
x_av = mean(device_mouse_raw_x(0), device_mouse_raw_x(1));
y_av = mean(device_mouse_raw_y(0), device_mouse_raw_y(1));
}

The above code checks to see if device1 and device2 are being pressed, and if they are it calculates the average position of the x/y coordinates between each press point.

Back: Device Input
Next: device_mouse_raw_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_raw_y

Returns the y position of the device when pressed.

Syntax:

device_mouse_raw_y(device);

Argument | Description
device | The device (from 0 - 4) that is being checked.

Returns: Real

Description

This function returns raw y position of the device. What this means is that it returns the actual device definition of the y position that is being touched, not the GameMaker: Studio one, and as such will ignore things like view position and scaling.

Note: This function is very much device dependant and you should experiment first with the desired target module and device to see what exactly is returned.

Example:

if device_mouse_check_button(0, mb_left) && device_mouse_check_button(1, mb_left)
{
x_av = mean(device_mouse_raw_x(0), device_mouse_raw_x(1));
y_av = mean(device_mouse_raw_y(0), device_mouse_raw_y(1));
}

The above code checks to see if device1 and device2 are being pressed, and if they are it calculates the average position of the x/y coordinates between each press point.

Back: Device Input
Next: device_mouse_x_to_gui

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_x

Returns the x position of the device when pressed.

Syntax:

device_mouse_x(device);

Argument | Description
device | The device (from 0 - 4) that is being checked.

Returns: Real

Description

This function returns x position of the device. If you are running this on a the HTML5 or PC and Mac modules then this value is updated constantly, as long as the device (usually a mouse) is plugged in, however for mobile devices, this will only be updated while the screen is being touched.

Example:

if device_mouse_check_button(0, mb_left)
{
if device_mouse_x(0) > x-32 && device_mouse_x(0) < x+32
{
pressed = true;
}
else
{
pressed = false;
}
}

The above code checks to see if the device is being pressed and if so it then polls the device x position to see if it is within the parameters. If it is it sets the variable "pressed" to true, other wise it sets it to false.

Back: Device Input
Next: device_mouse_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_x_to_gui

Returns the x position of the mouse relative to the GUI layer when pressed.

Syntax:

device_mouse_x_to_gui(device);

Argument | Description
device | The device (from 0 - 4) that is being checked.

Returns: Real

Description

This function returns x position of the device in relation to the GUI layer. Since the GUI layer can be set to be a different size independently of the screen resolution and the room size, it can sometimes be complicated to get the exact point on the GUI layer that a user has touched the screen. With this function you can get that position based on the actual GUI size, making GUI buttons and HUD elements easier to create. If you are running this on a the HTML5 or PC and Mac modules then this value is updated constantly, as long as the device (usually a mouse) is plugged in, however for mobile devices, this will only be updated while the screen is being touched.

Example:

if device_mouse_check_button(0, mb_left)
{
if device_mouse_x_to_gui(0) > 0 && device_mouse_x_to_gui(0) < 32
{
pressed = true;
}
else
{
pressed = false;
}
}

The above code checks to see if the device mouse is being pressed and if so it then polls the device x position on the GUI layer to see if it is within the parameters. If it is it sets the variable "pressed" to true, other wise it sets it to false.

Back: Device Input
Next: device_mouse_y_to_gui

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_y

Returns the y position of the device when pressed.

Syntax:

device_mouse_y(device);

Argument | Description
device | The device (from 0 - 4) that is being checked.

Returns: Real

Description

This function returns y position of the device. If you are running this on a the HTML5 or PC and Mac modules then this value is updated constantly, as long as the device (usually a mouse) is plugged in, however for mobile devices, this will only be updated while the screen is being touched.

Example:

if device_mouse_check_button(0, mb_left)
{
if device_mouse_y(0) > y-32 && device_mouse_y(0) < y+32
{
pressed = true;
}
else
{
pressed = false;
}
}

The above code checks to see if the device is being pressed and if so it then polls the device y position to see if it is within the parameters. If it is it sets the variable "pressed" to true, other wise it sets it to false.

Back: Device Input
Next: device_mouse_raw_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


device_mouse_y_to_gui

Returns the x position of the mouse relative to the GUI layer when pressed.

Syntax:

device_mouse_y_to_gui(device);

Argument | Description
device | The device (from 0 - 4) that is being checked.

Returns: Real

Description

This function returns y position of the device in relation to the GUI layer. Since the GUI layer can be set to be a different size independently of the screen resolution and the room size, it can sometimes be complicated to get the exact point on the GUI layer that a user has touched the screen. With this function you can get that position based on the actual GUI size, making GUI buttons and HUD elements easier to create. If you are running this on a the HTML5 or PC and Mac modules then this value is updated constantly, as long as the device (usually a mouse) is plugged in, however for mobile devices, this will only be updated while the screen is being touched.

Example:

if device_mouse_check_button(0, mb_left)
{
if device_mouse_y_to_gui(0) > 0 && device_mouse_y_to_gui(0) < 32
{
pressed = true;
}
else
{
pressed = false;
}
}

The above code checks to see if the device mouse is being pressed and if so it then polls the device x position on the GUI layer to see if it is within the parameters. If it is it sets the variable "pressed" to true, other wise it sets it to false.

Back: Device Input
Next: device_is_keypad_open

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


GamePad Input

This section deals with gamepad input for your game.

GameMaker: Studio has a number of dedicated functions that can be used to detect both analogue and digital controls from multiple connected game pads. These functions work similar to the Device Inputs, in that you can detect up to four different XInput game pads that are connected (and up to 8 DirectInput gamepads) and deal with the input from each one using the same functions. Note that when a gamepad is plugged in to your device (or it is removed) then an asynchronous System Event is triggered where you can deal with the situation using the appropriate functions.

The gamepad "slots" are indexed from 0 with slots 0 - 3 inclusive being only for Xinput gamepads, ie: Xbox360 controllers and compatibles. However you can also check slots 4 - 11 inclusive for DirectInput gamepads, which means you can detect many other models of controller when connected through these slots. It is worth noting that when using DirectInput gamepads, the constants given below may not match exactly the buttons that you expect when they are pressed, due to the fragmented and non-standardised way thet the API is implemented by controller manufacturers. It is recommend that you have some kind of game-pad setup screen in your games where people can redefine the gamepad buttons based on input from any connected to device to mitigate any issues. Also note that the Direct Input interface is run in cooperative mode which means that your game only has access when it is the foreground application, which in turn will cause Direct Input controllers to be "lost" if the game uses focus and then "found" again when it comes back into focus (this can be detected in the System Event and dealt with).

When working with the gamepad functions, there are a number of built-in constants that should be used for getting/defining buttons and stick axis etc...:

Constant | Description
gp_face1 | Top button 1 (this maps to the "A" on an Xbox 360 controller and the cross on a PS controller)
gp_face2 | Top button 2 (this maps to the "B" on an Xbox 360 controller and the circle on a PS controller)
gp_face3 | Top button 3 (this maps to the "X" on an Xbox 360 controller and the square on a PS controller)
gp_face4 | Top button 4 (this maps to the "Y" on an Xbox 360 controller and the triangle on a PS controller)
gp_shoulderl | Left shoulder button
gp_shoulderlb | Left shoulder trigger
gp_shoulderr | Right shoulder button
gp_shoulderrb | Right shoulder trigger
gp_select | The select button (this is a touch-pad press on a PS4 controller)
gp_start | The start button (this is the "options" button on a PS4 controller)
gp_stickl | The left stick pressed (as a button)
gp_stickr | The right stick pressed (as a button)
gp_padu | D-pad up
gp_padd | D-pad down
gp_padl | D-pad left
gp_padr | D-pad right
gp_axislh | Left stick horizontal axis (analogue)
gp_axislv | Left stick vertical axis (analogue)
gp_axisrh | Right stick horizontal axis (analogue)
gp_axisrv | Right stick vertical axis (analogue)

To better understand exactly what part of the controller each constant represents, you can refer to the following image of a standard gamepad:

Below you can find a list of all the gamepad functions:

  1. gamepad_is_supported
  2. gamepad_get_device_count
  3. gamepad_is_connected
  4. gamepad_get_description
  5. gamepad_get_button_threshold
  6. gamepad_set_button_threshold
  7. gamepad_axis_count
  8. gamepad_axis_value
  9. gamepad_button_check
  10. gamepad_button_check_pressed
  11. gamepad_button_check_released
  12. gamepad_button_count
  13. gamepad_button_value
  14. gamepad_set_vibration
  15. gamepad_set_axis_deadzone
  16. gamepad_set_colour

Compatibility

The following list shows current compatibility across the platforms (note that this will change with future updates):

  • Windows is fully supported with up to a maximum of 12 connected devices permitted at once (numbered from 0 to 11, with 0 - 3 being XInput devices and 4 - 11 being DirectInput).

  • Mac OSX is supported with up to a maximum of 4 connected devices permitted at once, and these devices can ONLY be of the type Playstation3 or Xbox 360. Please note that the "Build for Mac AppStore" option in Mac Global Game Settings needs to be OFF for pad support to work.

  • Ubuntu does also support GamePad input, but you may need to install additional libraries from the Ubuntu repository. You can do this easily by opening a command line terminal and typing the following:

    sudo apt-get install jstest-gtk
    sudo apt-get install joystick.

    This will install GUI support for the joystick as well as the joystick itself.

  • HTML5 games are only supported by most major browsers, except Safari.

  • Gamepad support also extends to iOS with the iCade cabinet. The left axis maps to the stick controller (although the input is digital, not analogue), the four "face" buttons map to the cabinet front buttons, and the four shoulder buttons map to those at the back of the cabinet.

  • Android export supports NYKO controllers and generic Bluetooth controllers (including the OUYA), but only when they are enabled, meaning that you will have to tick the iCade/Bluetooth option in the Android Tab of the Global Game Settings. They require API level 12 for them to work fully and it should be noted that GameMaker: Studio will register as connected any Bluetooth devices that your device is paired with, whether or not it’s actually connected. Therefore this should be taken into account when assigning and checking "slots".

  • On PS4, if you want to use the touch pad tracking you need to use the device_mouse_* buttons.

Back: Mouse, Keyboard and Other Controls
Next: Joystick Input

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_axis_count

Returns the total number of axis controls for the given device.

Syntax:

gamepad_axis_count(device);

Argument | Description
device | Which gamepad device "slot" to check.

Returns: Real

Description

This function will return the number of "axis" controls on the device being checked. These controls are the analogue direction "thumbsticks" on most controllers.

Example:

axis = gamepad_axis_count(0))

The above code stores the number of axes available for the gamepad connected to device "slot" 0 in the variable "axis".

Back: GamePad Input
Next: gamepad_axis_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_axis_value

Returns a value based on the current axis position.

Syntax:

gamepad_axis_value(device, axisIndex);

Argument | Description
device | Which gamepad device "slot" to check.
axisIndex | The axis index to check (see the constants list).

Returns: real

Description

You can use this function to get the value of the different axes from a given gamepad. The return value will be between -1 and 1 for each of the available horizontal and vertical axes (the constants used by this function can be found listed here).

Example:

var haxis = gamepad_axis_value(0, gp_axislh);
var vaxis = gamepad_axis_value(0, gp_axislv);
direction = point_direction(0, 0, haxis, vaxis);
speed = point_distance(0 ,0, haxis, vaxis) * 5;

The above code sets the speed and direction of the instance based on the returned values of the left analogue controller of the gamepad plugged into device "slot" 0.

Back: GamePad Input
Next: gamepad_button_check

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_button_check

Returns whether a given gamepad button is currently down.

Syntax:

gamepad_button_check(device, button);

Argument | Description
device | Which gamepad device "slot" to check.
button | Which gamepad button constant to check for.

Returns: Boolean

Description

This function will return true or false depending on whether the given gamepad button is detected as being held down or not.

Example:

if gamepad_button_check(0, gp_face1)
{
if canshoot = true
{
audio_sound_play(snd_Shoot, 0, false);
instance_create(x, y, obj_Bullet)
canshoot = false;
alarm[0] = room_speed / 2;
}
}

The above code will detect whether the bottom button of the top face (the "X" on a ps3 controller) is being held down and if so, it will shoot a "bullet" instance and set an alarm.

Back: GamePad Input
Next: gamepad_button_check_pressed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_button_check_pressed

Returns whether a given gamepad button has been pressed.

Syntax:

gamepad_button_check_pressed(device, button);

Argument | Description
device | Which gamepad device "slot" to check.
button | Which gamepad button constant to check for.

Returns: Boolean

Description

This function will return true or false depending on whether the given gamepad button is detected as having been pressed or not. Note that this function will only trigger once for the button the first time it is pressed. For it to trigger again the button must first be released and then re-pressed. If you need to check a continuous press of the button you should be using the function gamepad_button_check.

Example:

if gamepad_button_check_pressed(0, gp_start)
{
audio_sound_play(snd_Start, 0, false);
room_goto(rm_Level_1);
}

The above code will detect whether the "start" button of the gamepad connected to device "slot" 0 has been pressed or not and change room if it has.

Back: GamePad Input
Next: gamepad_button_check_released

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_button_check_released

Returns whether a given gamepad button has been released.

Syntax:

gamepad_button_check_released(device, button);

Argument | Description
device | Which gamepad device "slot" to check.
button | Which gamepad button constant to check for.

Returns: Boolean

Description

This function will return true or false depending on whether the given gamepad button is detected as having been released or not. Note that this function will only trigger once for the button the moment it has been released. For it to trigger again the button must first be pressed and then released once more.

Example:

if gamepad_button_check_released(0, gp_select)
{
audio_sound_play(snd_Button, 0, false);
global.Pause = !global.Pause;
}

The above code will detect whether the "select" button of the gamepad connected to device "slot" 0 has been pressed or not and toggle the global "Pause" variable.

Back: GamePad Input
Next: gamepad_button_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_button_count

Returns the total number of supported buttons for the device.

Syntax:

gamepad_button_count(device);

Argument | Description
device | Which gamepad device "slot" to check.

Returns: Real

Description

This function will return the total number of buttons available for the gamepad connected to the given device "slot".

Example:

b_num = gamepad_button_count(0);

The above code will return the number of buttons available on the gamepad plugged into device "slot" 0 and store the value in the variable "b_num".

Back: GamePad Input
Next: gamepad_button_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_button_value

Returns the current position of an analogue button.

Syntax:

gamepad_button_value(device, button);

Argument | Description
device | Which gamepad device "slot" to check.
button | Which gamepad button constant to check for.

Returns: Real

Description

With this function you can get the current value of an analogue button, from 0 to 1, where 0 is no pressure and 1 is full pressure.

Example:

speed = gamepad_button_value(0, gp_shoulderrb) * 4;

The above code uses the analogue trigger value from the gamepad plugged into device "slot" 0 to set the speed of the instance.

Back: GamePad Input
Next: gamepad_set_vibration

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_get_button_threshold

Returns the current threshold setting of the analogue buttons.

Syntax:

gamepad_get_button_threshold(device);

Argument | Description
device | Which gamepad device "slot" to check.

Returns: Real

Description

This function can be used to detect the current threshold setting of the analogue buttons for a given device. The default threshold for all analogue buttons is 0.5, with the range being from 0 to 1. The threshold defines at what point the button is considered as being "pressed" for games that require them to act as a digital button.

Example:

if gamepad_get_button_threshold(0) != 0.5
{
gamepad_set_button_threshold(0, 0.5);
}

The above code checks the analogue button threshold of the gamepad connected to device "slot" 0 and if it is not the default value of 0.5, it is set to that value.

Back: GamePad Input
Next: gamepad_set_button_threshold

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_get_description

Returns a descriptive string for the given gamepad.

Syntax:

gamepad_get_description(device);

Argument | Description
device | Which gamepad "slot" to get the name of.

Returns: String

Description

This function will return a string with the description of the given gamepad, for example, a PS3 controller may return a string similar to "PLAYSTATION(R)3 Controller", or an XBox360 controller could return "Xbox 360 Controller (XInput STANDARD GAMEPAD)". This string is hardware dependant and the returned value will depend on the gamepad plugged into the device "slot" that is being checked.

Example:

var gp_num = gamepad_get_device_count();
for (var i = 0; i < gp_num; i++;)
{
if gamepad_is_connected(i)
{
draw_text(32, 32 + (i * 32), gamepad_get_description(i));
}
else
{
draw_text(32, 32 + (i * 32), "No Gamepad Connected");
}
}

Back: GamePad Input
Next: gamepad_get_button_threshold

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_get_device_count

Returns the number of game pads connected or the number of slots available for game pads.

Syntax:

gamepad_get_device_count();

Returns: Real

Description

This function will tell you one of two things. Either the number of game pads connected, or the number of available "slots" for game pads to be connected to. The actual return value will depend on the platform and the internal configuration of that platform and as such this function should be used in conjunction with the function gamepad_is_connected to make sure of the exact number of pads connected at any time.

Example:

var gp_num = gamepad_get_device_count();
for (var i = 0; i < gp_num; i++;)
{
if gamepad_is_connected(i) global.gp[i] = true else global.gp[i] = false;
}

The above code loops through the available game pads (or gamepad slots) and then checks each one for a connected gamepad. the returned value is then used to set a global array to true or false for use in future checks.

Back: GamePad Input
Next: gamepad_is_connected

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_is_connected

Returns whether a given gamepad is currently connected.

Syntax:

gamepad_is_connected(numb);

Argument | Description
device | Which gamepad "slot" to check.

Returns: Boolean

Description

This function will return whether a gamepad is connected to the given "slot" (returns true) or not (returns false). You would normally use this function in conjunction with the gamepad_get_device_count function to get the correct number of available game pads and/or gamepad "slots". Note that there may be a slight delay between the user connecting the gamepad and GameMaker: Studio detecting it as being connected (this is especially the case when dealing with bluetooth connected controllers).

Example:

var gp_num = gamepad_get_device_count();
for (var i = 0; i < gp_num; i++;)
{
if gamepad_is_connected(i) global.gp[i] = true else global.gp[i] = false;
}

The above code loops through the available game pads (or gamepad slots) and then checks each one for a connected gamepad. the returned value is then used to set a global array to true or false for use in future checks.

Back: GamePad Input
Next: gamepad_get_description

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_is_supported

Returns whether game pads are supported by the target platform.

Syntax:

gamepad_is_supported();

Returns: Boolean

Description

With this function you can find out whether the target platform supports game pads (returns true) or not (returns false).

Example:

global.GP = gamepad_is_supported();

The above code checks to see if a gamepad is supported and stores the return value in a global variable for future checks.

Back: GamePad Input
Next: gamepad_get_device_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_set_axis_deadzone

Set the dead-zone (input cut-off) for the axis values returned by the device.

Syntax:

gamepad_set_axis_deadzone(device, deadzone);

Argument | Description
device | Which gamepad device "slot" to check.
deadzone | The dead zone value from 0 to 1.

Returns: N/A

Description

This function can be used to set the "dead zone" of the joystick axis. You specify the device slot to set, and then set a value from 0 to 1 and if the input amount is lower than the given value, the joystick axis is considered to be at 0. Note that this is a global setting that will affect all axis of all joysticks connected to the device slot specified.

Example:

if gamepad_is_connected(0) gamepad_set_axis_deadzone(0, 0.05);
if gamepad_is_connected(1) gamepad_set_axis_deadzone(1, 0.05);
if gamepad_is_connected(2) gamepad_set_axis_deadzone(2, 0.05);
if gamepad_is_connected(3) gamepad_set_axis_deadzone(3, 0.05);

The above code will set the dead zone of the joystick axis on any of 4 connected devices to 0.05.

Back: GamePad Input
Next: gamepad_set_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_set_button_threshold

Sets the threshold for the analogue buttons of the given device.

Syntax:

gamepad_set_button_threshold(device, threshold);

Argument | Description
device | Which gamepad device "slot" to check.
threshold | The new threshold value (from 0 - 1, default 0.5).

Returns: N/A

Description

This function can be used to set the current threshold setting of the analogue buttons for a given device. The default threshold for all analogue buttons is 0.5, with the range being from 0 to 1. The threshold defines at what point the button is considered as being "pressed" for games that require them to act as a digital button.

Example:

if gamepad_get_button_threshold(0) != 0.5
{
gamepad_set_button_threshold(0, 0.5);
}

The above code checks the analogue button threshold of the gamepad connected to device "slot" 0 and if it is not the default value of 0.5, it is set to that value.

Back: GamePad Input
Next: gamepad_axis_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_set_colour

Set the LED colour for PS4 gamepads.

Syntax:

gamepad_set_colour(device, colour);

Argument | Description
device | Which gamepad device "slot" to set.
colour | The colour to use.

Returns: N/A

Description

This function can be used to set the colour of the LEDs within a PlayStation controller. You specify the device slot to set, and then give a colour, which can be any of the colour constants or a colour value created using the specific colour functions or a HEX value(like $FFFFFFF).

Example:

if health < 10
{
gamepad_set_colour(0, c_red);
}

The above code will set the PlayStation controller LEDs to red if the health variable falls below 10.

Back: GamePad Input
Next: gamepad_is_supported

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gamepad_set_vibration

Controls the device vibration

Syntax:

gamepad_set_vibration(device, left_motor, right_motor);

Argument | Description
device | Which gamepad device "slot" to check.
left_motor | The amount of vibration from the left motor from 0 to 1.
right_motor | The amount of vibration from the right motor from 0 to 1.

Returns: N/A

Description

With this function you can set the vibration of the gamepad motors, with either motor using a value from 0 (no vibration) to 1 (full vibration). Note that there is no time limit on this function, so you will need to use a variable or an alarm to switch off the vibration (set motors to 0) after a given time has passed otherwise the gamepad will continue to vibrate indefinitely.

NOTE: This function is currently only available for the standard Windows, PS4 and Xbox One target modules.

Example:

if lives = 0
{
gamepad_set_vibration(0, 1, 1);
alarm[0] = room_speed / 2;
}

The above code would be used (for example) in a collision event to make the gamepad plugged into "slot" 0 vibrate for half a second, with the alarm that is set being used to switch it off again once that time has passed.

Back: GamePad Input
Next: gamepad_set_axis_deadzone

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Immersion Haptics

This section deals with haptic effects for Android devices.

Haptics are similar to the "rumble packs" on game consoles, brought to mobile devices and the technology uses fine control over the vibration motor on a device to accentuate audio-visual effects within the game. This means that as well as seeing and hearing a shot (or collision, or bounce, or engine, etc), the player can also feel it. This provides higher level of user engagement, and consequent monetization opportunities.

The haptic library in GameMaker: Studio is provided by Immersion (of San Jose, California) and is licensed without charge for use in your games. However, to use haptic effects, you will need to tick the "Use Haptics" check-box on the Android Tab in the Global Game Settings, and accept the Immersion EULA (End User License Agreement) that is shown. After you accept the EULA, you will be able to successfully compile your game in GameMaker: Studio with haptic effects enabled.

To help developers feel haptic effects in a game context, and also to review the set of over 100 effects, please install the free Immersion Haptic Muse app onto your Android test device. The Haptic Muse app lets you choose individual effects, feel them in game scenarios, and select the effects that work best in your game.

It is worth noting that haptic effects are used in over 2,000 game apps from around the world and that the technology consumes less battery power than playing the sound effects in a game. Game apps with Haptic technology enhance the satisfaction of game players both casual and hardcore and can differentiate your app from many others in the market place.

The Immersion integrated API is easy to use, with only two control functions:

  1. immersion_play_effect
  2. immersion_stop

Should you need any further information or advice on haptics, you can contact the Immersion Developer Support by email at HapticsDev@immersion.com.

Back: Mouse, Keyboard and Other Controls

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


immersion_play_effect

Play a haptic effect.

Syntax:

immersion_play_effect(effect);

Argument | Description
effect | The effect value to use (real).

Returns: N/A

Description

With this function you can play any one of the 123 available haptic effects. Before you can use these effects you must have ticked the "Use Haptics" check-box on the Global Game Settings Android Tab and accepted the Immersion EULA that is shown. Note that some of these effects are repeating or constant and will need to be stopped using the immersion_stop function. A full list of the Immersion effects values are given below, but to get a true feel for what they do and how they will work, it is recommended that you download their test app from Google Play (available here).

NOTE: Using any of the haptic functions without having previously agreed to the EULA will cause your games to fail compiling.

Name | Value | Name | Value
ALERT1 | 63 | ALERT10 | 72
ALERT2 | 64 | ALERT3 | 65
ALERT4 | 66 | ALERT5 | 67
ALERT6 | 68 | ALERT7 | 69
ALERT8 | 70 | ALERT9 | 71
BOUNCE_100 | 9 | BOUNCE_33 | 11
BOUNCE_66 | 10 | BUMP_100 | 6
BUMP_33 | 8 | BUMP_66 | 7
DOUBLE_BUMP_100 | 18 | DOUBLE_BUMP_33 | 20
DOUBLE_BUMP_66 | 19 | DOUBLE_SHARP_CLICK_100 | 12
DOUBLE_SHARP_CLICK_33 | 14 | DOUBLE_SHARP_CLICK_66 | 13
DOUBLE_STRONG_CLICK_100 | 15 | DOUBLE_STRONG_CLICK_33 | 17
DOUBLE_STRONG_CLICK_66 | 16 | ENGINE1_100 | 112
ENGINE1_33 | 114 | ENGINE1_66 | 113
ENGINE2_100 | 115 | ENGINE2_33 | 117
ENGINE2_66 | 116 | ENGINE3_100 | 118
ENGINE3_33 | 120 | ENGINE3_66 | 119
ENGINE4_100 | 121 | ENGINE4_33 | 123
ENGINE4_66 | 122 | EXPLOSION1 | 73
EXPLOSION10 | 82 | EXPLOSION2 | 74
EXPLOSION3 | 75 | EXPLOSION4 | 76
EXPLOSION5 | 77 | EXPLOSION6 | 78
EXPLOSION7 | 79 | EXPLOSION8 | 80
EXPLOSION9 | 81 | FAST_PULSE_100 | 45
FAST_PULSE_33 | 47 | FAST_PULSE_66 | 46
FAST_PULSING_100 | 48 | FAST_PULSING_33 | 50
FAST_PULSING_66 | 49 | IMPACT_METAL_100 | 96
IMPACT_METAL_33 | 98 | IMPACT_METAL_66 | 97
IMPACT_RUBBER_100 | 99 | IMPACT_RUBBER_33 | 101
IMPACT_RUBBER_66 | 100 | IMPACT_WOOD_100 | 93
IMPACT_WOOD_33 | 95 | IMPACT_WOOD_66 | 94
LONG_BUZZ_100 | 27 | LONG_BUZZ_33 | 29
LONG_BUZZ_66 | 28 | LONG_TRANSITION_RAMP_DOWN_100 | 39
LONG_TRANSITION_RAMP_DOWN_33 | 41 | LONG_TRANSITION_RAMP_DOWN_66 | 40
LONG_TRANSITION_RAMP_UP_100 | 33 | LONG_TRANSITION_RAMP_UP_33 | 35
LONG_TRANSITION_RAMP_UP_66 | 34 | SHARP_CLICK_100 | 0
SHARP_CLICK_33 | 2 | SHARP_CLICK_66 | 1
SHORT_BUZZ_100 | 30 | SHORT_BUZZ_33 | 32
SHORT_BUZZ_66 | 31 | SHORT_TRANSITION_RAMP_DOWN_100 | 42
SHORT_TRANSITION_RAMP_DOWN_33 | 44 | SHORT_TRANSITION_RAMP_DOWN_66 | 43
SHORT_TRANSITION_RAMP_UP_100 | 36 | SHORT_TRANSITION_RAMP_UP_33 | 38
SHORT_TRANSITION_RAMP_UP_66 | 37 | SLOW_PULSE_100 | 51
SLOW_PULSE_33 | 53 | SLOW_PULSE_66 | 52
SLOW_PULSING_100 | 54 | SLOW_PULSING_33 | 56
SLOW_PULSING_66 | 55 | STRONG_CLICK_100 | 3
STRONG_CLICK_33 | 5 | STRONG_CLICK_66 | 4
TEXTURE1 | 102 | TEXTURE10 | 111
TEXTURE2 | 103 | TEXTURE3 | 104
TEXTURE4 | 105 | TEXTURE5 | 106
TEXTURE6 | 107 | TEXTURE7 | 108
TEXTURE8 | 109 | TEXTURE9 | 110
TICK_100 | 24 | TICK_33 | 26
TICK_66 | 25 | TRANSITION_BOUNCE_100 | 60
TRANSITION_BOUNCE_33 | 62 | TRANSITION_BOUNCE_66 | 61
TRANSITION_BUMP_100 | 57 | TRANSITION_BUMP_33 | 59
TRANSITION_BUMP_66 | 58 | TRIPLE_STRONG_CLICK_100 | 21
TRIPLE_STRONG_CLICK_33 | 23 | TRIPLE_STRONG_CLICK_66 | 22
WEAPON1 | 83 | WEAPON10 | 92
WEAPON2 | 84 | WEAPON3 | 85
WEAPON4 | 86 | WEAPON5 | 87
WEAPON6 | 88 | WEAPON7 | 89
WEAPON8 | 90 | WEAPON9 | 91

Example:

if hp <0
{
immersion_play_effect(44);
}

The above code checks to see if the instance variable "hp" is less than 0 and if it is it plays a haptic effect.

Back: Immersion Haptics
Next: immersion_stop

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


immersion_stop

Stop a haptic effect.

Syntax:

immersion_stop();

Returns: N/A

Description

This function will stop any of the haptic effects (started using immersion_play_effect) that are currently playing.

NOTE: Using any of the haptic functions without having previously agreed to the EULA will cause your games to fail compiling.

Example:

immersion_stop();

The above code will stop any currently playing haptic effects.

Back: Immersion Haptics
Next: immersion_play_effect

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Joystick Input

This section deals with the joystick input.

GameMaker: Studio will accept up to two joysticks/gamepads being used for your game, with a number of specialist functions designed to get the necessary details about position and buttons pressed.

NOTE: These functions are for Windows only and are provided as legacy support for previous versions. As such, they may not work correctly on modern PC's.

The following functions exist for joystick controls:

  1. joystick_exists
  2. joystick_name
  3. joystick_axes
  4. joystick_buttons
  5. joystick_has_pov
  6. joystick_direction
  7. joystick_check_button
  8. joystick_xpos
  9. joystick_ypos
  10. joystick_zpos
  11. joystick_rpos
  12. joystick_upos
  13. joystick_vpos
  14. joystick_pov

Back: Mouse, Keyboard and Other Controls

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_axes

Returns the number of axes the joystick has.

Syntax:

joystick_axes(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return the number of axes that the joystick/gamepad with the given id has. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

if joystick_exists(1)
{
axes = joystick_axes(1);
}
else
{
axes = -1;
}

The above code checks to see if a joystick or gamepad is connected to the device and then sets a variable to the number of axes it has or -1 if none is connected.

Back: Joystick Input
Next: joystick_buttons

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_buttons

Returns the number of buttons the joystick has.

Syntax:

joystick_buttons(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return the number of buttons that the joystick/gamepad with the given id has, between 1 and 32. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

if joystick_exists(1)
{
axes = joystick_buttons(1);
}
else
{
axes = -1;
}

The above code checks to see if a joystick or gamepad is connected to the device and then sets a variable to the number of buttons it has or -1 if none is connected.

Back: Joystick Input
Next: joystick_has_pov

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_check_button

Checks to see if a joystick button has been pressed.

Syntax:

joystick_check_button(id, numb);

Argument | Description
id | The id of the joystick (1 or 2).
numb | The number of the button to check (from 1 to 32).

Returns: Boolean

Description

This function will return true if the selected button on the joystick/gamepad with the given id is being pressed and false if it is not. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

if joystick_check_button(1, 1)
{
if canshoot
{
canshoot = !canshoot;
alarm[0] = 10;
instance_create(x, y, obj_Bullet);
}
}

The above code checks to see if a joystick or gamepad button is being pressed and if it returns true it checks a variable and creates a bullet object.

Back: Joystick Input
Next: joystick_xpos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_direction

Returns the direction of movement for the joystick.

Syntax:

joystick_direction(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: vk_numpad1...9

Description

This function will return a virtual key code for the numberpad buttons depending on direction being pressed by the joystick/gamepad with the given id, as shown in the image below. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

switch (joystick_direction(1))
{
case vk_numpad1: direction = 225; break;
case vk_numpad2: direction = 270; break;
case vk_numpad3: direction = 315; break;
case vk_numpad4: direction = 180; break;
case vk_numpad6: direction = 0; break;
case vk_numpad7: direction = 135; break;
case vk_numpad8: direction = 90; break;
case vk_numpad9: direction = 45; break;
}

The above code uses the returned value of the joystick_direction function to set the direction of movement for the instance.

Back: Joystick Input
Next: joystick_check_button

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_exists

Checks for a joystick.

Syntax:

joystick_exists(id);

Argument | Description
id | The id of the joystick to check for (1 or 2).

Returns: Boolean

Description

This function will return true if a joystick/gamepad with the given id is connected or false if it is not. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

if joystick_exists(1) || joystick_exists(2)
{
global.Control = 3;
}

The above code checks to see if a joystick or gamepad is connected to the device and, if so, sets a global variable.

Back: Joystick Input
Next: joystick_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_has_pov

Checks the point of view capabilities of the joystick.

Syntax:

joystick_has_pov(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return true if the joystick/gamepad with the given id has point of view capabilities or false if it does not. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available Windows.

Example:

if joystick_has_pov(1)
{
c_angle = joystick_pov(1);
}

The above code checks to see if a joystick or gamepad has point of view capabilities and if it does it sets a variable to the returned value of the joystick_pov function.

Back: Joystick Input
Next: joystick_direction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_name

Returns the name of the joystick.

Syntax:

joystick_name(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: String

Description

This function will return a string with the name of the joystick/gamepad with the given id. If no such device is connected an empty string "" will be returned. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

if joystick_exists(1)
{
j_name = joystick_name(1);
}
else
{
j_name = "None";
}

The above code checks to see if a joystick or gamepad is connected to the device and then sets a variable depending on the result of the check.

Back: Joystick Input
Next: joystick_axes

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_pov

Returns the joysticks point-of view position.

Syntax:

joystick_pov(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return the point-of view position of the joystick/gamepad with the given id. This is an angle between 0 and 360 degrees, where 0 is forwards, 90 to the right, 180 backwards and 270 to the left. When no point-of-view direction is pressed by the user -1 is returned. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

if joystick_has_pov(1)
{
c_angle = joystick_pov(1);
}

The above code checks to see if a joystick or gamepad has point of view capabilities and if it does it sets a variable to the returned value of the joystick_pov function.

Back: Joystick Input
Next: joystick_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_rpos

Returns the position of the r-axis of joystick.

Syntax:

joystick_rpos(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return the position of the r-axis of the joystick/gamepad with the given id, with the value being somewhere between -1 and 1. See the image below for the relationship between the different axes of rotation that are accepted. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

rr += spd * joystick_rpos(1);

The above code uses the returned value of the joystick_ypos function to set a variable within the instance.

Back: Joystick Input
Next: joystick_upos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_upos

Returns the position of the u-axis of joystick.

Syntax:

joystick_upos(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return the position of the u-axis of the joystick/gamepad with the given id, with the value being somewhere between -1 and 1. See the image below for the relationship between the different axes of rotation that are accepted. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

uu += spd * joystick_upos(1);

The above code uses the returned value of the joystick_ypos function to set a variable within the instance.

Back: Joystick Input
Next: joystick_vpos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_vpos

Returns the position of the y-axis of joystick.

Syntax:

joystick_vpos(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return the position of the v-axis of the joystick/gamepad with the given id, with the value being somewhere between -1 and 1. See the image below for the relationship between the different axes of rotation that are accepted. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

vv += spd * joystick_vpos(1);

The above code uses the returned value of the joystick_ypos function to set a variable within the instance.

Back: Joystick Input
Next: joystick_pov

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_xpos

Returns the position of the x-axis of joystick.

Syntax:

joystick_xpos(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return the position of the x-axis of the joystick/gamepad with the given id, with the value being somewhere between -1 and 1. See the image below for the relationship between the different axes of rotation that are accepted. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

xx += spd * joystick_xpos(1);

The above code uses the returned value of the joystick_xpos function to set a variable within the instance.

Back: Joystick Input
Next: joystick_ypos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_ypos

Returns the position of the y-axis of joystick.

Syntax:

joystick_ypos(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return the position of the y-axis of the joystick/gamepad with the given id, with the value being somewhere between -1 and 1. See the image below for the relationship between the different axes of rotation that are accepted. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

yy += spd * joystick_ypos(1);

The above code uses the returned value of the joystick_ypos function to set a variable within the instance.

Back: Joystick Input
Next: joystick_zpos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


joystick_zpos

Returns the position of the z-axis of joystick.

Syntax:

joystick_zpos(id);

Argument | Description
id | The id of the joystick (1 or 2).

Returns: Real

Description

This function will return the position of the z-axis of the joystick/gamepad with the given id, with the value being somewhere between -1 and 1. See the image below for the relationship between the different axes of rotation that are accepted. The id can be either 1 or 2 as GameMaker: Studio only accepts input from a maximum of two joysticks/gamepads.

NOTE: This function is only available for Windows.

Example:

zz += spd * joystick_zpos(1);

The above code uses the returned value of the joystick_ypos function to set a variable within the instance.

Back: Joystick Input
Next: joystick_rpos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Keyboard Input

GameMaker: Studio has a number of constants and functions related to the keyboard and how it can be used to make things happen in your games.

When dealing with the keyboard in GameMaker: Studio you have a variety of functions that can be used to recognise different keyboard states like pressed or released. There are also some that store all the keypresses as a string or that can tell you what the last key pressed was, as well as others that allow you to clear the keyboard state completely.

NOTE: These functions are designed for Windows/Mac/Ubuntu desktop platforms only. You may find some of the in-built variables and constants aren't valid on other platforms and many of the functions won't work on mobiles.

Now, each key is normally defined by a number, called the ascii code, and you can directly input this number into these functions and they will work fine... But, as it's a bit difficult to remember so many numbers and the relationship that they have with your keyboard, GameMaker: Studio has a series of constants for the most used keyboard special keys and a special function ord() to return the number from ordinary typed characters (either letters or numbers).

The following is a small example of how to use ord():

if keyboard_check(ord('A'))
{
hspeed = -5;
}

So, the above will check the "A" key and if it's being pressed then it'll set the horizontal speed of the object to -5. Note, that the "A" is a capital "A", and that when using ord() the keyboard key to check must always be written in quotes and as a capital. Now, what if you want to use the arrow keys? Or if you want to modify an action using the "shift" key? Well, for that GameMaker: Studio has a series of vk_ constants (vk_ stands for virtual keyboard) that you can use in place of ord or the ascii code.

Here is a complete list of the vk_ constants:

Constant | Description
vk_nokey | keycode representing that no key is pressed
vk_anykey | keycode representing that any key is pressed
vk_left | keycode for left arrow key
vk_right | keycode for right arrow key
vk_up | keycode for up arrow key
vk_down | keycode for down arrow key
vk_enter | enter key
vk_escape | escape key
vk_space | space key
vk_shift | either of the shift keys
vk_control | either of the control keys
vk_alt | alt key
vk_backspace | backspace key
vk_tab | tab key
vk_home | home key
vk_end | end key
vk_delete | delete key
vk_insert | insert key
vk_pageup | pageup key
vk_pagedown | pagedown key
vk_pause | pause/break key
vk_printscreen | printscreen/sysrq key
vk_f1 ... vk_f12 | keycode for the function keys F1 to F12
vk_numpad0 ... vk_numpad9 | number keys on the numeric keypad
vk_multiply | multiply key on the numeric keypad
vk_divide | divide key on the numeric keypad
vk_add | key on the numeric keypad
vk_subtract | subtract key on the numeric keypad
vk_decimal | decimal dot keys on the numeric keypad

The following constants can only be used with keyboard_check_direct():

Constant | Description
vk_lshift | left shift key
vk_lcontrol | left control key
vk_lalt | left alt key
vk_rshift | right shift key
vk_rcontrol | right control key
vk_ralt | right alt key

The following is a small example of how to use the vk_ constants:

if keyboard_check_pressed(vk_tab)
{
instance_create(x,y,obj_Menu);
}

The above code will detect if the "Tab" key is pressed and create an instance of object "obj_Menu" if it is.

For information on the available GameMaker: Studio keyboard functions, please see the following sections of the manual:

  1. io_clear
  2. keyboard_check
  3. keyboard_check_pressed
  4. keyboard_check_released
  5. keyboard_check_direct
  6. keyboard_clear
  7. keyboard_key_press
  8. keyboard_key_release
  9. keyboard_key
  10. keyboard_lastkey
  11. keyboard_lastchar
  12. keyboard_string
  13. keyboard_set_map
  14. keyboard_get_map
  15. keyboard_unset_map
  16. keyboard_get_numlock
  17. keyboard_set_numlock

Back: Mouse, Keyboard and Other Controls

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


io_clear

Clears all keyboard and mouse states.

Syntax:

io_clear();

Returns: N/A

Description

This function will clear the current keyboard and mouse states. Note that what happens in the next step after calling this function will depend on what is being checked and the platform it is being checked on. With mouse input, the mouse button will have to be released and pressed again for any further input to be detected, but with the keyboard it's not quite that simple. In general, the keyboard will be cleared only for that step but the next step will again detect the key, however this may not be the same across all platforms and keyboards, and in some cases the function may act like it does for the mouse and require the key to be lifted and pressed again.

Example:

io_clear();

This will clear all keyboard and mouse states.

Back: Keyboard Input
Next: keyboard_check

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_check

Returns whether the given key on the keyboard is currently held down.

Syntax:

keyboard_check(key);

Argument | Description
key | The key to check the down state of.

Returns: Boolean

Description

With this function you can check to see if a key is held down or not. Unlike the keyboard_check_pressed or keyboard_check_released functions which are only triggered once when the key is pressed or released, this function is triggered every step that the key is held down for.

Example:

if keyboard_check(vk_left)
{
x -= 5;
}

The above code will check to see if the arrow key is being pressed and move the instance 5 pixels left every step that it returns true.

Back: Keyboard Input
Next: keyboard_check_pressed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_check_direct

Returns whether the key with the particular keycode is pressed by checking the hardware directly.

Syntax:

keyboard_check_direct(key);

Argument | Description
key | The key to check the down state of.

Returns: Boolean

Description

This function will return true if the key with the particular keycode is pressed, or false if it is not, by checking the hardware directly. It allows for a few more checks, in particular you can use keycodes vk_lshift, vk_lcontrol, vk_lalt, vk_rshift, vk_rcontrol and vk_ralt to check whether the left or right shift, control or alt key is pressed.

NOTE: This function is only available for the standard Windows target and the result is independent of which application has focus.

Example:

if keyboard_check_direct(vk_ralt) || keyboard_check_direct(vk_lalt)
{
crouch = true;
}

The above code will check to see if either the left or right alt keys have been pressed, and if they have it sets the variable "crouch" to true.

Back: Keyboard Input
Next: keyboard_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_check_pressed

Returns whether the given key on the keyboard has just been pressed.

Syntax:

keyboard_check_pressed(key);

Argument | Description
key | The key to check the pressed state of.

Returns: Boolean

Description

With this function you can check to see if a key has been pressed or not. Unlike the keyboard_check function, this function will only run once for every time the key is pressed down, so for it to trigger again, the key must be first released and then pressed again.

Example:

if keyboard_check_pressed(vk_anykey)
{
room_goto_next();
}

The above code will advance to the next room if the player presses any of the keyboard's keys (working like a 'Press Any Key to Continue' prompt).

Back: Keyboard Input
Next: keyboard_check_released

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_check_released

Returns whether the given key on the keyboard has just been released.

Syntax:

keyboard_check_released(key);

Argument | Description
key | The key to check the released state of.

Returns: Boolean

Description

With this function you can check to see if a key has been released or not. Unlike the keyboard_check function, this function will only run once for every time the key is lifted, so for it to trigger again, the key must be first pressed and then released again.

Example:

if keyboard_check_released(ord('P'))
{
instance_create(0, 0, obj_Pause);
}

The above code will check to see if the "P" key has been released and if so, create an instance of "obj_Pause".

Back: Keyboard Input
Next: keyboard_check_direct

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_clear

Clears the state of the given key.

Syntax:

keyboard_clear(key);

Argument | Description
key | The key to clear.

Returns: N/A

Description

With this function you can clear the current keyboard state, which essentially means that if the key is being held down, it will no longer be recognised until it is released again (which won't generate a keyboard_key_release event either on this occasion) and pressed again.

Example:

keyboard_clear(vk_space);

The above code clears the state of the spacebar.

Back: Keyboard Input
Next: keyboard_key_press

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_get_map

Gets the currently mapped ascii code for the selected key.

Syntax:

keyboard_get_map(key);

Argument | Description
key | This is the key that you wish to get the mapped value from

Returns: Real

Description

Sometimes you may wish to get the ascii code for a mapped key (to see if it is already mapped, for example) which is what this function returns.

Example:

if keyboard_get_map(ord("A")) = ord("A")
{
keyboard_set_map(ord("A"), keyboard_lastkey);
}

The above example code will first check and see if "A" has been mapped to another key, and if it hasn't it will map it to the last key that the user has pressed.

Back: Keyboard Input
Next: keyboard_unset_map

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_get_numlock

Get the status of the numberlock key on the keypad.

Syntax:

keyboard_get_numlock();

Returns: Boolean

Description

You can use this function to find the status of the keypad number lock with true being returned for on, and false returned for off.

NOTE: This functionality is only available in the Windows exe builds and will not function on any other device.

Example:

if keyboard_get_numlock()
{
keyboard_set_numlock(0);
}
else
{
keyboard_set_numlock(1);
}

The above example code will get the state of the numberlock key and if it is on (true) it will set it to off (false) and vice-versa.

Back: Keyboard Input
Next: keyboard_set_numlock

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_key

Stores the current key being used.

Syntax:

keyboard_key;

Returns: Real

Description

With this variable you can get the keycode of the key that is currently being pressed and it will return 0 if no key is being pressed when the check is done.

Example:

switch (keyboard_key)
{
case vk_numpad1: gun = weapon[0,0]; break;
case vk_numpad2: gun = weapon[1,0]; break;
case vk_numpad3: gun = weapon[2,0]; break;
}

The above code uses the value of the keyboard_key variable to set a variable to the same value as an array.

Back: Keyboard Input
Next: keyboard_lastkey

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_key_press

Simulates the press of a given key.

Syntax:

keyboard_key_press(key);

Argument | Description
key | The key to simulate a press of.

Returns: N/A

Description

With this function you can simulate the press of any key on the keyboard. The function accepts any of the vk_ constants as well as the standard keys and even the ascii code.

Example:

keyboard_key_press(vk_space);

This will simulate a spacebar press.

Back: Keyboard Input
Next: keyboard_key_release

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_key_release

Simulates the release of a given key.

Syntax:

keyboard_key_release(key);

Argument | Description
key | The key to simulate a release of.

Returns: Boolean

Description

With this function you can simulate the release of any key on the keyboard. The function accepts any of the vk_ constants as well as the standard keys and even the ascii code.

Example:

keyboard_key_release(vk_space);

This will simulate a spacebar release.

Back: Keyboard Input
Next: keyboard_key

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_lastchar

Stores the last character pressed (as a string).

Syntax:

keyboard_lastchar;

Returns: String

Description

This variable stores a string of the last key pressed. This variable is not read only and you can change it, for example to set it to "" (an empty string) if you handled it already.

Example:

if keyboard_lastkey != -1
{
str += keyboard_lastchar;
keyboard_lastkey = -1;
}

The above code checks to see if the lastkey variable is greater than -1, and if it is it adds whatever the last key was as a string to the variable "str".

Back: Keyboard Input
Next: keyboard_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_lastkey

Stores the keycode of the last key pressed.

Syntax:

keyboard_lastkey;

Returns: Real

Description

This variable refers to the value that keyboard_key was in the previous frame, returning the keycode of that key (all standard keycode constants are returned). This variable is not read only and you can change it, for example to set it to -1 if you handled it already.

Example:

if (keyboard_lastkey != -1)
{
str += keyboard_lastchar;
keyboard_lastkey = -1;
}

The above code checks to see if the lastkey variable is not equal to -1, and if it is it adds whatever the last key was as a string to the variable "str", then it resets the keyboard_lastkey variable to accept further input.

Back: Keyboard Input
Next: keyboard_lastchar

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_set_map

Maps one key on the keyboard to another.

Syntax:

keyboard_set_map(key1, key2);

Argument | Description
key1 | This is the key that key1 is to be mapped to
key2 | This is the key that is to be mapped

Returns: Boolean

Description

Sometimes when making a game you may wish one key to do the same as another. For example many people use the keys WASD for movement, but then many people also use the arrow keys! So, what to do? Well, you could code the movement system twice, but that is a bit complicated and thankfully redundant as this function permits you to "map" one key to another and so any input from either key will be interpreted as the same. To do this you choose a key that you want to map (key2 - this will be the key that you write the code for) and a key that you want it to be mapped to (key1). After that, keypresses to either key will be interpreted by GameMaker: Studio as coming from key2. You can also use this function to design a system where the user can define their own keys for playing by simply mapping the user input key to the key that you have coded into the game.

Example:

keyboard_set_map(ord("A"), vk_left);

The above example code will map the "A" key to the left arrow key. This means that the player can use either the "A" or the left arrow key, and that all code written for the left arrow will also respond to the "A" key being used instead.

Back: Keyboard Input
Next: keyboard_get_map

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_set_numlock

Set the status of the keypad numberlock.

Syntax:

keyboard_set_numlock(value);

Argument | Description
value | Set this to true for "on" and false for "off"

Returns: N/A

Description

You can use this function to switch the keypad numberlock on or off (set to true for on, and false for off).

NOTE: This functionality is only available in the Windows exe builds and will not function on any other device.

Example:

if keyboard_get_numlock()
{
keyboard_set_numlock(0);
}
else
{
keyboard_set_numlock(1);
}

The above example code will get the state of the numberlock key and if it is on (true) it will set it to off (false) and vice-versa.

Back: Keyboard Input
Next: io_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_string

Holds a string of the last keys pressed.

Syntax:

keyboard_string;

Returns: String

Description

This variable holds a string containing the last (at most) 1024 characters typed on the keyboard. This string will only contain printable characters typed, but it will correctly respond to pressing the backspace key by erasing the last character. This variable is not read only and you can change it, for example to set it to "" (an empty string) if you handled it already, or use the String Functions to manipulate it.

Example:

if string_length(keyboard_string) > 15
{
keyboard_string = string_copy(keyboard_string, 1, 15);
}

The above code will limit the length of the keyboard string to 15 characters, removing those that are over that limit by copying the first fifteen characters back into the variable.

Back: Keyboard Input
Next: keyboard_set_map

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


keyboard_unset_map

Resets the keyboard mapping to its default state.

Syntax:

keyboard_get_map(key);

Returns: N/A

Description

With this function you can clear all re-mapped keys so that they return to their default state, ie: all keys to map to themselves.

Example:

if keyboard_check_pressed(vk_escape) keyboard_unset_map();

The above example code will reset all mapped keys to their default settings if the user presses the "escape" key.

Back: Keyboard Input
Next: keyboard_get_numlock

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Mouse Input

This section deals with the standard mouse input.

Mouse input is accepted on all platforms (on mobile devices it is accepted as a single touch. If you need to use multi-touch, you should be using the device specific functions) and has a number of constants that are used to specify the buttons being pressed. These constants are shown in the following table:

Constant | Description
mb_left | The left mouse button
mb_middle | The middle mouse button (this may not be valid for all target platforms)
mb_right | The right mouse button
mb_none | No mouse button
mb_any | Any of the mouse buttons

The following functions exist for the standard mouse button controls:

  1. mouse_button
  2. mouse_check_button
  3. mouse_check_button_pressed
  4. mouse_check_button_released
  5. mouse_clear
  6. mouse_last_button
  7. mouse_wheel_up
  8. mouse_wheel_down
  9. mouse_x
  10. mouse_y

You can also use the following window and view functions to get and set certain information based on the mouse too:

  1. window_mouse_set
  2. window_mouse_get_x
  3. window_mouse_get_y
  4. window_view_mouse_get_x
  5. window_view_mouse_get_y
  6. window_views_mouse_get_x
  7. window_views_mouse_get_y

Back: Mouse, Keyboard and Other Controls

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_button

Returns the currently pressed mouse button.

Syntax:

mouse_button;

Returns: Real

Description

This read only variable returns the mouse button that is currently being pressed (currently, as in, this step) and can return any of the special mouse constants except mb_any.

Example:

if mouse_button = mb_left
{
x -= 1;
}

This moves the current instance left if the left mouse button is down.

Back: Mouse Input
Next: mouse_check_button

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_check_button

Returns whether a given mouse button is currently down.

Syntax:

mouse_check_button(numb);

Argument | Description
numb | Which mouse button constant to check for.

Returns: Boolean

Description

This function will return true if the mouse button being checked is held down or false if it is not.

Example:

if mouse_check_button(mb_left)
{
instance_create(mouse_x, mouse_y, obj_Star);
}

The above code will check for the left mouse button and every step that it is held down will create an instance of the object indexed in "obj_Star".

Back: Mouse Input
Next: mouse_check_button_pressed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_check_button_pressed

Returns whether a given mouse button has just been pressed.

Syntax:

mouse_check_button_pressed(numb);

Argument | Description
numb | Which mouse button constant to check for.

Returns: Boolean

Description

This function will return true if the mouse button being checked has been pressed or false if it has not. This function will only be triggered once for any mouse button when it is first pressed and to trigger it again the button will need to have been released and pressed again.

Example:

if mouse_check_button_pressed(mb_left)
{
score += 50;
}

The above code will check to see if the left mouse button has been pressed and if it has it will add 50 to the score.

Back: Mouse Input
Next: mouse_check_button_released

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_check_button_released

Returns whether a given mouse button has just been released.

Syntax:

mouse_check_button_released(numb);

Argument | Description
numb | Which mouse button constant to check for.

Returns: Boolean

Description

This function will return true if the mouse button being checked has been released or false if it has not. This function will only be triggered once for any mouse button when it is released and to trigger it again the button will need to have been pressed and released again.

Example:

if mouse_check_button_released(mb_right)
{
speed = point_distance(x, y, mouse_x, mouse_y) / 10;
}

The above code will check to see if the right mouse button has been released and if it has it will set the speed of the instance to a tenth of the distance between the current x/y position and the mouse x/y position.

Back: Mouse Input
Next: mouse_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_clear

This will clear the state of the currently pressed mouse buttons.

Syntax:

mouse_clear(button);

Argument | Description
button | Which mouse button constant to check for.

Returns: Boolean

Description

This function will clear the state of any mouse buttons currently being used. This means that checks for their being held down/released will not return true until the player releases the buttons and represses them.

Example:

mouse_clear(mb_any);

The above code will clear the down state of all the mouse buttons.

Back: Mouse Input
Next: mouse_last_button

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_last_button

The last pressed mouse button.

Syntax:

mouse_lastbutton;

Returns: Real

Description

This variable returns the last mouse button that was pressed and can return any of the special mouse constants. You may also set this variable to use any of the constants too.

Example:

if mouse_lastbutton = mb_left
{
x -= 1;
}

This moves the current instance left if the last button pressed was the left mouse button.

Back: Mouse Input
Next: mouse_wheel_up

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_wheel_down

The last pressed mouse button.

Syntax:

mouse_wheel_down();

Returns: Bool

Description

This function returns true if the mouse wheel is being rotated downwards and false otherwise.

Example:

if mouse_wheel_down()
{
y += 10;
}

This moves the current instance down the screen if the mouse wheel is rotated upwards.

Back: Mouse Input
Next: mouse_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_wheel_up

The last pressed mouse button.

Syntax:

mouse_wheel_up();

Returns: Bool

Description

This function returns true if the mouse wheel is being rotated upwards and false otherwise.

Example:

if mouse_wheel_up()
{
y -= 10;
}

This moves the current instance up the screen if the mouse wheel is rotated upwards.

Back: Mouse Input
Next: mouse_wheel_down

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_x

The current x position of the mouse.

Syntax:

mouse_x;

Returns: Real

Description

This read-only variable returns the current x axis position of the mouse within the room.

Example:

x = median(64, mouse_x, room_width - 64);

The above code will maintain the instance at the mouse x position as long as it is within the limits of 64 pixels from either side of the room.

Back: Mouse Input
Next: mouse_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mouse_y

The current y position of the mouse.

Syntax:

mouse_y;

Returns: Real

Description

This read-only variable returns the current y axis position of the mouse within the room.

Example:

y = median(64, mouse_y, room_height - 64);

The above code will maintain the instance at the mouse y position as long as it is within the limits of 64 pixels from the top and bottom of the room.

Back: Mouse Input
Next: mouse_button

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Virtual Keys

Here you can find out how device virtual keys are used.

In order for your games to work properly on mobile devices with a touch screen, you may need to be able to assign areas of the screen to respond to certain things when they are touched by the user. This is done by assigning a "virtual Key" to an internally mapped standard keyboard key and then using the keyboard events that they generate to control your application. It is worth noting that these "virtual keys" are mapped to the screen position rather than room position and so the x/y values are absolute, based on the display size. This means that you don't need to worry about the use of views or the relative room coordinates, and can simply draw your key sprites and define your virtual keys in the Draw GUI Event of an object.

NOTE: These functions will not work on the Windows, Ubuntu (Linux), nor the MacOS, target platforms!

The available virtual key functions are:

  1. virtual_key_add
  2. virtual_key_show
  3. virtual_key_hide
  4. virtual_key_delete

Back: Mouse, Keyboard and Other Controls

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


virtual_key_add

Creates a virtual key with a set area and keycode, returning its id.

Syntax:

virtual_key_add(x, y, w, h, keycode);

Argument | Description
x | The x coordinate (left side) of the virtual key on the screen
y | The y coordinate (top side) of the virtual key on the screen
w | The width of the virtual key
h | The height of the virtual key
keycode | Which keyboard key event should be triggered by touching this area

Returns: index of virtual key

Description

This function enables you to map "touches" of a screen area to keyboard events. This means that once you have assigned an area to a virtual key, all touches on that area will trigger the keyboard event corresponding to the key you have mapped to the area. You can assign each virtual key you define to a variable too, which can then be used in the further virtual key functions to show, hide and delete them. These keys are assigned on a per room basis and will be automatically removed by GameMaker: Studio when changing rooms.

The actual position of the virtual key is based on the screen position rather than room position and so the x/y values are absolute on the screen. This means that you don't need to worry about the use of views or the relative room coordinates, and can simply draw your key sprites and define your virtual keys in the Draw GUI Event of an object.

Example:

global.Left = virtual_key_add(32, 32, 64, 64, vk_left);

The above code creates a virtual key 64x64 pixels square, positioned on the screen at (32, 32) which will trigger the vk_left event when touched and assigns the index of this virtual key to a global variable.

Back: Virtual Keys
Next: virtual_key_show

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


virtual_key_delete

Hides a given created virtual key previously shown on the screen of the device.

Syntax:

virtual_key_delete(index);

Argument | Description
index | The index of the virtual key to delete.

Returns: N/A

Description

If your game has different rooms or instances to control menus and game-play and other things, then it is probable that you will need to change the position and key maps of your virtual keys at some point. For that you can use this function to delete the old ones before creating the new ones (if necessary). Note, however, that the virtual keys will be automatically removed from the room at its end, so this function is only necessary when you wish to manually remove the keys before the room itself has finished.

Example:

virtual_key_delete(global.Left);

The above code deletes the virtual key indexed in the global variable "global.Left".

Back: Virtual Keys
Next: virtual_key_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


virtual_key_hide

Hides a given created virtual key previously shown on the screen of the device.

Syntax:

virtual_key_hide(index);

Argument | Description
index | The index of the virtual key to hide.

Returns: N/A

Description

Once you have created your virtual key for your devices, you may need to debug and test that it is correctly positioned and working properly and for that you would call the function virtual_key_show. However, you may need to toggle this view on and off, so you can also hide the virtual key with this function, using the index of the virtual key that you want to hide (previously created and stored using virtual_key_add). Once you are happy with things it is recommended that you create and place your own graphic in its area.

Example:

if global.Debug
{
virtual_key_show(global.Left);
}
else
{
virtual_key_hide(global.Left);
}

The above code checks the global variable "global.Debug" and if it tests true then the virtual key indexed in the variable "global.Left" will be drawn on the screen, and if it is false then the key will be hidden.

Back: Virtual Keys
Next: virtual_key_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


virtual_key_show

Shows a given created virtual key on the screen of the device.

Syntax:

virtual_key_show(index);

Argument | Description
index | The index of the virtual key to show.

Returns: N/A

Description

Once you have created your virtual key for your devices, you may need to debug and test that it is correctly positioned and working properly. For that you would call this function, using the index of the virtual key that you want to see (previously created and stored using virtual_key_add) which will draw a coloured rectangle to represent the key on the screen. Once you are happy with things it is recommended that you create and place your own graphic in its area.

NOTE: The rectangle being drawn will be affected by the blending, colour and alpha options set by the corresponding draw functions.

Example:

if global.Debug
{
virtual_key_show(global.Left);
}
else
{
virtual_key_hide(global.Left);
}

The above code checks the global variable "global.Debug" and if it tests true then the virtual key indexed in the variable "global.Left" will be drawn on the screen, and if it is false then the key will be hidden.

Back: Virtual Keys
Next: virtual_key_hide

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Movement and Collisions

These sections all deal with moving objects and collision checking

When making any game there are many different ways that you can get an instance from A to B. However, not all methods are the same and some are considerably better in certain circumstances than others! For example, in a platform game you would probably want to involve gravity and friction in the movement, whereas for a top down game it would probably be better to use a relative coordinate system. And just as there are many different ways to move an instance, there are also many different ways to stop an instance too, and so this part of the manual also has a section dedicated to collision checking. Finally, there is a section on motion planning which is another system for movement that can be used to actually avoid obstacles and collisions.

The following sections list all the available functions dealing with movement and collisions:

  1. Movement
  2. Motion Planning
  3. Collisions

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Collision Checking

This section deals with the various methods to check for collisions in GameMaker: Studio.

When planning motions or deciding on certain actions, it is often important to see whether there are collisions with other objects at certain places within the game world, and often choosing the right collision for the job is the most important task of all. GameMaker: Studio has a number of built in functions to help you deal with collisions correctly and in accordance with the needs of your project.

Simple Collision Checking

The following functions deal with the various ways in which you can have an instance check for collisions with another instance:

  1. place_empty
  2. place_free
  3. place_meeting
  4. position_empty
  5. position_meeting
  6. position_change
  7. position_destroy

Advanced Collision Checking

The following routines can be used for this (as well as other functions detailed in the sections relating to Moving Around and Instances). These collision functions all work slightly differently but they maintain three common arguments which we will explain here:

  • obj. This is where we specify the object that the function has to check for a collision with. It can be an instance id, an object type, or the special GM keyword all. It is also worth noting that if the object type chosen is the designated parent of other objects, then all children of that object will be included in this check too.

  • prec. This can be either true or false and relates to the precision of the collision checking. If set to true, then precise collisions are to be calculated (but only if the object being checked for has "precise" marked for its collision detection in its mask properties) which is a slightly more complex task for the CPU and so should be used with caution. If false then collisions will be calculated based on the bounding box of the object to be checked for.

  • notme. You may need to check for collisions with an object that has the same index as the object that runs the code, so to prevent the code finding a collision with itself, you can set this to true. If you are specifically looking for the instance of the object running the code, or it's not important, it can be left as false.

All these functions return either the id of an instance found to be colliding, or the special keyword noone when there is no collision. Note that if there are multiple collisions with the areas defined by these functions and instances of the given object, only one instance ID is returned, and it can be any one of the instances in the collision.

The following functions exist that deal with advanced collisions.

  1. collision_circle
  2. collision_ellipse
  3. collision_line
  4. collision_point
  5. collision_rectangle

Collision Checking Without Masks

All of the above functions are related to collision checking instances, and as such rely on the collision mask that is defined for the instance. However, there are many moments when you require to check for "collisions" with a point or an area, especially when your instance does not have a sprite assigned, or when you are working with the mouse etc... Therefore GameMaker: Studio also provides the following functions to help you in these situations:

  1. point_in_rectangle
  2. point_in_triangle
  3. point_in_circle
  4. rectangle_in_rectangle
  5. rectangle_in_triangle
  6. rectangle_in_circle

Back: Movement and Collisions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


collision_circle

Checks whether any instances of a given object collides with a circular, user defined area.

Syntax:

collision_circle( x1, y1, rad, obj, prec, notme );

Argument | Description
x1 | The x coordinate of the center of the circle to check.
y1 | The y coordinate of the center of the circle to check.
rad | The radius (distance in pixels from its center to its edge).
obj | The object to check for instance collisions.
prec | Whether the check is based on pixel-perfect collisions (true = slow) or its bounding box in general (false = fast).
notme | Whether the calling instance, if relevant, should be excluded (true) or not (false).

Returns: Instance id or noone

Description

Collision circle creates a circular zone of the radius given by the user around the points x1,y1 and then checks that zone for a collision with any instance of the object specified by the argument "obj". This check can be either precise or not, but for precise collisions to be enabled, the object or instance that you are checking for must also have precise collisions enabled for their sprite. If not, the default check is based on bounding boxes. The following image illustrates how this works:

Here, the instance in the middle is using a collision circle to check for ball objects. Now, the blue ones do not have a precise bounding box and as you can see, even if the sprite is not actually touching the circle, the collision can still happen (even if you set the precise option in the function to true) as the bounding box of that sprite over-laps the circular area defined by collision_circle. On the other hand, the green balls will only be considered in collision if the actual sprite over-laps with the defined circle. Remember, for precise collisions to be considered both the object sprite and the collision function must have precise marked as on. It should also be noted that the return value of the function can be the id of any one of the instances considered to be in collision.

Example:

if collision_circle(x, y, 20, obj_Cursor, false, true)
{
image_index = 1;
}
else image_index = 0;

The code above will check a circular are with a 20pixel radius for a collision with "obj_Cursor" and if there is one it will set the image_index of the object running the code to 1, but if there is not it will set the image_index of the object to 0.

Back: Collision Checking
Next: collision_ellipse


collision_ellipse

Checks whether any instances of a given object collides with a given elliptical area defined by the user.

Syntax:

collision_ellipse( x1, y1, x2, y2, obj, prec, notme );

Argument | Description
x1 | The x coordinate of the left side of the ellipse to check.
y1 | The y coordinate of the top side of the ellipse to check.
x2 | The x coordinate of the right side of the ellipse to check.
y2 | The y coordinate of the bottom side of the ellipse to check.
obj | The object to check for instance collisions.
prec | Whether the check is based on pixel-perfect collisions (true = slow) or its bounding box in general (false = fast).
notme | Whether the calling instance, if relevant, should be excluded (true) or not (false).

Returns: Instance id or noone

Description

Collision_ellipse uses the first four arguments (x1,y1,x2,y2) to define the width and height of an ellipse within the current room and then checks to see if any object that is defined by the "obj" argument is in collision with that area. This collision can be checked as precise or not, and you may also choose to check for the instance running the code itself or not. Consider this image:

Here, the instance in the middle is using a collision ellipse to check for ball objects. Now, the blue ones do not have a precise bounding box and as you can see, even if the sprite is not actually touching the ellipse, the collision can still happen (even if you set the precise option in the function to true) as the bounding box of that sprite over-laps the elliptical area defined by collision_circle. On the other hand, the green balls will only be considered in collision if the actual sprite over-laps the defined ellipse. Remember, for precise collisions to be considered both the object sprite and the collision function must have precise marked as on. It should also be noted that the return value of the function can be the id of any one of the instances considered to be in collision.

Example:

if collision_ellipse(50, 50, 200, 100, obj_Player, false, true)
{
instance_create(obj_Player.x, obj_Player.y, obj_Splash);
}

This will check an elliptical zone within the bounds of 50x, 50y and 200x, 100y for the object "obj_Player". If there is a collision with that object, then it will create an instance of "obj_Splash" at the x/y coordinates of obj_Player.

Back: Collision Checking
Next: collision_line


collision_line

Checks whether any instances of a given object collide with a given line, and if there is it returns the id of one of those instances.

Syntax:

collision_line( x1, y1, x2, y2, obj, prec, notme );

Argument | Description
x1 | The x coordinate of the start of the line.
y1 | The y coordinate of the start of the line.
x2 | The x coordinate of the end of the line.
y2 | The y coordinate of the end of the line.
obj | The object to check for instance collisions.
prec | Whether the check is based on pixel-perfect collisions (true = slow) or its bounding box in general (false = fast).
notme | Whether the calling instance, if relevant, should be excluded (true) or not (false).

Returns: Instance id or noone

Description

Collision line checks along a line from point x1,y1 to point x2,y2 for a collision with any instance of the object specified by the argument "obj". this check can be either precise or not, but for precise collisions to be enabled, the object or instance that you are checking for must also have precise collisions enabled for their sprite. If not, the default check is based on bounding boxes. The following image illustrates how this works:

Remember, for precise collisions to be considered both the object sprite and the collision function must have precise marked as on. It should also be noted that the return value of the function can be the id of any one of the instances considered to be in collision along the line, so if three instance overlap the defined line, any one of their ids could be the return value of the function.

Example:

with (obj_Enemy)
{
if collision_line(100, 400, 100, 600, id, false, false) instance_destroy();
}

This code gets all instances of "obj_Enemy" to check along a line from 100x, 400y to 100x, 600y for a collision with themselves, and if there is one then they are destroyed.

Back: Collision Checking
Next: collision_point


collision_point

Checks a specific, user defined point for a collision with the an instance of the chosen object.

Syntax:

collision_point( x, y, obj, prec, notme );

Argument | Description
x | The x coordinate of the point to check.
y | The y coordinate of the point to check.
obj | The object to check for instance collisions.
prec | Whether the check is based on pixel-perfect collisions (true = slow) or its bounding box in general (false = fast).
notme | Whether the calling instance, if relevant, should be excluded (true) or not (false).

Returns: Instance id or noone

Description

Collision point checks the point specified by the arguments x1,y1 for a collision with any instance of the object specified by the argument "obj". this check can be either precise or not, but for precise collisions to be enabled, the object or instance that you are checking for must also have precise collisions enabled for their sprite. If not, the default check is based on bounding boxes. The following image illustrates how this works:

Remember, for precise collisions to be considered both the object sprite and the collision function must have precise marked as on. It should also be noted that the return value of the function can be the id of any one of the instances considered to be in collision, so if three instance overlap at that point, any one of their ids could be the return value of the function.

Example:

if collision_point(x, y, obj_Cursor, false, true)
{
Score += 10S;
}

Here we are checking the point at the position of the object that has the code for the object "obj_Cursor". If there is one, then we add 10 onto the score variable.

Back: Collision Checking
Next: collision_rectangle


collision_rectangle

Checks to see whether any instance of a given object collides with a user defined rectangular area.

Syntax:

collision_rectangle( x1, y1, x2, y2, obj, prec, notme );

Argument | Description
x1 | The x coordinate of the left side of the rectangle to check.
y1 | The y coordinate of the top side of the rectangle to check.
x2 | The x coordinate of the right side of the rectangle to check.
y2 | The y coordinate of the bottom side of the rectangle to check.
obj | The object to check for instance collisions.
prec | Whether the check is based on pixel-perfect collisions (true = slow) or its bounding box in general (false = fast).
notme | Whether the calling instance, if relevant, should be excluded (true) or not (false).

Returns: Instance id or noone

Description

Collision_rectangle uses the first four arguments (x1,y1,x2,y2) to define an area within the current room and then checks to see if any object that is defined by the "obj" argument is in collision with that area. This collision can be checked as precise or not, and you may also choose to check for the instance running the code itself or not. Consider this image:

Here, the instance in the middle is using a collision rectangle to check for ball objects. Now, the blue ones do not have a precise bounding box and as you can see, even if the sprite is not actually touching the rectangle, the collision will still happen (even if you set the precise option in the function to true) as the bounding box of that sprite over-laps the collision_rectangle. On the other hand, the green balls will only be considered in collision if the actual sprite over-laps the rectangle. Remember, for precise collisions to be considered both the object sprite and the collision function must have precise marked as on. It should also be noted that the return value of the function can be the id of any one of the instances considered to be in collision.

Example:

var inst;
inst = collision_rectangle(50, 50, 200, 100, obj_Ball, false, true);
if inst != noone
{
with (inst) instance_destroy();
}

This short code uses collision_rectangle check an area in the room from 50x, 50y (top left of the rectangle) to 200x, 200y (bottom right of the rectangle) for an instance of an object called "obj_ball". It stores the return value in a temporary variable which is then checked to see if that value is an instance id, or the keyword noone. If it is not noone then it uses the stored instance id to destroy the object.

Back: Collision Checking
Next: point_in_rectangle


place_empty

Checks for a collision with any other instance.

Syntax:

place_empty(x, y);

Argument | Description
x | The x position to check.
y | The y position to check.

Returns: Boolean.

Description

You can use this function to check and see if the calling instance would collide with any other instance in your game. Now, it should be noted that for this to work, the instance running the code must have a valid collision mask (either for the sprite itself, or through the mask_index.) and it will only register collisions with those instances that also have a valid mask.

The function itself basically works by taking the instance and testing for collisions when placed at the position specified by the x/y arguments. The collision checking can be either precise or based on the bounding box of the instance, depending on what kind of collision mask has been selected.

Note that the given x/y coordinates will be floored to the nearest integer before the check is performed.

Example:

if place_empty(mouse_x, mouse_y)
{
x = mouse_x;
y = mouse_y;
}

The above code will check for a collision with any other instance if the calling instance were to be placed at the same position as the mouse. If there is no collision detected, then the instance has its x/y coordinates set to those of the mouse.

Back: Collision Checking
Next: place_free

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


place_free

Checks for a collision with any instance flagged as solid.

Syntax:

place_free(x, y);

Argument | Description
x | The x position to check.
y | The y position to check.

Returns: Boolean.

Description

You can use this function to check and see if the calling instance would collide with any instance flagged as solid in your game. Now, it should be noted that for this to work, the instance running the code must have a valid collision mask (either for the sprite itself, or through the mask_index.) and it will only register collisions with those solid flagged instances that also have a valid mask.

The function itself basically works by taking the instance and testing for collisions with only solid flagged instances when placed at the position specified by the x/y arguments. The collision checking can be either precise or based on the bounding box of the instance, depending on what kind of collision mask has been selected.

Note that the given x/y coordinates will be floored to the nearest integer before the check is performed.

Example:

if place_free(mouse_x, mouse_y)
{
x = mouse_x;
y = mouse_y;
}

The above code will check for a collision with any solid flagged instance if the calling instance were to be placed at the same position as the mouse. If there is no collision detected, then the instance has its x/y coordinates set to those of the mouse.

Back: Collision Checking
Next: place_meeting

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


place_meeting

Checks for a collision between two instances at a given position

Syntax:

place_meeting(x, y, obj);

Argument | Description
x | The x position to check.
y | The y position to check.
obj | The instance or object to check for.

Returns: Boolean

Description

With this function you can check a position for a collision with another instance or all instances of an object using the collision mask of the instance that runs the code for the check. When you use this you are effectively asking GameMaker: Studio to move the instance to the new position, check for a collision, move back and tell you if a collision was found or not. This will work for precise collisions, but only if both the instance and the object being checked for have precise collision masks selected otherwise only bounding box collisions are applied. This function also accepts the special keywords all and other. Please note that should you need to get the unique instance id of the object being collided with, you should use instance_place.

Note that the given x/y coordinates will be floored to the nearest integer before the check is performed.

Example:

if keyboard_check(vk_left)
{
if !place_meeting(x - 5, y, obj_wall) x -=5;
}

The above code checks to see if there is not a collision to the left of the instance and moves the instance if there is none.

Back: Collision Checking
Next: position_empty

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


point_in_circle

Checks to see whether a given point falls within the defined circular area.

Syntax:

point_in_circle(px, py, x1, y1, r);

Argument | Description
px | The x coordinate of the point to check.
py | The y coordinate of the point to check.
x1 | The x coordinate of the circle centre.
y1 | The y coordinate of the circle centre.
r | The radius of the circle.

Returns: Boolean

Description

When using this function, you define a circular area and GameMaker: Studio will work out whether the given point falls within its bounds or not. If the point falls within the defined circle the function will return true otherwise the function will return false.

Example:

if point_in_circle(mouse_x, mouse_y, x, y, 16)
{
over = true;
}
else
{
over = false;
}

The above code uses the point_in_circle function to check if the mouse position falls within the defined circular area, setting the variable "over" to true if it does, or false otherwise.

Back: Collision Checking
Next: rectangle_in_rectangle


point_in_rectangle

Checks to see whether a given point falls within the defined rectangular area.

Syntax:

point_in_rectangle(px, py, x1, y1, x2, y2);

Argument | Description
px | The x coordinate of the point to check.
py | The y coordinate of the point to check.
x1 | The x coordinate of the left side of the rectangle to check.
y1 | The y coordinate of the top side of the rectangle to check.
x2 | The x coordinate of the right side of the rectangle to check.
y2 | The y coordinate of the bottom side of the rectangle to check.

Returns: Boolean

Description

When using this function, you define a rectangular area and GameMaker: Studio will work out whether the given point falls within its bounds or not. If the point falls within the defined rectangle the function will return true otherwise the function will return false.

Example:

if point_in_rectangle(mouse_x, mouse_y, x -10, y - 10, x + 10, y + 10)
{
audio_play_sound(snd_click, 0, false);
}

This short code checks the mouse position against the defined rectangular area and plays a sound if it falls within the bounds.

Back: Collision Checking
Next: point_in_triangle


point_in_triangle

Checks to see whether a given point falls within the defined triangular area.

Syntax:

point_in_triangle(px, py, x1, y1, x2, y2, x3, y3);

Argument | Description
px | The x coordinate of the point to check.
py | The y coordinate of the point to check.
x1 | The x coordinate of the first corner of the triangle to check.
y1 | The y coordinate of the first corner of the triangle to check.
x2 | The x coordinate of the second corner of the triangle to check.
y2 | The y coordinate of the second corner of the triangle to check.
x3 | The x coordinate of the third corner of the triangle to check.
y3 | The y coordinate of the third corner of the triangle to check.

Returns: Boolean

Description

When using this function, you define a triangular area and GameMaker: Studio will work out whether the given point falls within its bounds or not. If the point falls within the defined triangle the function will return true otherwise the function will return false.

Example:

var inst = instance_nearest(x, y, obj_Player);
if instance_exists(inst)
{
var x1 = x + lengthdir_x(100, image_angle - 45);
var y1 = y + lengthdir_y(100, image_angle - 45);
var x2 = x + lengthdir_x(100, image_angle + 45);
var y2 = y + lengthdir_y(100, image_angle + 45);
if point_in_triangle(inst.x, inst.y, x, y, x1, y1, x2, y2)
{
can_see = true;
}
}

The above code uses the point_in_triangle function as a "cone of vision" to check for an instance of "obj_player", setting a variable to true should the objects x/y position fall within the defined triangle.

Back: Collision Checking
Next: point_in_circle


position_change

Changes all instances at a given position to a different object.

Syntax:

position_change(x, y, obj, perf);

Argument | Description
x | The x coordinate of where to change colliding instances.
y | The y coordinate of where to change colliding instances.
obj | The new object the calling object will change into.
perf | Whether to perform that new object's Create event (true) or not (false).

Returns: N/A

Description

This function will check a position for a collision with any instances at the given point, and if there is one, it will change all instances in collision to be instances of the chosen object. You can set the "perf" argument to true which will force GameMaker: Studio to perform the destroy event of the found instance and the create event of the new instance, or false to not perform either of these events. Please note, that if you choose not to perform the destroy and create events, any instance created that uses a variable normally defined in the create event will crash the game as that variable will no longer exist.

Example:

position_change(200, 200, obj_Bird, true);

This will change all instances colliding at point (200,200) into an instance of "obj_Bird", performing "obj_Bird"s Create event for each of them in the process.

Back: Collision Checking
Next: position_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


position_destroy

Destroys all instances that collide with a given position.

Syntax:

position_destroy(x, y);

Argument | Description
x | The x coordinate of where to destroy colliding instances.
y | The y coordinate of where to destroy colliding instances.

Returns: N/A

Description

This function simply destroys all instances that are found to be in collision with the specified position. Collisions are based on the mask of the instances, and if any part of the mask over-laps with the target point it then the function will destroy that instance.

Example:

if mouse_check_button_pressed(mb_left)
{
position_destroy(mouse_x, mouse_y);
}

This will destroy all instances that collide with the position of the mouse cursor when the left mouse button is pressed.

Back: Collision Checking
Next: collision_circle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


position_empty

Returns whether a given position is empty or not.

Syntax:

position_empty(x, y);

Argument | Description
x | The x position to check.
y | The y position to check.

Returns: Boolean

Description

This function will check to see if a given position enters into collision with any instance with a valid collision mask at the given position.

Example:

var xx, yy;
xx = random(room_width);
yy = random(room_height);
if position_empty(xx, yy)
{
instance_create(xx, yy, obj_Bomb);
}

This will check a random position somewhere in the room for a collision and if there is none it will create an instance of obj_Bomb.

Back: Collision Checking
Next: position_meeting

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


position_meeting

Checks a position for a collision with a specific object.

Syntax:

position_meeting(x, y, obj);

Argument | Description
x | The x position to check.
y | The y position to check.
obj | The object (or instance id, or the keywords "all" or "other") to check for a collision with.

Returns: Boolean

Description

With this function you can check a position for a collision with another instance or all instances of an object. When you use this you are checking a single point in the room for an instance or an object. This check will be done against the bounding box of the instance or against the mask of the instance if that instance has precise collisions checked. If you need to know get the unique instance id if the object being collided with you should use instance_position. This function also accepts the special keywords all and other.

Example:

if mouse_check_button(mb_left)
{
if !position_meeting(mouse_x, mouse_y, all) instance_create(mouse_x, mouse_y, obj_Wall);
}

The above code checks for the left mouse button, and if it is pressed it checks the mouse x/y position for a collision with any instance. If there is none, then an instance of "obj_Wall" is created.

Back: Collision Checking
Next: position_change

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


rectangle_in_circle

Checks to see if a rectangular area collides, or is encompassed by, a defined circular area.

Syntax:

rectangle_in_circle(sx1, sy1, sx2, sy2, x, y, rad);

Argument | Description
sx1 | The x coordinate of the left side of the source rectangle.
sy1 | The y coordinate of the top side of the source rectangle.
sx2 | The x coordinate of the right side of the source rectangle.
sy2 | The y coordinate of the bottom side of the source rectangle.
x | The x coordinate of the centre of the circle
y | The y coordinate of the centre of the circle.
rad | The x coordinate of the second side of the triangle to check.

Returns: Real.

Description

This function will check a rectangular area that you define to see if it is either not in collision, completely within the destination bounds, or if it is simply touching, a defined circular area. If they are not touching at all the function will return 0, if the source is completely within the destination it will return 1, and if they are simply overlapping then it will return 2. The image below illustrates this:

Example:

inst = instance_nearest(x, y, obj_Bullet);
if instance_exists(inst)
{
if rectangle_in_circle(inst.x - 5, inst.y - 5, inst.x + 5, inst.y + 5, x, y - 25, 20) > 0
{
hit = true;
}
}

The above code uses the rectangle_in_circle function to check for a collision within a circular area and the rectangle around a found instance. If there is a collision (either an edge overlap or encompassed) then a variable will be set to true.

Back: Collision Checking
Next: place_empty


rectangle_in_rectangle

Checks to see if a rectangular area collides, or is encompassed by, another rectangular area.

Syntax:

rectangle_in_rectangle(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2);

Argument | Description
sx1 | The x coordinate of the left side of the source rectangle.
sy1 | The y coordinate of the top side of the source rectangle.
sx2 | The x coordinate of the right side of the source rectangle.
sy2 | The y coordinate of the bottom side of the source rectangle.
dx1 | The x coordinate of the left side of the destination rectangle to check against.
dy1 | The y coordinate of the top side of the destination rectangle to check against.
dx2 | The x coordinate of the right side of the destination rectangle to check against.
dy2 | The y coordinate of the bottom side of the destination rectangle to check against.

Returns: Real.

Description

This function will check two rectangular areas that you define to see if the source rectangle is either not in collision, completely within the destination rectangles bounds, or if they are simply touching. If they are not touching at all the function will return 0, if the source is completely within the destination it will return 1, and if they are simply overlapping then it will return 2. The image below illustrates this:

Example:

switch(rectangle_in_rectangle(x - 50, y - 50, x + 50, y + 50, mouse_x - 50, mouse_y - 50, mouse_x + 50, mouse_y + 50))
{
case 0: image_blend = c_yellow; break;
case 1: image_blend = c_red; break;
case 2: image_blend = c_orange; break;
}

The above code checks two rectangular areas for collision, and will set the instance image_blend based on the return value.

Back: Collision Checking
Next: rectangle_in_triangle


rectangle_in_triangle

Checks to see if a rectangular area collides, or is encompassed by, a defined triangular area.

Syntax:

rectangle_in_triangle(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, dx3, dy3);

Argument | Description
sx1 | The x coordinate of the left side of the source rectangle.
sy1 | The y coordinate of the top side of the source rectangle.
sx2 | The x coordinate of the right side of the source rectangle.
sy2 | The y coordinate of the bottom side of the source rectangle.
x1 | The x coordinate of the first side of the triangle to check.
y1 | The y coordinate of the first side of the triangle to check.
x2 | The x coordinate of the second side of the triangle to check.
y2 | The y coordinate of the second side of the triangle to check.
x3 | The x coordinate of the third side of the triangle to check.
y3 | The y coordinate of the third side of the triangle to check.

Returns: Real.

Description

This function will check a rectangular area that you define to see if it is either not in collision, completely within the destination bounds, or if it is simply touching, a defined triangular area. If they are not touching at all the function will return 0, if the source is completely within the destination it will return 1, and if they are simply overlapping then it will return 2. The image below illustrates this:

Example:

var inst = instance_nearest(x, y, obj_Player);
if instance_exists(inst)
{
var x1 = x + lengthdir_x(100, image_angle - 45);
var y1 = y + lengthdir_y(100, image_angle - 45);
var x2 = x + lengthdir_x(100, image_angle + 45);
var y2 = y + lengthdir_y(100, image_angle + 45);
if rectangle_in_triangle(inst.bbox_left, inst.bbox_top, inst.bbox_right, inst.bbox_bottom, x, y, x1, y1, x2, y2) == 1
{
can_see = true;
}
}

The above code uses the rectangle_in_triangle function as a "cone of vision" to check for an instance of "obj_player". If the full bounding box is within the given triangular area, it will set a variable to true.

Back: Collision Checking
Next: rectangle_in_circle


Motion Planning

This section explains the use of the motion planning functions.

In many games you want opponents, npc's, enemies etc... to interact with the player and show certain intelligence when moving around ie: you want them to avoid obstacles, plan routes and generally not bump into everything in their path when moving around! To aid in this GameMaker: Studio has a series of functions that deal with motion planning.

Motion planning in GameMaker: Studio is dealt with by the mp_ functions, which themselves are split into three groups:

mp_linear functions

This kind of function tries to compute a collision-free path for the instance. Once this path has been computed you can assign it to the instance to move towards the goal. The computation of the path will take some time but after that the execution of the path will be fast. Of course this is only valid if the situation has not changed in the meantime. For example, if obstacles change you possibly will need to recompute the path. Again notice that these functions might fail and that no path is found for the instance.

  1. mp_linear_step
  2. mp_linear_step_object
  3. mp_linear_path
  4. mp_linear_path_object

mp_potential functions

These are the basic avoidance functions and good for simple AI. They work by making an instance take a step towards a particular goal position while trying to go straight if possible but taking a different direction if required. These functions should be used in the step event of an instance.

  1. mp_potential_settings
  2. mp_potential_step
  3. mp_potential_step_object
  4. mp_potential_path
  5. mp_potential_path_object

mp_grid functions

The final type of function use a much more complex mechanism based on a grid-based approach (sometimes called an A* algorithm). It will be much more successful in finding paths (although it still might fail) and will find the shortest paths possible but it requires more work on your side to set it up.

The global idea is as follows - First of all we create a grid that covers the room (or the relevant part of it). You can choose to use a fine grid, which will be slower, or a coarse grid, but both of them should be based on the resolution of the room so that the path-finding is as accurate as possible. For example, if you have a room that is 400x200 pixels, you can have a grid resolution of 40, or 20, or 10... it all depends on how accurate you need the path to be and how much processing you want GameMaker to do to generate it.

Next, for all relevant objects that we want to avoid we need to determine the grid cells they overlap (based either on their bounding boxes or their precise sprite) and mark these cells as being forbidden. So a cell will be marked totally forbidden, even if an obstacle is only partially overlapping.

Finally we specify a start position and a goal position, both of which must lie in free cells, and the function then computes the shortest path possible between these two positions. The path will run between the centers of all free cells, so if the cells are large enough so that the instance placed at its center will lie completely inside it this will be successful. This path is then assigned to the instance to follow using the path_ functions. You should realise how important cell size is for this as the cells must be large enough so that the moving object placed with its origin on the center of a cell will lie completely inside the cell. (Be careful about the position of the origin of the object. Also realize that you can shift the path if the origin of the object is not in its center!) On the other hand, the smaller the cells the more possible paths exist. If you make cells too large, openings between obstacles may get closed because all cells intersect an obstacle.

  1. mp_grid_create
  2. mp_grid_destroy
  3. mp_grid_path
  4. mp_grid_add_cell
  5. mp_grid_add_instances
  6. mp_grid_add_rectangle
  7. mp_grid_get_cell
  8. mp_grid_clear_all
  9. mp_grid_clear_cell
  10. mp_grid_clear_rectangle
  11. mp_grid_to_ds_grid
  12. mp_grid_draw

The grid-based approach is very powerful (and is used in many professional games) but it requires that you do some careful thinking as you must determine which area and cell size are good enough for solving the game. Also, you must determine which objects must be avoided and whether precise checking is important. All these parameters strongly influence the efficiency of the approach. You must also decide whether it is actually necessary as maybe one of the less costly mp_ functions can do the job just as well.

Whatever you choose, it should be noted that in many situations not one of the above will give you a perfect solution and that you will have to "mix and match" the functions, using one or the other depending on the situation within your game.

Back: Movement and Collisions
Next: Collisions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_add_cell

Marks the indicated cell as being forbidden to the path-finding functions.

Syntax:

mp_grid_add_cell(id, h, v);

Argument | Description
id | Index of the mp_grid that is to be used
h | Horizontal position of the cell in the grid
v | Vertical position of the cell in the grid

Returns: N/A

Description

With this function we can mark individual cells within the mp_grid as being "forbidden" meaning that the path finding functions will not ever cross them. Now, normally you work in x/y room coordinates, and not in mp_grid cell coordinates. So let's consider the following image which shows how the two can correlate:

As you can see the mp_grid is numbered as a series of cells (starting at 0,0 in the upper left corner), and when you place this grid over the room there is a direct correlation between the room coordinates (which also start at 0,0 in the top left) and the cells within the grid. In the image you can see that an instance at the position 260,130 falls on the grid cell 8,4. You can calculate mathematically the exact cell that a position lands on easily by either dividing the number by the grid resolution and then rounding down or (if you are using power of 2 grid resolutions like 8, 16, 32 etc...) you can use the bitwise operators. It should be noted that the bitwise operation is faster. The example below shows both methods.

Example:

with (obj_Wall)
{
mp_grid_add_cell(grid, floor(x / 32), floor(y / 32));
}
with (obj_Door)
{
mp_grid_add_cell(grid, x>>5, y>>5);
}

The above code will make all "obj_Wall" and all obj_Door add their equivalent cell positions into the mp_grid indexed in the variable "grid". In the first part of the example, this is done by taking the x/y coordinates of the object and dividing them by the resolution of the grid (using floor to keep the values as integers), and in the second part (since the grid resolution is a power of 2) it is done by bit-shifting the x,y coordinates 5 places to the right.

Back: Motion Planning
Next: mp_grid_add_instances

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_add_instances

Marks all cells that an instance of the indicated object overlaps as being forbidden.

Syntax:

mp_grid_add_instances(id, obj, prec);

Argument | Description
id | Index of the mp_grid that is to be used
obj | Object index, or instance id, of the instances to be added into the mp_grid
prec | Whether the check is based on pixel-perfect collisions (true = slow) or its bounding box in general (false = fast).

Returns: N/A

Description

This function uses the instance collision mask (decided by the sprite properties or the mask index of the calling instance) to mark cells as forbidden or not, where forbidden cells cannot be crossed by any of the pathfinding functions. You can specify in the function whether to consider precise collisions or not and the forbidden cells marked will change depending on this setting. This image illustrates this behaviour:

The two instances above have been added into the mp_grid using the mp_grid_add_instances function with precise being set as true. As you can see the, green instance has only marked the grid squares it "touches" as forbidden, due to the fact that its sprite mask is also set to precise. However the second instance has marked other cells too which don't appear to be touching. This is because the sprite mask is not set to precise, meaning that even if you are using the precise setting in the function, only the bounding box of the sprite will be considered. This is also what would happen if you set the precise argument of the function to false - even instances with a precise sprite mask will be added into the grid based on their bounding boxes.

Example:

mp_grid_add_instances(grid, obj_Wall, 1);

The above code will add all instances of "obj_Wall" into the mp_grid indexed in the variable "grid" using the precise collision mask rather than the bounding box.

Back: Motion Planning
Next: mp_grid_add_rectangle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_add_rectangle

Marks all cells that overlap the indicated rectangle as being forbidden.

Syntax:

mp_grid_add_rectangle(id, x1, y1, x2, y2);

Argument | Description
id | Index of the mp_grid that is to be used
x1 | The x coordinate of the left side of the rectangle to check.
y1 | The y coordinate of the top side of the rectangle to check.
x2 | The x coordinate of the right side of the rectangle to check.
y2 | The x coordinate of the bottom side of the rectangle to check.

Returns: N/A

Description

This function asks you to define a rectangle within the room, and then it marks all mp_grid cells "touch" that rectangle as being forbidden, meaning that the path-finding functions cannot cross them. The image below illustrates how this works:

As you can see, the rectangle defined by (50, 90) to (200, 180) marks all the equivalent mp_grid cells that it touches as being forbidden.

Example:

mp_grid_add_rectangle(grid, 0, 0, 100, 200);

The above code will mark as forbidden all cells of the mp_grid indexed in the variable "grid" that fall within the area 0,0 to 100,200.

Back: Motion Planning
Next: mp_grid_get_cell

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_clear_all

Mark all cells in the grid to be free.

Syntax:

mp_grid_clear_all(id);

Argument | Description
id | Index of the mp_grid that is to be used

Returns: Boolean.

Description

With this function you can clear an mp_grid of all "forbidden" cells.

Example:

if !instance_exists(obj_Player) mp_grid_clear_all(grid);

The above code will clear the mp_grid indexed in the variable "grid", marking all the cells as free, if an instance of the object "obj_Player" no longer exists in the room.

Back: Motion Planning
Next: mp_grid_clear_cell

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_clear_cell

Clears the indicated cell of an mp_grid.

Syntax:

mp_grid_clear_cell(id, h, v);

Argument | Description
id | Index of the mp_grid that is to be used
h | Horizontal position of the cell to clear
v | vertical position of the cell to clear

Returns: Boolean.

Description

This function can be used to clear a specific "cell" of an mp_grid. Cells are not calculated as room coordinates, but rather as grid coordinates, where (0,0) is the top let corner of the grid. this means that to clear a cell at a specific position in the room, we must change the x and y coordinates into cell coordinate dividing them by the resolution of the mp_grid. The code example below shows how this works.

Example:

with (obj_Box)
{
mp_grid_clear_cell(grid, floor(x / 32), floor(y /32));
instance_destroy();
}

The above code will make all "obj_Box" destroy themselves and have them mark the cells they occupied in the mp_grid indexed in the variable "grid" as free. In this example, we find the appropriate cell by taking the x/y coordinate of the object and dividing them by the resolution of the grid (using floor to keep the values as integers);

Back: Motion Planning
Next: mp_grid_clear_rectangle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_clear_rectangle

Marks all cells that overlap the indicated rectangle as being free.

Syntax:

mp_grid_clear_rectangle(id, x1, y1, x2, y2);

Argument | Description
id | Index of the mp_grid that is to be used
x1 | The x coordinate of the left side of the rectangle to check.
y1 | The y coordinate of the top side of the rectangle to check.
x2 | The x coordinate of the right side of the rectangle to check.
y2 | The x coordinate of the bottom side of the rectangle to check.

Returns: Boolean.

Description

With this function you can define an area in room coordinates which will then clear the corresponding cells in the specified mp_grid. Even if a cell partially falls within the defined rectangular region it will be cleared.

Example:

mp_grid_clear_rectangle(grid, 0, 0, 100, 200);

The above code will mark as free all cells of the mp_grid indexed in the variable "grid" that fall within the area 0,0 to 100,200.

Back: Motion Planning
Next: mp_grid_to_ds_grid

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_create

This function creates an mp_grid for the motion planning functions.

Syntax:

mp_grid_create(xstart, ystart, hcells, vcells, cellwidth, cellheight):

Argument | Description
xstart | Starting x coordinate of the mp_grid in the room
ystart | Starting y coordinate of the mp_grid in the room
hcells | Number of horizontal cells that the mp_grid will contain
vcells | Number of vertical cells that the mp_grid will contain
cellwidth | The width (in pixels) of each individual cell of the mp_grid
cellheight | The height (in pixels) of each individual cell of the mp_grid

Returns: Real.

Description

With this function you can create an mp_grid for the motion planning functions. It returns an index that must be used in all other mp_grid function calls. The x and y coordinates indicate the position of the top-left corner of the grid, hcells and vcells indicate the number of horizontal and vertical cells to be created within the grid, and cell width and cell height indicate the size of the cells in pixels. You can create and maintain multiple grid structures at the same moment if you need them for different things, but be aware that these are complex functions and the more you use and the higher the cell resolution then the slower your game could be.

Example:

globalvar grid;
grid = mp_grid_create(0, 0, room_width / 32, room_height /32, 32, 32)

The above code creates a global variable "grid", then generates an mp_grid and assigns its index (id) to that variable for use in all further mp_grid function calls. The grid covers the room, with a cell resolution of 32x32 pixels. This means that, for example, in a room that is 640x480, the grid would contain 300 cells: 20 horizontal cells (640 / 32) multiplied by 15 vertical cells (480 /32) gives 300 cells

Back: Motion Planning
Next: mp_grid_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_destroy

Destroys the indicated mp_grid and frees up its memory.

Syntax:

mp_grid_destroy(id);

Argument | Description
id | Index of the mp_grid that is to be destroyed

Returns: N/A.

Description

You can use this function to destroy the indicated mp_grid and free up the memory allocated it. It is essential that you call this whenever the mp_grid is finished with or you could potentially get a memory leak, meaning that your game will slow down over time and eventually crash.

NOTE: Destroying an mp_grid when there are still instances using it will result in an error!

Example:

if timer = 0
{
mp_grid_destroy(grid);
room_goto(rm_Menu);
}

The above code will destroy the mp_grid indexed in the variable "grid" if the variable "timer" is equal to 0, and then goto another room.

Back: Motion Planning
Next: mp_grid_path

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_draw

This function draws the specified mp_grid.

Syntax:

mp_grid_draw(id);

Argument | Description
id | Index of the mp_grid that is to be drawn

Returns: Boolean.

Description

This function will draw the specified mp_grid, marking free cells as green and forbidden cells as red. This function is essential as a debug tool but it should be noted that it is very slow and only works when used in the draw event of the instance.

Example:

draw_set_alpha(0.3);
mp_grid_draw(grid);
draw_set_alpha(1);

The above code will draw the mp_grid indexed in the variable "grid" as a semi-transparent overlay (but only if the instance running the code has a depth lower than all the rest).

Back: Motion Planning

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_get_cell

Return whether a cell in the mp_grid is occupied or not.

Syntax:

mp_grid_get_cell(id, x , y);

Argument | Description
id | Index of the mp_grid that is to be used
x1 | The x coordinate of the grid to check.
y1 | The y coordinate of the grid to check.

Returns: Real

Description

With this function you can check any given cell of the mp_grid to see if it has been flagged as occupied or not, giving the index of the (previously created) mp_grid and the x an y coordinates of the cell to check. If it has been occupied or the position being checked is out of the grids bounds then the function will return -1 otherwise it will return 0.

Example:

if mp_grid_get_cell(grid, mouse_x div 16, mouse_y div 16) == -1
{
image_blend = c_red;
}
else
{
image_blend = c_lime;
}

The above code will check the mp_grid cell that corresponds to the mouse position and if it is occupied it sets the image_blend variable to red, and if it is not occupied it sets it to green.

Back: Motion Planning
Next: mp_grid_clear_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_path

This function computes a path through the given mp_grid.

Syntax:

mp_grid_path(id, path, xstart, ystart, xgoal, ygoal, allowdiag);

Argument | Description
id | Index of the mp_grid that is to be used
path | index of the path that is to be used by the function
x start | Starting x coordinate of the new path
y start | Starting y coordinate of the new path
xgoal | Finishing x coordinate of the new path
ygoal | Finishing y coordinate of the new path
allowdiag | Indicates whether diagonal moves are allowed instead of just horizontal or vertical

Returns: Boolean.

Description

With this function you can create a path that will navigate from a start point to a finish point using an mp_grid that you have previously defined, avoiding any obstacles that have already been added into the grid. The xstart and ystart arguments indicate the start of the path in room coordinates, while xgoal, ygoal arguments indicate the destination. You can also select either horizontal/vertical movement only, or allow full diagonal movements by specifying true in the allowdiag argument. The function returns either true (it succeeded in finding a path) or false (it failed) as well as setting the chosen path. In the following image, you can see how this all works together:

As you can see, the "pipe" objects have been added into the grid, meaning that any path created has to go around them. There are two paths created in the image, one (green) has been made with diagonals allowed and the other (red) without. The difference between the two is pretty obvious with the green path appearing much more "elegant" and direct, but it all depends what use you are going to put them to which one you prefer. Note that the path is independent of the current instance - it is a path through the grid, not a path for a specific instance, even though a specific instance may have the variable that stores the path index. You may also need to debug these paths to see how they are made and interact within the game environment, in which case you should be using the draw_path function.

NOTE: The path must have been previously created (either in code with path_add or as a resource) and will be replaced by the path generated by this function.

Example:

globalvar grid;
grid = mp_grid_create(0, 0, room_width div 32, room_height div 32, 32, 32);
mp_grid_add_instances(grid, obj_wall, false);
with (obj_Enemy)
{
path = path_add();
if mp_grid_path(grid, path, x, y, obj_Player.x, obj_Player.y, 1)
{
path_start(path, 0, 3, 0);
}
}

The above code creates a global variable "grid", then generates an mp_grid and assigns its index (id) to that variable for use in all further mp_grid function calls. It then adds all instances of "obj_Wall" into the grid before getting all instances of "obj_Enemy" to create a path and then use mp_grid_path to calculate a rout from their position to the position of "obj_Player". If a route exists then the object starts itself along the path.

Back: Motion Planning
Next: mp_grid_add_cell

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_grid_to_ds_grid

Copies the data from a motion planning grid to a pre-made DS grid.

Syntax:

mp_grid_to_ds_grid(source, destination);

Argument | Description
source | Index of the mp_grid that is to be used
destination | Index of the ds_grid that is to be used to copy the grid data to.

Returns: Boolean.

Description

With this function you can copy the given MP grid into a DS Grid. The DS grid should be the same size as the MP grid, although it doesn't have to be (data will be lost if it is smaller, and if it is larger all extra grid cells will be 0). The DS grid cells will contain the value -1 if the MP grid cell was flagged as occupied, or it will be 0 if not.

Example:

motion_grid = ds_grid_create(room_width / 32, room_height / 32); mp_grid_to_ds_grid(mp_grid, motion_grid);

The above code will create a new DS grid and then copy the MP grid data contained in the variable "mp_grid" into the new DS grid.

Back: Motion Planning
Next: mp_grid_draw

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_linear_path

This function computes a straight-line path for the instance.

Syntax:

mp_linear_path(path, xgoal, ygoal, stepsize, checkall);

Argument | Description
path | The index of the path to be used.
xgoal | The target x position.
ygoal | The target y position.
stepsize | The speed the instance moves in pixels per step.
checkall | Whether to check for collisions with all instances (true) or just solid ones (false).

Returns: Boolean.

Description

This function computes a straight line path from the current instance position to the point specified by the "xgoal" and "ygoal" values. It uses the indicated step size, the same as in the function mp_linear_step(). The indicated path must already exist and will be overwritten by the new path and the function will return if a complete path was found (true) or not (false). If false is returned then a path is still generated, but it will only run up to the position where the path was blocked.

Note: This function does not move the instance. It sets a path only, and you must use the Path functions for movement.

Example:

if mp_linear_path(path, obj_Player.x, obj_Player.y, 2, 0) path_start(path, 2, 0, 0);

This gets the object to check and see if there is a linear path from its current position to the position of "obj_Player". If there is then it starts the path.

Back: Motion Planning
Next: mp_linear_path_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_linear_path_object

This function computes a straight-line path for the instance, checking for collisions with a specific object

Syntax:

mp_linear_path_object(path, xgoal, ygoal, stepsize, obj);

Argument | Description
path | The index of the path to be used
xgoal | The target x position.
ygoal | The target y position.
stepsize | The speed the instance moves in pixels per step.
obj | The object that is to block the path. Can be an object index, an instance id or the special keyword ,all

Returns: Boolean

Description

This function computes a straight line path from the current instance position to the point specified by the "xgoal" and "ygoal" values. It uses the indicated step size, the same as in the function mp_linear_step(). The indicated path must already exist and will be overwritten by the new path and the function will return if a complete path was found (true) or not (false). A full path is only found there was no collision with the specified object or instance and if false is returned then a path is still generated, but it will only run up to the position where the path was blocked.

Note: This function does not move the instance. It sets a path only, and you must use the Path functions for movement.

Example:

if mp_linear_path_object(path, mouse_x, mouse_y, 4, obj_Wall) path_start(path, 4, 0, 0);

The above code checks for a collision with "obj_Wall" along the path between the object running the code and the x/y position of the mouse. If there is no collision and the complete path is generated then it will start the object along the path generated.

Back: Motion Planning
Next: mp_potential_settings

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_linear_step

This makes an instance try to get to a position while checking for all other instances.

Syntax:

mp_linear_step(xgoal, ygoal, stepsize, checkall);

Argument | Description
xgoal | The target x position.
ygoal | The target y position.
stepsize | The speed the instance moves in pixels per step.
checkall | Whether to check all instances (true) or just solid ones (false).

Returns: Boolean

Description

With this function you tell an instance to take a "step" towards a specific point, specified by the xgoal and ygoal values. The size of the step (which is how many pixels the instance should move each step) is indicated by the stepsize, and if the instance is already at the position it will stop and not move any further, contrary to other, simpler functions like move_towards_point. The stepsize is also the distance "ahead" that the object will check each step for a collision, and you can choose whether the instance stops at a collision with any instance or only those that are flagged as solid.

Note: This function does not try to make detours if it meets an obstacle, it simply fails and stops moving. The function will return whether it has reached the goal position (true) or if it has failed (false).

Example:

if mp_linear_step(mouse_x, mouse_y, 5, 0)
{
instance_create(x,y,obj_Explosion);
instance_destroy();
}

The above code will make the object move towards the mouse at a speed of 5 pixels per step. Once it reaches the mouse position it will create an object "obj_Explosion" and destroy itself.

Back: Motion Planning
Next: mp_linear_step_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_linear_step_object

This makes an instance try to get to a position while checking for all instances of the specified object.

Syntax:

mp_linear_step_object(xgoal, ygoal, stepsize, obj);

Argument | Description
xgoal | The target x position.
ygoal | The target y position.
stepsize | The speed the instance moves in pixels per step.
obj | The object that is to block the path. Can be an object index, an instance id or the special keyword, all

Returns: Boolean.

Description

With this function you tell an instance to take a "step" towards a specific point, specified by the xgoal and ygoal values. The size of the step (which is how many pixels the instance should move each step) is indicated by the stepsize, and if the instance is already at the position it will stop and not move any further, contrary to other, simpler functions like move_towards_point. The stepsize is also the distance "ahead" that the object will check each step for a collision, and you can choose whether the instance stops at a collision with an object or instance of your choice.

Example:

if mp_linear_step_object(mouse_x, mouse_y, 5, obj_Wall)
{
instance_create(x,y,obj_Explosion);
instance_destroy();
}

The above code will make the object move towards the mouse at a speed of 5 pixels per step, only checking for collisions with the object "obj_Wall". Once it reaches the mouse position it will create an object "obj_Explosion" and destroy itself.

Back: Motion Planning
Next: mp_linear_path

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_potential_path

Calculates a path between two points, avoiding instances along the way.

Syntax:

mp_potential_path(path, xgoal, ygoal, stepsize, factor, checkall)

Argument | Description
path | index of the path that is to be used by the function
xgoal | The target x position.
ygoal | The target y position.
stepsize | The speed the instance moves in pixels per step.
factor | This number is used to prevent an infinite loop. It should be larger than 1. See the function description for more information.
checkall | Whether to check all instances (true) or just solid ones (false).

Returns: Boolean.

Description

This function computes a path for the instance from its current position and orientation to the position specified by the xgoal,ygoal arguments. It uses the indicated step size while trying to avoid collision with either all instances or only those flagged as solid. Like in the function mp_potential_step it uses potential field steps to accomplish this and the manner in which it does this can be modified through the function mp_potential_settings. The indicated path must already exist and it will be overwritten by the new path. The function will return whether a path was found (true) or not (false).

To avoid the function continuing to compute forever you need to provide a factor of larger than 1 - the function will stop and report failure if it cannot find a path shorter than this factor times the distance between start and goal. A factor of 4 is normally good enough but if you expect long detours you might make it longer. If it fails a path is still created that runs in the approximate direction of the goal but it will not reach it.

Note: This function does not move the instance. It sets a path only, and you must use the Path functions for movement.

Example:

path = path_add();
mp_potential_path(path, obj_Player.x, obj_Player.y, 3, 4, 0);
path_start(path, 3, 0, 0);

The above code creates a new path resource and stores its index in the variable "path". It then generates a path using mp_potential_path between the object with this code and the object "obj_Player", checking for collisions with all instances in the room. Finally it starts the object along that path, even if the function has failed to return a complete route to the "obj_Player".

Back: Motion Planning
Next: mp_potential_path_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_potential_path_object

Calculates a path between two points, avoiding the specified object along the way.

Syntax:

mp_potential_path_object(path, xgoal, ygoal, stepsize, factor, obj)

Argument | Description
path | index of the path that is to be used by the function
xgoal | The target x position.
ygoal | The target y position.
stepsize | The speed the instance moves in pixels per step.
factor | This number is used to prevent an infinite loop. It should be larger than 1. See the function description for more information.
obj | The object that is to block the path. Can be an object index, an instance id or the special keyword ,all

Returns: Boolean.

Description

This function computes a path for the instance from its current position and orientation to the position specified by the xgoal, ygoal arguments. It uses the indicated step size while trying to avoid collision with instances of the object specified by the "obj" argument. Like in the function mp_potential_step it uses potential field steps to accomplish this and the manner in which it does this can be modified through the function mp_potential_settings. The indicated path must already exist and it will be overwritten by the new path. The function will return whether a path was found (true) or not (false).

To avoid the function continuing to compute forever you need to provide a factor of larger than 1 - the function will stop and report failure if it cannot find a path shorter than this factor times the distance between start and goal. A factor of 4 is normally good enough but if you expect long detours you might make it longer. If it fails a path is still created that runs in the approximate direction of the goal but it will not reach it.

Note: This function does not move the instance. It sets a path only, and you must use the Path functions for movement.

Example:

path = path_add();
mp_potential_path_object(path, obj_Player.x, obj_Player.y, 3, 4, obj_Wall);
path_start(path, 3, 0, 0);

The above code creates a new path resource and stores its index in the variable "path". It then generates a path using mp_potential_path between the object with this code and the object "obj_Player", checking for collisions with the object "obj_Wall". Finally it starts the object along that path, even if the function has failed to return a complete route to the "obj_Player".

Back: Motion Planning
Next: mp_grid_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_potential_settings

This function sets various parameters to change how the mp_potential functions work.

Syntax:

mp_potential_settings(maxrot, rotstep, ahead, onspot)

Argument | Description
maxrot | The number of degrees either side of the current direction that the instance can rotate in a step
rotstep | The number of degrees either side of the current direction that the instance can check for a collision
ahead | The number of steps ahead that the instance can check for a collision. Larger values are slower than lower ones.
onspot | Use this to allow the instance to rotate on the spot when no path is found (true) or not (false)

Returns: N/A.

Description

The mp_potential_ functions do their work using a number of parameters that can be changed using this function. Globally the method works as follows: it first tries to move straight towards the goal, looking a number of steps ahead which can be set with the parameter "ahead" (default value is 3). Reducing this value means that the instance will start changing direction later as it doesn't "see" as far ahead, and increasing it means it will start changing direction earlier. If this check leads to a collision then it starts looking at directions more to the left and to the right of the ideal, straight-line direction. It does this in steps of size "rotstep" (default value is 10), and reducing this gives the instance more movement possibilities but will be slower as it needs more processing power.

The parameter "maxrot" is a bit more difficult to explain! The instance has a current direction of movement, and maxrot (default value is 30) indicates how much it is allowed to vary its direction either side of that current direction in one step. So even if it can move e.g. straight to the goal it will only do so if it does not violate this maximal change of direction. If you make maxrot a large value then the instance can change direction a lot in each step, and this will make it easier to find a short path but the path will be uglier and less natural. If you make the value smaller then the path will be smoother but it might take longer detours (and sometimes even fail to find the goal). Finally, When no step can be made the behavior depends on the value of the parameter "onspot". If onspot is true (the default value), then the instance will rotate on its spot by the amount indicated with "maxrot" and if it is false it will not move at all. Setting it to false is useful for e.g. cars but reduces the chance of the instance finding a path.

Example:

mp_potential_settings(45, 5, 5, 0)

The above code will set the mp_potential_ functions to use the following settings: the instance can look ahead five steps, change direction 45 degrees each step, look 5 degrees either side of the current direction if there is an obstacle and not rotate on the spot of there is a collision.

Back: Motion Planning
Next: mp_potential_step

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_potential_step

This function moves an instance towards a point avoiding obstacles.

Syntax:

mp_potential_step(xgoal, ygoal, stepsize, checkall)

Argument | Description
xgoal | The target x position.
ygoal | The target y position.
stepsize | The speed the instance moves in pixels per step.
checkall | Whether to check all instances (true) or just solid ones (false).

Returns: Boolean.

Description

This function lets the instance take a step towards a particular position defined by xgoal/ygoal, all the while trying to avoid obstacles. When the instance would run into a solid instance (or any instance when checkall is true) it will change the direction of motion to try to avoid that instance and move around it. This approach is not guaranteed to work but in most easy cases it will effectively move the instance towards the goal. The function returns whether the goal was reached or not.

Example:

if instance_exists(obj_Enemy)
{
var inst;
inst = instance_nearest(x, y, obj_Enemy);
mp_potential_step(inst.x, inst.y, 5, false);
}

The above code first checks to see if there are any instances of "obj_Enemy" in the room. If there are it then finds the nearest one and stores its id in a variable. This variable is then used to tell mp_potential_step to move the instance with the code towards the x/y position of the object that was found at a speed of 5 pixels per step while avoiding only instances flagged as solid.

Back: Motion Planning
Next: mp_potential_step_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mp_potential_step_object

This function moves an instance towards a point avoiding the specified object.

Syntax:

mp_potential_step_object(xgoal, ygoal, stepsize, obj)

Argument | Description
xgoal | The target x position.
ygoal | The target y position.
stepsize | The speed the instance moves in pixels per step.
obj | The object that is to block the path of the instance running the function. Can be an object index, an instance id or the special keyword ,all.

Returns: Boolean.

Description

This function lets the instance take a step towards a particular position defined by xgoal/ygoal, all the while trying to avoid obstacles. When the instance would run into an instance of the object specified by the "obj" argument it will change the direction of motion to try to avoid that instance and move around it. This approach is not guaranteed to work but in most easy cases it will effectively move the instance towards the goal. The function returns whether the goal was reached or not.

Example:

if instance_exists(obj_Enemy)
{
var inst;
inst = instance_nearest(x, y, obj_Enemy);
mp_potential_step_object(inst.x, inst.y, 5, obj_Wall);
}

The above code first checks to see if there are any instances of "obj_Enemy" in the room. If there are it then finds the nearest one and stores its id in a variable. This variable is then used to tell mp_potential_step_object to move the instance with the code towards the x/y position of the object that was found at a speed of 5 pixels per step while avoiding only instances of the object "obj_Wall".

Back: Motion Planning
Next: mp_potential_path

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Movement

These functions all deal with movement and direction.

In any game, movement and position are of paramount importance and so GameMaker: Studio has a complete selection of functions to deal with every situation.

Built In Variables and Functions

The following functions are all included "built in" to every instance and can be read and modified to change different behaviours when the instance is moving:

  1. direction
  2. friction
  3. gravity
  4. gravity_direction
  5. hspeed
  6. vspeed
  7. speed

X and Y

The following sections detail the different positional variables that are built into each instance:

  1. x
  2. y
  3. xprevious
  4. yprevious
  5. xstart
  6. ystart

Movement Functions

The following functions deal with movement and interaction with other instances through movement:

  1. distance_to_object
  2. distance_to_point
  3. motion_add
  4. motion_set
  5. move_towards_point
  6. move_bounce_all
  7. move_bounce_solid
  8. move_contact_all
  9. move_contact_solid
  10. move_outside_all
  11. move_outside_solid
  12. move_random
  13. move_snap
  14. place_snapped
  15. move_wrap

Back: Movement and Collisions
Next: Motion Planning

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


direction

The direction of the object's motion, in degrees.

Syntax:

direction;

Returns: Real

Description

All instances in GameMaker: Studio have certain "built in" properties that you can use and set to govern how they look and behave. Direction is one of those properties and can be used to set the direction of movement of the instance when the instance has a speed other than 0. Note that directions in GameMaker: Studio are usually calculated as 0° being right, 90° being up, 180° being left and 270° being down.

Example:

if keyboard_check(vk_left) direction += 5;
if keyboard_check(vk_right) direction -= 5;

The above code will change the direction of movement of the instance based on which key (left or right) is pressed.

Back: Moving Around
Next: friction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


distance_to_object

Returns the distance between the calling instance and the nearest instance of a given object.

Syntax:

distance_to_object( obj );

Argument | Description
obj | The object to check for.

Returns: Real.

Description

This function calculates the distance from the edge of the bounding box of the calling instance to the nearest edge of the nearest instance of the object specified. The object can be an object index or a specific instance id as well as the keyword other, and the distance is returned in pixels. Note that if either of the objects have no sprite or no mask defined, the results will be incorrect.

Example:

if distance_to_object(obj_Player) < range
{
canshoot = true;
}

The above code will check for the distance to the player object and if it is less than the value stored in the variable "range" the variable "canshoot" is set to true.

Back: Moving Around
Next: distance_to_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


distance_to_point

Returns the distance between the calling instance and a given point, in pixels.

Syntax:

distance_to_point(x, y);

Argument | Description
x | The x position to check.
y | The y position to check.

Returns: Real

Description

This function calculates the distance from the edge of the bounding box of the calling instance to the specified x/y position in the room, with the return value being in pixels. Note that if the calling object have no sprite or no mask defined, the results will be incorrect.

Example:

if distance_to_point(obj_Player.x, obj_Player.y) < range
{
canshoot = true;
}

The above code will check for the distance to the player object x/y position and if it is less than the value stored in the variable "range" the variable "canshoot" is set to true.

Back: Moving Around
Next: motion_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


friction

The friction to apply to the object.

Syntax:

friction

Returns: Real

Description

All instances in GameMaker: Studio have certain "built in" properties that you can use and set to govern how they look and behave. Friction is one of those properties and can be used to slow the instance down over time when the speed is greater than zero. It works simply by subtracting an amount from the speed every step until the object has a speed of 0, so if the friction is set to, for example, 0.1 and the speed of the instance is 1 (1 pixel per step), it will slow down and stop after 10 steps have passed. Note too that the friction is applied to positive and negative speeds equally with the net result always being that the object has a speed of 0 after a given time.

Example:

if abs(speed) > 0
{
friction=0.05;
}
else
{
friction=0;
}

The above code will only apply friction if the instance's absolute speed is above 0.

Back: Moving Around
Next: gravity

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gravity

The gravity to apply to the object.

Syntax:

gravity

Returns: Real

Description

All instances in GameMaker: Studio have certain "built in" properties that you can use and set to govern how they look and behave. Gravity is one of those properties and, when set, will apply a constant force in the gravity direction of the instance, influencing its speed. Note that gravity is a cumulative force and will accelerate the object if you choose not to cap the final speed.

Example:

if !place_meeting(x, y + 1, obj_Ground)
{
gravity = 0.01;
}
else
{
gravity = 0;
}

The above code will only apply gravity if the instance does not find any instances of "obj_Ground" beneath it.

Back: Moving Around
Next: gravity_direction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


gravity_direction

The direction of gravity for the instance.

Syntax:

gravity_direction;

Returns: Real

Description

All instances in GameMaker: Studio have certain "built in" properties that you can use and set to govern how they look and behave. Gravity_direction is one of those properties and can be used to set the direction of movement when the instances gravity is greater than 0. Note that directions in GameMaker: Studio are usually calculated as 0° being right, 90° being up, 180° being left and 270° being down.

Example:

if place_meeting(x, y, obj_switch)
{
gravity_direction += 180;
}

The above code will change the gravity_direction if the player object meets an instance of "obj_switch".

Back: Moving Around
Next: hspeed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


hspeed

The horizontal speed of the object.

Syntax:

hspeed

Returns: Real

Description

All instances in GameMaker: Studio have certain "built in" properties that you can use and set to govern how they look and behave. hspeed is one of those properties and defines the horizontal movement speed of the instance in pixels per step. So, an hspeed of 3 means 3 pixels of movement to the right (+x) every step, and an hspeed of -3 would mean 3 pixels of movement to the left (-x) every step.

Example:

if keyboard_check(vk_left) hspeed = -5;
if keyboard_check(vk_right) hspeed = 5;

The above code will change the horizontal speed depending on which keys are pressed.

Back: Moving Around
Next: vspeed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


motion_add

Adds to the motion of the calling object the given direction and speed

Syntax:

motion_add(dir, speed);

Argument | Description
dir | The added direction.
speed | The added speed.

Returns: N/A

Description

This function add to the direction and a movement speed of an instance, and can be very useful for collisions and simple physics.

Example:

var pdir;
pdir = point_direction(other.x, other.y, x, y);
motion_add(pdir, other.speed);
if speed > 8 speed = 8;

the above code would be called in the collision event with another object. It adds to the direction of motion and the speed of the instance a vector based on the position and speed of the other instance involved in the collision. It then limits the speed if it goes over 8 (pixels per step).

Back: Moving Around
Next: motion_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


motion_set

Sets the motion of the calling object to the given direction and speed.

Syntax:

motion_set(dir, speed);

Argument | Description
dir | The new direction.
speed | The new speed.`

Returns: N/A

Description

This function sets a new direction of movement and a new speed to the instance running the code. Note that this does not add to the instances current speed and direction (for that you would use motion_add) but rather forces it to the new settings.

Example:

if irandom(9) = 1 motion_set(random(360), 1 + random(3));

This above code will make the instance change speed and direction at random intervals.

Back: Moving Around
Next: move_towards_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_bounce_all

Allows bouncing of the calling instance against all objects.

Syntax:

move_bounce_all( adv );

Argument | Description
adv | Whether to enable advanced bouncing (true) or not (false).

Returns: N/A

Description

With this function you can command an instance to bounce off all instances within the room, with the only exception being those that have no sprite or mask index assigned to them. You can also tell it to use precise collision checking when enabled, but be aware that this requires all instances to have precise masks enabled and will greatly slow down your game when many instances are involved due to the amount of processing that has to be done. This should normally go in the step event of an instance, but can be used selectively in a collision event too, as illustrated by the code example below.

Example:

if other.visible
{
move_bounce_all(false);
}

The above code would be placed in a collision event with another object. It first checks to see if the object is visible and if it is it then performs the move_bounce_all() action. Note that in this case the bounce is selective and will only be calculated for this collision, rather than for every instance, every step.

Back: Moving Around
Next: move_bounce_solid

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_bounce_solid

Allows bouncing of the calling instance against solid objects, such as walls.

Syntax:

move_bounce_solid(adv);

Argument | Description
adv | Whether to enable advanced bouncing (true) or not (false).

Returns: N/A

Description

With this function you can command an instance to bounce off only those instances marked as solid within the room. You can also tell it to use precise collision checking when enabled, but be aware that this requires all instances to have precise masks enabled and will greatly slow down your game when many instances are involved due to the amount of processing that has to be done. This should normally go in the step event of an instance, but can be used selectively in a collision event too.

Example:

move_bounce_solid(false);

This will enable non-precise bouncing off instances flagged as "solid".

Back: Moving Around
Next: move_contact_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_contact_all

Moves the instance in a given direction until it comes into contact with an object.

Syntax:

move_contact_all(dir, maxdist);

Argument | Description
dir | The direction to move in.
maxdist | The maximum distance the object can travel (-1 or 0 a default value of 1000 pixels).

Returns: N/A

Description

This function will move the instance running the code a set number of pixels in the specified direction until it meets any other instance with a valid mask. You can use -1 or 0 for the maxdist being a default 1000px, ie: GameMaker: Studio will move the instance continually up 1000 pixels until it is out of collision.

Example:

if !place_meeting(x, y + 1, all)
{
move_contact_all(270, -1);
}

The above code will check beneath the instance for a collision, and if there is none, then it will move it down until there is or until 1000pixels have been covered.

Back: Moving Around
Next: move_contact_solid

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_contact_solid

Moves the instance in a given direction until it comes into contact with a solid object.

Syntax:

move_contact_solid( dir, maxdist );

Argument | Description
dir | The direction to move in.
maxdist | The maximum distance the object can travel (-1 or 0 a default value of 1000 pixels).

Returns: N/A

Description

This function will move the instance running the code a set number of pixels in the specified direction until it meets an instance with solid flagged as true. You can use -1 or 0 for the maxdist being a default 1000px, ie: GameMaker: Studio will move the instance continually up 1000 pixels until it is out of collision.

Example:

if !place_meeting(x, y + 1, obj_Floor)
{
move_contact_solid(270, -1);
}

The above code will check beneath the instance for a collision with "obj_Floor", and if there is none, then it will move it down until there is a collision, or 1000 pixels have been covered.

Back: Moving Around
Next: move_outside_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_outside_all

Moves the instance in a given direction until it no longer comes into contact with any other instance.

Syntax:

move_outside_all(dir, maxdist);

Argument | Description
dir | The direction to move in.
maxdist | The maximum distance the object can travel (-1 or 0 a default value of 1000 pixels).

Returns: N/A

Description

With this function you can tell an instance to move out of a collision in any direction and any number of pixels each step, with a value of -1 or 0 for the maxdist being a default 1000px, ie: GameMaker: Studio will move the instance continually up 1000 pixels until it is out of collision.

Example:

if place_meeting(x, y, all)
{
move_outside_all(90, 1);
}

The above code will move the instance up 1 pixel each step that it is in collision with any other instance.

Back: Moving Around
Next: move_outside_solid

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_outside_solid

Moves the instance in a given direction until it NO LONGER comes into contact with a solid object.

Syntax:

move_outside_solid(dir, maxdist);

Argument | Description
dir | The direction to move in.
maxdist | The maximum distance the object can travel (-1 or 0 a default value of 1000 pixels).

Returns: N/A

Description

With this function you can tell an instance to move out of a collision with any instance flagged as solid in any direction and any number of pixels each step, with a value of -1 or 0 for the maxdist being a default 1000px, ie: GameMaker: Studio will move the instance continually up 1000 pixels until it is out of collision.

Example:

if other.solid
{
var pdir;
pdir = point_direction(other.x, other.y, x, y);
move_outside_solid(pdir, -1);
}

The above code would go in a collision event and checks to see if the "other" instance in the collision is flagged as "solid". If it is, it will then move the instance out of collision.

Back: Moving Around
Next: move_random

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_random

Moves the calling instance to a random position on a given grid.

Syntax:

move_random(hsnap, vsnap);

Argument | Description
hsnap | The horizontal snapping (the size in pixels between 'cells').
vsnap | The vertical snapping (the size in pixels between 'cells').

Returns: N/A

Description

With this function you can set the instance to a position anywhere in the room, but aligned to an "invisible" grid. So a value of 32 for the hsnap and vsnap will set the instance to a random position that is aligned to a grid of 32x32 squares. you can set these values to 1 to get a position anywhere in the room.

NOTE: This function will snap to the same positions every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game. This is only true when testing and debugging the game, as the final executable package will not show this behaviour and will be random every play.

Example:

if keyboard_check(vk_space) move_random(1,1);

This will move the instance to a random position anywhere in the room when the space key is pressed.

Back: Moving Around
Next: move_snap

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_snap

Snaps the player to the nearest position on a grid with cells of a given size.

Syntax:

move_snap( hsnap, vsnap );

Argument | Description
hsnap | The horizontal snapping (the size in pixels between 'cells').
vsnap | The vertical snapping (the size in pixels between 'cells').

Returns: N/A

Description

This function is used to "snap" the instance to a grid of a given size. It will be snapped to the nearest corresponding position on the "invisible" grid that the hsnap and vsnap values define.

Example:

with (obj_Pieces)
{
if !place_snapped(32, 32)
{
move_snap(32, 32);
}
}

The above code checks all instances of "obj_Pieces" to see if they are snapped to a grid of 32x32 pixels, and if they are not it snaps them to the nearest position in that grid.

Back: Moving Around
Next: place_snapped

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_towards_point

Moves the instance towards a given point at a given speed.

Syntax:

move_towards_point( x, y, sp );

Argument | Description
x | The x position of the point to move towards.
y | The y position of the point to move towards.
sp | The speed to move at in pixels per second.

Returns: N/A

Description

This function simply tells the instance running the code to move towards a set point at a set speed. Bear in mind that it is up to you to tell it what to do once it gets there, as it won't just stop by itself. This means that you can get a "vibrating" instance as it moves (for example) 3 pixels forward, overshoots the x/y target position by 2, then moves 3 pixels back again, overshooting the target point by one and so on... There are a number of ways that this can be avoided, for example using distance_to_point to see how far from the specified location the instance is before moving.

Note: this function sets the speed of the instance, so even if you stop using this code, the instance will keep moving in the previous direction, so it is necessary to set the instance speed to 0 if you wish it to stop. See the code example below.

Example:

if point_distance(x, y, target.x, target.y) > 5
{
move_towards_point(target.x, target.y, 5);
}
else speed = 0;

The above code will move the instance towards the position of the instance indexed in the variable "target" at a speed of 5 pixels per step. Once it reaches that position the speed is set to 0.

Back: Moving Around
Next: move_bounce_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


move_wrap

Wraps the player around the room if relevant.

Syntax:

move_wrap(hor, vert, margin);

Argument | Description
hor | Whether to wrap horizontally (true) or not (false).
vert | Whether to wrap vertically (true) or not (false).
margin | How far outside the room, in pixels, the object must be to initiate wrapping.

Returns: N/A

Description

This function will automatically "wrap" an instance that has left the room on either the horizontal or vertical (or both) axis. You can specify a margin outside the edges of the room for this to occur, and when the instance has travelled outside of that margin GameMaker: Studio will automatically wrap it back into the room at the other side. Note that the instance must have a speed for wrapping to work, because the direction of wrapping is based on the direction of the motion.

Example:

move_wrap(true, false, sprite_width);

This will make the instance wrap horizontally but not vertically, when it is over its own sprite width outside of the room.

Back: Moving Around
Next: direction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


place_snapped

Returns whether the calling instance is aligned with the snapping values.

Syntax:

place_snapped(hsnap, vsnap);

Argument | Description
hsnap | The horizontal snapping to check.
vsnap | The vertical snapping to check.

Returns: Boolean

Description

With this function you can check and see if the origin of an instance (its x and y position) is aligned to a grid with the hsnap and vsnap values specified by you.

Example:

with (obj_Pieces)
{
if !place_snapped(32, 32)
{
move_snap(32, 32);
}
}

The above code checks all instances of "obj_Pieces" to see if they are snapped to a grid of 32x32 pixels, and if they are not it snaps them to the nearest position in that grid.

Back: Moving Around
Next: move_wrap

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


speed

The speed of the object.

Syntax:

speed

Returns: Real

Description

All instances in GameMaker: Studio have certain "built in" properties that you can use and set to govern how they look and behave. speed is one of those properties and defines how many pixels the instance will move every step. Unlike hspeed and vspeed, speed has no direction associated it with it as this is governed by the direction value of the instance, but it can have a negative value, in which case the instance will travel in the opposite direction to that set by the direction function (ie: direction - 180°).

Example:

if keyboard_check(vk_up) speed = 2;
if keyboard_check(vk_left) direction += 5;
if keyboard_check(vk_right) direction -= 5;

The above code will use the arrow keys to set the speed and direction of the instance.

Back: Moving Around
Next: x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vspeed

The vertical speed of the object.

Syntax:

vspeed

Returns: Real

Description

All instances in GameMaker: Studio have certain "built in" properties that you can use and set to govern how they look and behave. vspeed is one of those properties and defines the vertical movement speed of the instance in pixels per step. So, a vspeed of 3 means 3 pixels of movement down the screen (+y) every step, and a vspeed of -3 would mean 3 pixels of movement up the screen (-y) every step.

Example:

if keyboard_check(vk_up) vspeed = -5;
if keyboard_check(vk_down) vspeed = 5;

The above code will change the vertical speed depending on which keys are pressed.

Back: Moving Around
Next: speed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


x

The x position of the instance.

Syntax:

x

Returns: Real

Description

The x value of an instance is the horizontal position in the current room, measured in pixels. This value can be either 0, positive or minus, where 0 is the left hand side of the room and moving right increases x, moving left decreases x (a negative value for x means that the instance has gone outside the left side of the room). You can even give x a real value like 12.345, but as you cannot get .345 of a pixel, the instance may not appear to have moved, although these values will be maintained and used internally by GameMaker: Studio and are perfectly valid.

By setting the x (and y) values you can make the object jump around the room to the position of your choice, or you can add and subtract to them by smaller amounts to give the illusion of movement without actually using the built in speed and direction functions. This should be taken into account when making your games as often one type of movement lends itself to a particular style of game-play more than another.

Example:

if keyboard_check(vk_left) x += 5;
if keyboard_check(vk_right) x -= 5;

The above code will use the arrow keys to add or subtract to the x position and so create the illusion of movement.

Back: Moving Around
Next: y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


xprevious

The previous x position of the instance.

Syntax:

xprevious

Returns: Real

Description

This built-in variable returns the previous x position for the instance. This variable will be set just before the start of the begin step event but it can also be set through code at any time, meaning you can give it your own custom value should that be necessary.

Example:

if x != xprevious || y != yprevious
{
moved = true;
}

The above code checks to see if there is any difference between the xprevious and yprevious values and the current x and y values. If there is it sets a variable to true.

Back: Moving Around
Next: yprevious

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


xstart

The starting x position of the instance.

Syntax:

xstart

Returns: Real

Description

This function stores the initial position of the instance when it is first created. You can also set this in code to the value that you wish.

Example:

if place_meeting(x, y, obj_spike)
{
score -= 100;
x = xstart;
y = ystart;
}

The above code will check for a collision with an instance of "obj_spike" and if there is one, it deducts 100 from the score and moves the instance back to its starting position.

Back: Moving Around
Next: ystart

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


y

The y position of the instance.

Syntax:

y

Returns: Real

Description

The y value of an instance is the vertical position in the current room, measured in pixels. This value can be either 0, positive or minus, where 0 is the top of the room and moving down increases y, moving up decreases y (a negative value for y means that the instance has gone outside the top of the room). You can even give y a real value like 12.345, but as you cannot get .345 of a pixel, the instance may not appear to have moved, although these values will be maintained and used internally by GameMaker: Studio and are perfectly valid.

By setting the y (and x) values you can make the object jump around the room to the position of your choice, or you can add and subtract to them by smaller amounts to give the illusion of movement without actually using the built in speed and direction functions. This should be taken into account when making your games as often one type of movement lends itself to a particular style of game-play more than another.

Example:

if keyboard_check(vk_down) y += 5;
if keyboard_check(vk_up) y -= 5;

The above code will use the arrow keys to add or subtract to the y position and so create the illusion of movement.

Back: Moving Around
Next: xprevious

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


yprevious

The previous y position of the instance.

Syntax:

yprevious

Returns: Real

Description

This built-in variable returns the previous y position for the instance. This variable will be set just before the start of the begin step event but it can also be set through code at any time, meaning you can give it your own custom value should that be necessary.

Example:

if x != xprevious || y != yprevious
{
moved = true;
}

The above code checks to see if there is any difference between the xprevious and yprevious values and the current x and y values. If there is it sets a variable to true.

Back: Moving Around
Next: xstart

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ystart

The starting y position of the instance.

Syntax:

ystart

Returns: Real

Description

This function stores the initial position of the instance when it is first created. You can also set this in code to the value that you wish.

Example:

if place_meeting(x, y, obj_spike)
{
score -= 100;
x = xstart;
y = ystart;
}

The above code will check for a collision with an instance of "obj_spike" and if there is one, it deducts 100 from the score and moves the instance back to its starting position.

Back: Moving Around
Next: distance_to_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Networking

These functions are provided to give you basic client/server networking in your games.

The GameMaker: Studio networking functions are based on sockets, which is an industry standard on all platforms. With sockets, you have the ability to create both clients and servers using simple GML which allows you to create even a single player game using the client/server model (something which will allow multiplayer to be added easily later).

Basically, a socket is an object which can send, receive, connect and listen to ports on the network. These functions deal with just TCP/IP connections, which is what the internet is based on (IPv4 to be more precise). In essence this lets you connect one socket using an IP address (let’s say 192.168.1.10) to another socket on another IP address (say 192.168.1.11). Once connected, these two sockets can send data back and forth using the network_send_* functions (like network_send_packet) and the dedicated asynchronous event that is triggered by them. This async event will generate a ds_map containing the data received as well as other details, and you can find the complete details in the section on the Network Async Event.

Instead of programs having to read and deal with every bit of network traffic coming into a machine, IP addresses also deal with ports, which are numbered from 0 to 65535. This allows each program to get only the packets of data that it’s interested in, and not everything that has been sent by every program. This also saves considerable CPU time, as it seriously cuts down on data processing, so with GameMaker: Studio you can also “listen” to ports. So, a server will create a socket, and then bind it to a specific port to listen to. It will then get notified of connections, disconnections and data transfers from that socket.

The data "packets" themselves are made up of binary data taken from a buffer. This buffer can be created and manipulated using the GameMaker: Studio Buffer functions.

NOTE: These functions are not currently available for the HTML5 target module.

The following functions exist for you to use for networking:

  1. network_create_server
  2. network_create_server_raw
  3. network_create_socket
  4. network_create_socket_ext
  5. network_connect
  6. network_connect_raw
  7. network_resolve
  8. network_set_config
  9. network_set_timeout
  10. network_send_broadcast
  11. network_send_packet
  12. network_send_raw
  13. network_send_udp
  14. network_send_udp_raw
  15. network_destroy

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_connect

Connect to a GameMaker: Studio server.

Syntax:

network_connect(socket, url, port);

Argument | Description
socket | The id of the socket to use.
url | The URL or IP to connect to (a string).
port | The port to connect to.

Returns: Real

Description

With this function you can send a request to connect to a server. The function takes the socket id to connect through (see network_create_socket) and requires you to give the IP address to connect to (a string) as well as the port to connect through, and if the connection fails a value of less than 0 will be returned. The connection uses a special protocol that ensures only GameMaker: Studio games connect to each other, however if you need to connect to a server that is not a GameMaker: Studio game, you can use network_connect_raw.

Example:

client = network_create_socket(network_socket_tcp);
network_connect(client, "192.134.0.1", 6510);

The above code will create a new TCP socket then attempt to connect through that to the given IP address on port 6510.

Back: Networking
Next: network_connect_raw

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_connect_raw

Connect to a server.

Syntax:

network_connect_raw(socket, url, port);

Argument | Description
socket | The id of the socket to use.
url | The URL or IP to connect to (a string).
port | The port to connect to.

Returns: Real

Description

With this function you can send a request to connect to a server. The function takes the socket id to connect through (see network_create_socket) and requires you to give the IP address to connect to (a string) as well as the port to connect through, and if the connection fails a value of less than 0 will be returned. The difference between this function and network_connect is that this function can connect to any server and does nothing to the raw data, meaning that you have to implement the protocols yourself at the server end.

Example:

client = network_create_socket(network_socket_tcp);
network_connect_raw(client, "www.macsweeneygames.com", 6510);

The above code will create a new TCP socket then attempt to create a "raw" connection through that to the given URL on port 6510.

Back: Networking
Next: network_resolve

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_create_server

Create a new network server.

Syntax:

network_create_server(type, port, max_client);

Argument | Description
type | The type of server to create (see the constants listed below).
port | The port that the server will use.
max_client | The maximum number of clients that can connect at once.

Returns: Real

Description

This function is used to create a new network server for your game, using one of the permitted connection protocols (see the constants listed below). You supply the server type, then give it a port to use, and finally the number of maximum connections that should be permitted at any one time to the server (note that this number is up to you, but too many connected clients will saturate the network or the device CPU won’t be able to handle the processing of that number of players, so use with care). The function returns a unique id which should be used stored in a variable and used to identify the server in all further network functions, or a value of less than 0 if the connection fails.

Constant | Description
network_socket_tcp | Create a web socket using TCP.
network_socket_udp | Create a web socket using UDP.
network_socket_bluetooth | Create a Bluetooth socket (currently unavailable!).

Example:

var port = 6510;
server = network_create_server(network_socket_tcp, port, 32);
while (server < 0 && port < 65535)
{
port++
server = network_create_server(network_socket_tcp, port, 32);
}

The above code will try and create a server using TCP through port 32. If that port is unavailable, it will then loop through the ports to find one that is.

Back: Networking
Next: network_create_server_raw

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_create_server_raw

Create a new network server with no client handshake for raw data.

Syntax:

network_create_server_raw(type, port, max_client);

Argument | Description
type | The type of server to create (see the constants listed below).
port | The port that the server will use.
max_client | The maximum number of clients that can connect at once.

Returns: Real

Description

This function is used to create a new network server for your game, using one of the permitted connection protocols (see the constants listed below). You supply the server type, then give it a port to use, and finally the number of maximum connections that should be permitted at any one time to the server (note that this number is up to you, but too many connected clients will saturate the network or the device CPU won’t be able to handle the processing of that number of players, so use with care). The function returns a unique id which should be used stored in a variable and used to identify the server in all further network functions, or a value of less than 0 if the connection fails.

Constant | Description
network_socket_tcp | Create a web socket using TCP.
network_socket_udp | Create a web socket using UDP.
network_socket_bluetooth | Create a Bluetooth socket (currently unavailable!).

As this creates a "raw" server, it will not accept nor use any of the built in GameMaker data headers for communitation, and so you should be using the functions network_send_raw and network_send_udp_raw() to send unformatted data to the server created.

Example:

var port = 6510;
server = network_create_server_raw(network_socket_tcp, port, 32);
while (server < 0 && port < 65535)
{
port++
server = network_create_server(network_socket_tcp, port, 32);
}

The above code will try and create a server using TCP through port 32. If that port is unavailable, it will then loop through the ports to find one that is.

Back: Networking
Next: network_create_socket

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_create_socket

Create a new client socket.

Syntax:

network_create_socket(type);

Argument | Description
type | The type of socket connection to create (see the constants listed below).

Returns: Real

Description

This function is used to create a new client socket for your game to communicate over the network. You must define the socket type (see the list of constants below) and the function will return a unique id for that socket, which should be used in all further function calls for that socket, or a value of less than 0 if the connection fails.

NOTE: You can use the IP "127.0.0.1" to connect back to the same device that is running the game.

Constant | Description
network_socket_tcp | Create a web socket using TCP.
network_socket_udp | Create a web socket using UDP.

Example:

client = network_create_socket(network_socket_tcp);
network_connect( client, “192.134.0.1”, 6510 );

The above code will create a new TCP socket then attempt to connect through that to the given IP address on port 6510.

Back: Networking
Next: network_create_socket_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_create_socket_ext

Create a new client socket, with a specific port number.

Syntax:

network_create_socket_ext(protocol, port);

Argument | Description
protocol | The network protocol to use
port | The port to use

Returns: Real

Description

This function is used to create a new client socket for your game to communicate over the network. You must define the socket protocol (see the list of constants below) and give a port to use, and the function will return a unique id which should be used in all further function calls for that socket, or a value of less than 0 if the connection fails.

Constant | Description
network_socket_tcp | Create a web socket using TCP.
network_socket_udp | Create a web socket using UDP.

Example:

client = network_create_socket_ext(network_socket_udp, 6510);

The above code will create a new UDP socket on port 6510.

Back: Networking
Next: network_connect

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_destroy

Remove a socket (client or server).

Syntax:

network_destroy(socket);

Argument | Description
socket | The id of the socket to remove.

Returns: N/A

Description

With this function you can remove a network socket connection from your game.

Example:

if !os_is_network_connected()
{
network_destroy(sock);
}

The above code will check to see if there is a data connection and if none is found, destroy the socket with the id "sock".

Back: Networking
Next: network_create_server

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_resolve

Resolves the IP of a given URL.

Syntax:

network_resolve(url);

Argument | Description
url | The URL to get the IP of (a string).

Returns: String

Description

This function will return the IP address of the given URL.

Example:

game_ip = network_resolve("www.macsweeneygames.com");

The above code will return the IP address of the given URL and store it in the variable "game_ip".

Back: Networking
Next: network_set_config

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_send_broadcast

Broadcast data to a range of IPs.

Syntax:

network_send_broadcast(socket, port, buffer, size);

Argument | Description
socket | The id of the socket to use.
port | The port that the server will use.
buffer | The id of the buffer to get the data from.
size | The size (in bytes) of the data.

Returns: Real

Description

With this function you can broadcast the data from a buffer locally to a range of IP addresses (for more information on buffers see Reference - Buffers). The range is limited to that of the device running the server, such that if the device has an IP of 92.168.11.130, then the data will be broadcast over the range 92.168.11.*. The function will return the number of bytes of data sent, or a number less than 0 if the send has failed.

NOTE: This function will only work when used with UDP - your server needs to be TCP and your client needs to have a UDP client socket created with network_create_socket_ext() in order to receive any broadcasts sent from the server.

Example:

buffer_seek(broadcast_buffer, buffer_seek_start, 0);
buffer_write(broadcast_buffer, buffer_string, global.ServerName);
network_send_broadcast(server, 6511, broadcast_buffer, buffer_tell(broadcast_buffer));

The above code writes the name string of the current server (stored in "global.ServerName"), then writes it to a binary buffer with the id "broadcast_buffer". This data is then broadcast locally to a range of IPs (the device IP is currently implied as the broadcast base range) to port 6511.

Back: Networking
Next: network_send_packet

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_send_packet

Send a GameMaker: Studio formatted packet of data over the network.

Syntax:

network_send_packet(socket, buffer, size);

Argument | Description
socket | The id of the socket to use.
buffer | The id of the buffer to get the data from.
size | The size (in bytes) of the data.

Returns: Real

Description

With this function you can send a data "packet" through the network. The function takes the socket id to connect through and then you must supply the buffer id which contains the data to be sent (for more information on buffers see Reference - Buffers) and finally the size (in bytes) of the data packet. Packets sent with this function are formatted such that the GameMaker: Studio game receiving the data can correctly "split" the packets correctly, and the function will return the number of bytes of data sent, or a number less than 0 if the send has failed. It is worth noting that the final size of the data being sent that is returned by this function will also include the GameMaker header information, which is an additional 12 bytes.

Example:

buff = buffer_load("player_save.dat");
network_send_packet(sock, buff, buffer_get_size(buff));

The above information loads a previously saved buffer data into memory and returns the buffer id to be stored in the variable "buff". This complete buffer is then send as a packet over the network using the socket identified by the variable "sock".

Back: Networking
Next: network_send_raw

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_send_raw

Send a packet of raw buffer data.

Syntax:

network_send_raw(socket, buffer, size);

Argument | Description
socket | The id of the socket to use.
buffer | The id of the buffer to get the data from.
size | The size (in bytes) of the data.

Returns: Real

Description

With this function you can send a "raw" data packet through the network. The function takes the socket id to connect through and then you must supply the buffer id which contains the data to be sent (for more information on buffers see Reference - Buffers) and finally the size (in bytes) of the data packet. The data sent is not formatted by GameMaker: Studio in any way and the receiving devices will get the data as a stream which means you will have to handle it yourself. The function will return the number of bytes of data sent, or a number less than 0 if the send has failed.

Example:

buff = buffer_load("player_save.dat");
network_send_raw(sock, buff, buffer_get_size(buff));

The above information loads a previously saved buffer data into memory and returns the buffer id to be stored in the variable "buff". This complete buffer is then send as a raw data packet over the network using the socket identified by the variable "sock".

Back: Networking
Next: network_send_udp

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_send_udp

Send data over the network using UDP.

Syntax:

network_send_udp(socket, url, port, buffer, size);

Argument | Description
socket | The id of the socket to use.
url | The url or IP to connect to (a string).
port | The port to connect to.
buffer | The id of the buffer to get the data from.
size | The size (in bytes) of the data.

Returns: Real

Description

With this function you can send data over the network using UDP to a server. The function takes the socket id to connect through, the URL to connect to and the port to use. You must then supply the buffer id which contains the data to be sent (for more information on buffers see Reference - Buffers) and finally the size (in bytes) of the data. UDP is "connectionless" in that you don't actually do a connect, you just send a packet directly to an IP, and the server gets incoming data from an IP address and has to deal with it "as is". The function will return the number of bytes of data sent, or a number less than 0 if the send has failed. It is worth noting that the final size of the data being sent that is returned by this function will also include the GameMaker header information, which is an additional 12 bytes.

Example:

network_send_udp(sock, "www.macsweeneygames.com", 6510, buff, buffer_tell(buff));

The above code will send a UDP packet to the server defined by the URL on the port 6510. The data is taken from the buffer indexed in the variable "buff".

Back: Networking
Next: network_send_udp_raw

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_send_udp_raw

Send raw buffer data over the network using UDP.

Syntax:

network_send_udp_raw(socket, url, port, buffer, size);

Argument | Description
socket | The id of the socket to use.
url | The url or IP to connect to (a string).
port | The port to connect to.
buffer | The id of the buffer to get the data from.
size | The size (in bytes) of the data.

Returns: Real

Description

With this function you can send data over the network using UDP to a server. The function takes the socket id to connect through, the URL to connect to and the port to use. You must then supply the buffer id which contains the data to be sent (for more information on buffers see Reference - Buffers) and finally the size (in bytes) of the data. UDP is "connectionless" in that you don't actually do a connect, you just send a packet directly to an IP, and the server gets incoming data from an IP address and has to deal with it "as is". The data sent is not formatted by GameMaker: Studio in any way and the receiving devices will get the data as a stream which means you will have to handle it yourself. The function will return the number of bytes of data sent, or a number less than 0 if the send has failed.

Example:

network_send_udp_raw(sock, "www.macsweeneygames.com", 6510, buff, buffer_tell(buff));

The above code will send a raw UDP packet to the server defined by the URL on the port 6510. The data is taken from the buffer indexed in the variable "buff".

Back: Networking
Next: network_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_set_config

Set different configuration options for the network.

Syntax:

network_set_config(config_value, setting);

Argument | Description
config_value | The config value constant to set (listed below).
setting | The setting of the config value.

Returns: String

Description

With this function you can set different network configurations. These configurations are given as constants and the setting will depend on the constant that you have choosen. The table below lists the available constants and their settings:

Constant | Description | Setting
network_config_connect_timeout | Set a connection timeout value | A value in milliseconds
network_config_use_non_blocking_socket | Tell GameMaker: Studio not to block on connect. | 0 = block, 1 = don't block

The first option (network_config_connect_timeout) simply sets the timeout for connecting to a server but doesn't change connection behaviour apart from the time you have to wait. It is recommended that you don't set this too low and keep it at about 1000 for a LAN only game or 4000 or so for internet, or the game may fail to connect randomly. If you wish to set a timeout value for sending/receiving packets then use the function network_set_timeout().

The second option (network_config_use_non_blocking_socket) means that the network connect functions will all return a socket_id instantly, but you can't send or receive on that socket until you've received an async network event. The event triggered will have the "type" key set to network_type_non_blocking_connect (you can find further details from the page on the Networking Asynchronous Event). This is a global setting as GameMaker: Studio does not support a mixture of blocking and non-blocking in one application.

Example:

network_set_config(network_config_connect_timeout, 1000);
network_set_config(network_config_use_non_blocking_socket, 1);

The above code will set the timeout for the network connection to 1000ms and tell GameMaker: Studio not to block on connect.

Back: Networking
Next: network_set_timeout

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


network_set_timeout

Set the timeout for reading and writing data through a socket.

Syntax:

network_set_timeout(socket, read_timeout, write_timeout);

Argument | Description
socket | The id of the socket to use.
read_timeout | The milliseconds in which a transfer from a server will timeout.
write_timeout | The milliseconds in which a transfer to a server will timeout.

Returns: N/A

Description

With this function you can set the timeout for reading and writing data to/from a server through the given socket. Note that the timeout does not generate any type of event, so you will need to deal with timeouts yourself using alarms (for example). Note that this value only affects the sending and receiving of data, and should you wish to change the connection timeout value then you should be using the function network_set_config.

Example:

network_set_timeout(sock, 3000, 3000);

The above code will set the timeout for reading and writing data through the socket indexed in the variable "sock" to 3 seconds.

Back: Networking
Next: network_send_broadcast

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Objects and Instances

This section has all the functions directly related to objects and instances.

To make a game in GameMaker: Studio you will need to first define objects and add them to the resource tree. An object can contain a number of different Events and in each event you can use either GML code or D'n'D to define behaviours for that object. However, this object is not placed into the game, but rather acts as a template for instances which are placed into rooms. An instance is basically a copy of the object that is placed in the room of your game and so, in this way, you would create one wall object and then place 100 instances of it into the room to create your game world.

Another thing to understand about instances and objects is that once an instance is created it can be manipulated and changed through D'n'D or code on an individual basis with none of these changes necessarily affecting any other instance of this same object. For example, you can use the room editor Right Click instance menu to change a single instance to have a different colour or orientation and these changes will only be current for that instance. All further instances will be created exactly the same as the defined object template.

Information on objects and instances can be found in the following pages:

  1. Objects
  2. Instances

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Instances

This section contains all the functions and variables specific to instances.

Instances are created from objects and, once created, they can be changed and manipulated through GML code and D'n'D actions. The following sections deal with the internal variables that all instances have, the functions that are specifically for finding and manipulating instances, and the routines available in GameMaker: Studio for limiting the amount of "active" instances in a room at one time.

  1. Instance Properties
  2. Instance Functions
  3. Deactivating Instances
Note that there are two additional built in variables related to using instances which can be used to retrieve certain details:
  1. instance_id
  2. instance_count

Back: Objects and Instances
Next: Objects

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_count

Returns the total number of instances currently active in the room.

Syntax:

instance_count

Returns: Real

Description

With this read only variable you can get a count of all active instances that are in the room. This will include the instance running the code, but does not include those instances that have been deactivated using the instance_deactivate functions. Note that this function will only give you the number of instances at the start of the step, so any changes to the instances in the room made after the step has started will not be taken into consideration.

Example:

if (instance_count < 100)
{
var dif = 100 - instance_count;
while (--dif > 0)
{
instance_create(random(room_width), random(room_height), obj_Star);
}
}

The above code will create multiple instances of the object "obj_Star" until the total instance count reaches 100.

Back: Instance Functions
Next: instance_id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_id

Returns the id of an instance in the room.

Syntax:

instance_id[0 ... n];

Returns: Real

Description

This read only array holds all the ids of every active instance within the room. This means that if you have used any of the instance_deactivate functions those instances that have been deactivated will not be included in this array (if you have used a value from this array previously, it will now return the keyword noone).

Example:

var i;
for (i = 0; i < instance_count; i += 1;)
{
with (instance_id[i]) speed += 0.1;
}

The above code will loop through all instances within the room and add 0.1 to their speed.

Back: Instance Functions
Next: instance_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Deactivating Instances

This section deals with instance deactivation.

GameMaker: Studio offers you the possibility to "switch off" instances so that they are no longer processed in any way. Technically they don't really exist anymore, except as a pointer within the deactivation process itself, which means that a deactivated instance cannot be manipulated or changed in any way at all until it is re-activated again. So, these functions should be used with great care as they can cause problems when not used properly, particularly with persistent objects, as a persistent object that has been deactivated will not be moved to the next room unless it is re-activated first (effectively deleting it from the game).

It is normally not necessary to deactivate instances every step of your game and this can actually cause your game to lag and runs slow. Instead it is recommended that you only run these functions every few steps in an alarm (for example), or if the view has changed position, and it is especially important that you do not use these functions in the draw event as this can lead to serious errors in your game.

A deactivated instance effectively ceases to exist in the game, but individual instances can still have their variables accessed. You cannot use with(object) or with(instance) however, but rather you must access the instance directly using it's unique id in the following form:

val = inst.variable;

In the above example, "inst" would be a variable that holds the id of the deactivated instance, and this is the only way that a deactivated instance can be referenced without it being activated previously.

NOTE: If you deactivate an instance on room start (ie:from the room creation code, or from an instance create event of an instance within the room) all instances that are placed within the room from the room editor will still run their create event before being deactivated.

WARNING: Deactivating instances that have physics enabled will NOT stop their fixtures from interacting within the physics simulation. For that you should set their phy_active variable to true or false as you activate/deactivate the instances.

The following functions exist for deactivating instances:

  1. instance_activate_all
  2. instance_activate_object
  3. instance_activate_region
  4. instance_deactivate_all
  5. instance_deactivate_object
  6. instance_deactivate_region

Back: Instances
Next: Instance Properties

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_activate_all

Activates all instances in the room.

Syntax:

instance_activate_all();

Returns: N/A

Description

With this function you can tell GameMaker: Studio to activate all instances that have been previously deactivated in a room.

Example:

instance_activate_all();
instance_deactivate_region(view_xview[0] - 64, view_yview - 64, view_wview[0] + 128, view_hview + 128, false, false);

The above code activates all instances within the room and then deactivates those that are outside of the limits of the current view.

Back: Deactivating Instances
Next: instance_activate_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_activate_object

Activates all instances of a given object in the room, or a particular instance if you provide an id.

Syntax:

instance_activate_object(obj);

Argument | Description
obj | The object or instance to activate (the keyword all can also be used).

Returns: N/A

Description

With this function you can activate a single instance or all instances of a specific object from all those that have been deactivated previously.

Example:

instance_activate_all();
instance_deactivate_region(view_xview[0] - 64, view_yview - 64, view_wview[0] + 128, view_hview + 128, false, false);
instance_activate_object(obj_Lights);

The above code activates all instances within the room and then deactivates those that are outside of the limits of the current view, except for the object "obj_Lights" which are re-activated again at the end.

Back: Deactivating Instances
Next: instance_activate_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_activate_region

Activates all instances inside or outside the given region.

Syntax:

instance_activate_region(left, top, width, height, inside);

Argument | Description
left | The x coordinate of the left of the rectangular region to activate.
top | The y coordinate of the top of the rectangular region to activate.
width | The width of the region to activate.
height | The height of the region to activate.
inside | Whether to activate instances on the inside of the region (true) or the outside (false).

Returns: N/A

Description

With this function you can define a region within the room to activate instances that have previously been deactivated. This region can either be flagged as "inside" or "outside" as demonstrated in the following image:

You can see in the image above that the "apple" instance is always active because, even if the sprite itself doesn't overlap the region, the bounding box does. So, instances are considered to be within the region specified when their bounding box overlaps with it, and the state of the collision mask (precise or not) is not taken into consideration.

Example:

instance_deactivate_all(true);
instance_activate_region(view_xview[0] - 64, view_yview - 64, view_wview[0] + 128, view_hview[0] + 128, false);

The above code deactivates all instances except the one that is running the code and then activates a region within the room.

Back: Deactivating Instances
Next: instance_deactivate_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_deactivate_all

Deactivates all instances in the room.

Syntax:

instance_deactivate_all(notme);

Argument | Description
notme | Whether to keep the calling instance activated (true) or not (false).

Returns: N/A

Description

This function will deactivate all instances that are in the room at the moment that the code is run. This may include the instance running the code if the "notme" flag is set to false, but normally you would want that instance to be active, in which case the "notme" flag should be set to true.

NOTE: If you deactivate an instance on room start (ie:from the room creation code, or from an instance create event of an instance within the room) all instances that are placed within the room from the room editor will still run their create event before being deactivated.

WARNING: Deactivating instances that have physics enabled will NOT stop their fixtures from interacting within the physics simulation. For that you should set their phy_active variable to true or false as you activate/deactivate the instances.

Example:

instance_deactivate_all(true);
instance_activate_region(view_xview[0] - 64, view_yview - 64, view_wview[0] + 128, view_hview + 128, false, false);

The above code deactivates all instances except the one that is running the code and then activates a region within the room.

Back: Deactivating Instances
Next: instance_deactivate_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_deactivate_object

Deactivates all instances of a given object in the room, or a particular instance if you provide an id.

Syntax:

instance_deactivate_object(obj);

Argument | Description
obj | The object or instance to deactivate (the keyword all can also be used).

Returns: N/A

Description

With this function you can deactivate a single instance or all instances of a specific object from all those that have been activated previously.

NOTE: If you deactivate an instance on room start (ie:from the room creation code, or from an instance create event of an instance within the room) all instances that are placed within the room from the room editor will still run their create event before being deactivated.

WARNING: Deactivating instances that have physics enabled will NOT stop their fixtures from interacting within the physics simulation. For that you should set their phy_active variable to true or false as you activate/deactivate the instances.

Example:

instance_deactivate_object(obj_Enemy);
instance_activate_region(view_xview[0] - 64, view_yview - 64, view_wview[0] + 128, view_hview + 128, false);

The above code deactivates all instances of the object "obj_Enemy" and then activates a region within the room.

Back: Deactivating Instances
Next: instance_deactivate_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_deactivate_region

Deactivates all instances inside (or outside) the given region.

Syntax:

instance_deactivate_region(left, top, width, height, inside, notme);

Argument | Description
left | The x coordinate of the left of the rectangular region to deactivate.
top | The y coordinate of the top of the rectangular region to deactivate.
width | The width of the region to deactivate.
height | The height of the region to deactivate.
inside | Whether to deactivate instances on the inside of the region (true) or the outside (false).
notme | Whether to exclude the calling instance from deactivation (true) or not (false).

Returns: N/A

Description

With this function you can define a region within the room to deactivate instances that have previously been activated. This region can either be flagged as "inside" or "outside" as demonstrated in the following image:

You can see in the image above that the "apple" instance is always inactive because, even if the sprite itself doesn't overlap the region, the bounding box does. So, instances are considered to be within the region specified when their bounding box overlaps with it, and the state of the collision mask (precise or not) is not taken into consideration.

NOTE: If you deactivate an instance on room start (ie:from the room creation code, or from an instance create event of an instance within the room) all instances that are placed within the room from the room editor will still run their create event before being deactivated.

WARNING: Deactivating instances that have physics enabled will NOT stop their fixtures from interacting within the physics simulation. For that you should set their phy_active variable to true or false as you activate/deactivate the instances.

Example:

instance_activate_all();
instance_deactivate_region(view_xview[0] - 64, view_yview - 64, view_wview[0] + 128, view_hview + 128, false, false);

The above code activates all instances and then deactivates a region within the room.

Back: Deactivating Instances

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Instance Functions

This section deals with functions specifically for dealing with instances.

Instances are the copies of object resources which have been placed in a room to interact and do things to make your game come to life. The following functions exist that deal with instances.

  1. instance_change
  2. instance_copy
  3. instance_create
  4. instance_destroy
  5. instance_exists
  6. instance_find
  7. instance_furthest
  8. instance_nearest
  9. instance_number
  10. instance_place
  11. instance_position

Back: Instances
Next: Deactivating Instances

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_change

Changes the calling instance to an instance of a different object.

Syntax:

instance_change(obj, perf);

Argument | Description
obj | The new object the calling object will change into.
perf | Whether to perform that new object's create and destroy events (true) or not (false).

Returns: N/A

Description

You can use this function to change one instance of an object into another instance of a different object, and while doing so decide whether to perform the initial instances destroy event and the new instances create event. In this way, you can have (for example) a bomb change into an explosion - in which case the "perf" argument would probably be true as you would want the bomb to perform its destroy event, as well as the explosion to perform its create event - or you could have your player character change into a different one - in which case the "perf" argument would probably be false as you do not want the instances to perform their create and destroy events.

It is worth noting that changing the instance means that you should perform no further actions with that instance until the next step, in particular trying to access variables etc... as that will cause an error. Basically, you change the instance but it is not actually available until the end of the current step, so to access any of the variables it contains directly (for example, calling obj_Changed.x) will not work.

WARNING! When changing a physics enabled instance, the physical properties will not be carried over to the new instance being changed into. Therefore you should have code in place to "transfer" the physics state of the current instance over to the new instance, or have defined the new instances physical properties in its Create Event, or in the object editor. For this reason it is recommended that you not use this function with physics enabled instances, but rather use a combination of instance_destroy() and instance_create().

Example:

if keyboard_check(vk_enter)
{
instance_change(obj_Player_Swimming, false);
exit;
}

The above code will change the calling instance into an instance of "obj_Player_Swimming" without performing the original instances destroy event nor the new instances create event when the user presses the "Enter" key, exiting the code block when done.

Back: Instance Functions
Next: instance_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_copy

Creates a copy of the calling instance.

Syntax:

instance_copy(perf);

Argument | Description
perf | Whether to perform the new instance's Create event (true) or not (false).

Returns: Real

Description

With this function you can "clone" an instance as this will create a new version of the instance running the code at its same position. The "perf" argument is used to instruct this new instance to perform the create event or not. This function returns the id of the new instance which can then be stored in a variable or used to access that instance.

NOTE: If you choose not to perform the create event, you may encounter errors if the instance depends on any variables initialised in this event.

Example:

var inst;
inst = instance_number(object_index);
if inst < 10
{
instance_copy(true);
}

Back: Instance Functions
Next: instance_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_create

Creates an instance of a given object at a given position.

Syntax:

instance_create(x, y, obj);

Argument | Description
x | The x position the object will be created at.
y | The y position the object will be created at.
obj | The object to create an instance of.

Returns: Real

Description

With this function you can create a new instance of the specified object at any given point within the room. This function returns the id of the new instance which can then be stored in a variable or used to access that instance. Note that this function will also call the create event of the instance being created before continuing with the code or actions for the event that used the function.

Example:

var inst;
inst = instance_create(x, y, obj_Bullet);
with (inst)
{
speed = other.shoot_speed;
direction = other.image_angle;
}

The above code creates anew instance of the object "obj_Bullet" and stores the instance id in a variable. This variable is then used to assign speed and direction to the new instance.

Back: Instance Functions
Next: instance_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_destroy

Destroys the calling instance, removing it from the room.

Syntax:

instance_destroy();

Argument | Description
id | The instance ID or object_index to destroy (optional, default is the calling instance)
execute_event_flag | Set to true or false to perform the destroy event or not (optional, default is true)

Returns: N/A

Description

You call this function whenever you wish to "destroy" an instance, normally triggering a Destroy Event and also a Clean Up event. This will remove it from the room until the room is restarted (unless the room is persistent). Calling the function with no arguments will simply destroy the instance that is currently in scope and running the code, but you can provide an optional "id" argument and target a specific instance by using the instance ID value, or you can target all instances of a particular object by using an object_index. For example:

instance_destroy(other); // destroy the other instance in a Collision Event
instance_destroy(obj_Bullet); // destroy ALL instances of the object "obj_Bullet"

The second optional flag permits you to "switch off" the Destroy Event for the instance being destroyed. By default the Destroy Event will always be performed, but if you set this flag to false then you can make the instance destroy itself and skip performing that event.

It is worth noting that when you destroy an instance, its destroy event is called immediately after the code or action that calls the destroy. Second, although the destroy event is performed, the instance is not immediately removed from the game, and it will continue to perform the code contained in the current event. Only when the current event is over will it be removed from the game.

So, if you have, for example, this code:

if hp <= 0 instance_destroy();
score += 10;

The variable "score" will be incremented even though the instance_destroy function has been called, and the instance will finally be removed from your game at the end of the event. Be careful of this, as if you have (for example) created a dynamic resource for the instance, like a data structure, and then have destroyed that resource in the destroy event, if there are any references to it after the destroy function or action has been performed then you will get an "unknown resource" error, as the destroy event removed it from the game.

Example:

if bbox_right < 0 || bbox_left > room_width || bbox_bottom &let; 0 || bbox_top > room_height
{
instance_destroy(id, false);
}

The above code will destroy the instance running the code without calling the Destroy Event if the instance is outside the room bounds.

Back: Instance Functions
Next: instance_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_exists

Returns whether an instance of the given object exists in the current room.

Syntax:

instance_exists(obj);

Argument | Description
obj | The object or instance to check for the existence of.

Returns: Boolean

Description

This function can be used in two ways depending on what you wish to check. You can give it an object_index to check for, in which case this function will return true if any active instances of the specified object exist in the current room, or you can also supply it with an instance id, in which case this function will return true if that specific instance exists and is active in the current room.

Please note that this function does not take into account those instances that have been deactivated using the instance_deactivate functions.

Example:

if !instance_exists(obj_Enemy)
{
score += 200;
room_goto(rm_hiscores);
}

The above code checks to see if any instances of the object "obj_Enemy" exist and if not it adds to the variable "score" and changes room.

Back: Instance Functions
Next: instance_find

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_find

Returns the id of the (n)th instance of a given object.

Syntax:

instance_find(obj, n);

Argument | Description
obj | The object index of which to find the nth instance
n | The number of the instance to find.

Returns: instance id or noone

Description

All instances have a unique identifier (id) which can be used to modify and manipulate them while a game is running, but you may not always know what the id for a specific instance is and so this function can help as you can use it to iterate through all of them to find what you need. You specify the object that you want to find the instance of and a number, and if there is an instance at that position in the instance list then the function returns the id of that instance, and if not it returns the special keyword noone. You can also use the keyword all to iterate through all the instances in a room, as well as a parent object to iterate through all the instances that are part of that parent / child hierarchy and you can even specify an instance itself (if you have its id) as a check to see if it actually exists in the current room. Please note that as instances are sorted in an arbitrary manner, there is no specific order to how the instances are checked by this function, and any instance can be in any position.

The maximum value for "n" in this function would be

  • For the keyword all: instance_count - 1
  • For an object index: instance_number(OBJ) - 1

Example:

var i;
for (i = 0; i < instance_number(obj_Enemy); i += 1)
{
enemy[i] = instance_find(obj_Enemy,i);
}

The above code will use a for loop to iterate through all the instances of "obj_Enemy" and store their id in the array "enemy[]".

Back: Instance Functions
Next: instance_furthest

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_furthest

Returns the id of the instance of an object furthest from a given position.

Syntax:

instance_furthest(x, y, obj);

Argument | Description
x | The x position to check for instances far from.
y | The y position to check for instances far from.
obj | The object to check for instances of.

Returns: Real

Description

This function will check all the instances of the given object to see which is furthest from the given point of origin. If no instances of the object exist, the function will return the keyword noone, but if there are instances then it will return the id of the instance found. Please note that if the instance running the code was created as an instance of the object being checked, then it will be included in the check.

Example:

var inst;
inst = instance_furthest(x, y, object_index);
if inst != id
{
draw_line(x, y, inst.x, inst.y);
}

The above code will find the furthest instance that shares the same object index as the instance running the code and store the id in a variable. This variable is then checked to see if it is the same as the id of the calling instance and, if it is not, a line is drawn between the two instances.

Back: Instance Functions
Next: instance_nearest

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_nearest

Returns the id of the instance of an object nearest to a given position.

Syntax:

instance_nearest(x, y, obj);

Argument | Description
x | The x position to check from.
y | The y position to check from.
obj | The object to check for instances of.

Returns: Real

Description

This function will check all the instances of the given object to see which is nearest to the given point of origin. If no instances of the object exist, the function will return the keyword noone, but if there are instances then it will return the id of the instance found. Please note that if the instance running the code was created as an instance of the object being checked, then it will be included in the check.

Example:

var inst, xx;
xx = x;
x -= 10000;
inst = instance_nearest(xx, y, object_index);
if inst != id
{
draw_line(x, y, inst.x, inst.y);
}
x += 10000;

The above code move the current instance 10000 pixels then check its previous position to find the nearest instance of the same object type. If that instance is itself, it will do nothing more than move back to its original position, but should the instance found be different, it will draw a line between the two.

Back: Instance Functions
Next: instance_number

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_number

Returns the number of active instances of a given object.

Syntax:

instance_number(obj);

Argument | Description
obj | The object to total the number of instances of.

Returns: Real

Description

With this function you can find out how many active instances of the specified object exists in the room. Please note that those instances which have been deactivated with the instance_deactivate functions will not be included in this check.

Example:

if instance_number(object_index) < 50
   {
instance_create(random(room_width), random(room_height), object_index);
}

The above code will check the number of instances that are created form the same object as the current instance and then if there are less than 50, create another one at a random position within the room.

Back: Instance Functions
Next: instance_place

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_place

Checks for a collision with the specified object and returns its id.

Syntax:

instance_place(x, y, obj);

Argument | Description
x | The x position to check for instances.
y | The y position to check for instances.
obj | The object to check for instances of.

Returns: Real

Description

With this function you can check a position for a collision with another instance or all instances of an object using the collision mask of the instance that runs the code for the check. When you use this you are effectively asking GameMaker: Studio to move the instance to the new position, check for a collision, move back and tell you if a collision was found or not. This will work for precise collisions, but only if both the instance and the object being checked for have precise collision masks selected otherwise only bounding box collisions are applied. this function will return the unique instance id of the object being collided, but if that is not needed it is slightly faster to use the function place_meeting. This function also accepts the special keywords all and other and will return the keyword noone if no collision occurs.

Note that the given x/y coordinates will be rounded to the nearest integer before the check is performed, so if this is not what you require (or you have been using a legacy GameMaker product), you should floor the coordinates in the check: instance_place(floor(x), floor(y), obj_Enemy).

Example:

var inst;
inst = instance_place(x, y, obj_Enemy);
if inst != noone
{
   hp -= inst.dmg;
with (inst) instance_destroy();
}

The above code will check for a collision with instances of "obj_Enemy" and if there is one, it will reduce the "hp" variable by the amount stored in the colliding instance's "dmg" variable and then destroy the colliding instance.

Back: Instance Functions
Next: instance_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


instance_position

Checks for a collision with the specified object at a specific location and returns its id.

Syntax:

instance_position( x, y, obj );

Argument | Description
x | The x position to check for instances.
y | The y position to check for instances.
obj | The object to check for instances of.

Returns: Real

Description

With this function you can check a position for a collision with another instance or all instances of an object. When you use this you are checking a single point in the room for an instance or an object. This check will be done against the bounding box of the instance or against the mask of the instance if that instance has precise collisions checked and will return the unique instance id. If you do not need the id of the colliding instance you should consider using position_meeting instead. This function also accepts the special keywords all and other and will return the keyword noone if no collision occurs.

Example:

var inst;
inst = instance_position(mouse_x, mouse_y, obj_Pause_Button);
if inst != noone
{
with (inst) image_index=1;
instance_create(room_width / 2, 0, obj_Menu);
}

The above code will check for a collision with an instance of "obj_Pause_Button" at the mouse position, and if there is one it will then use the returned id to set its image_index to a new value before creating a new instance of the object "obj_Menu".

Back: Instance Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Instance Properties

This section shows all the built-in variables that an instance has.

When an instance is created, GameMaker: Studio generates a number of pre-defined variables to help you set and change certain common properties, such as the sprite_index, or the depth. Below you can find a list of all these built-in variables.

General Variables

These variables deal with general instance properties:

  1. id
  2. solid
  3. visible
  4. persistent
  5. depth
  6. alarm
  7. object_index

Sprite Variables

These variables deal with sprites and their sub-images:

  1. sprite_index
  2. sprite_width
  3. sprite_height
  4. sprite_xoffset
  5. sprite_yoffset
  6. image_alpha
  7. image_angle
  8. image_blend
  9. image_index
  10. image_number
  11. image_speed
  12. image_xscale
  13. image_yscale

Mask Variables

These variables deal with the collision mask:

  1. mask_index
  2. bbox_bottom
  3. bbox_left
  4. bbox_right
  5. bbox_top

Additional Variables

There are a great many more specialised variables that are not used as much as the ones above as they relate to specific aspects of GameMaker: Studio that not all games will make use of. The following sections deal with these variables:

  1. Movement Variables
  2. Path Variables
  3. Timeline Variables
  4. Physics Variables

Back: Instances
Next: Instance Functions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


alarm

Sets an alarm for the instance.

Syntax:

alarm[0 ... 11]

Returns: Real.

Description

This 1 dimension array is used to get the current value for any alarms that the instance may have, or to set those alarms. There are twelve alarms built into each instance of an object, and each one has its own event that will run when this variable reaches 0. it should be noted that the alarm is not finished at that point (although the event has been triggered) as the next step it will go down to -1, so if you need to stop an alarm for any reason you should set its array value to -1 not 0. Alarm times are calculated in game steps, with a value of 30 being 30 steps etc...

NOTE: An alarm with no actions or code in it will not run. However, even with just a comment and no code, the alarm will count down.

You can set the alarm array directly (and retrieve the current alarm value directly by using the array too), but under some circumstances this is not the most appropriate method, so you can also use the function alarm_set() to set an alarm, and the function alarm_get() to get the value of an alarm.

Example:

if canshoot
{
if keyboard_check_pressed(vk_space)
{
canshoot = false;
alarm[0] = room_speed;
instance_create(x, y, obj_Bullet);
}
}

The above code checks a variable and then if it is true, checks for a key press and if that is true it finally sets the variable to false, sets an alarm (where it will be set to true again) and creates an instance.

Back: Instance Properties
Next: object_index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


bbox_bottom

Returns the position of bottom of the bounding box.

Syntax:

bbox_bottom

Returns: Real

Description

This read only variable returns the position within the room (along the y-axis) of the bottom of the bounding box for the instance, where the bounding box is defined by the maximum width and height of the mask for the instance (as set by the sprite or by the mask index). Even when a sprite has a precise collision mask, the bounding box exists and is used for certain things, and so you can use this variable to find it. Please note that when the instance has no sprite assigned the bbox_ variables will always return 1.

Example:

if bbox_bottom > room_height
{
y = room_height - sprite_yoffset;
}

The above code checks to see if the bounding box of the instance is outside the room and if it is it sets the instance to a new position.

Back: Instance properties
Next: bbox_left

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


bbox_left

Returns the position of the left hand side of the bounding box.

Syntax:

bbox_left

Returns: Real

Description

This read only variable returns the x position (within the room) of the left hand bounding box for the instance, where the bounding box is defined by the maximum width and height of the mask for the instance (as set by the sprite or by the mask index). Even when a sprite has a precise collision mask, the bounding box exists and is used for certain things, and so you can use this variable to find it. Please note that when the instance has no sprite assigned the bbox_ variables will always return 1.

Example:

if bbox_left < 0
{
x = sprite_xoffset;
}

The above code checks to see if the bounding box of the instance is outside the room and if it is it sets the instance to a new position.

Back: Instance properties
Next: bbox_right

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


bbox_right

Returns the position of the right hand side of the bounding box.

Syntax:

bbox_right

Returns: Real

Description

This read only variable returns the x position (within the room) of the right hand side of the bounding box for the instance, where the bounding box is defined by the maximum width and height of the mask for the instance (as set by the sprite or by the mask index). Even when a sprite has a precise collision mask, the bounding box exists and is used for certain things, and so you can use this variable to find it. Please note that when the instance has no sprite assigned the bbox_ variables will always return 1.

Example:

if bbox_right > room_width
{
x = room_width - sprite_xoffset;
}

The above code checks to see if the bounding box of the instance is outside the room and if it is it sets the instance to a new position.

Back: Instance properties
Next: bbox_top

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


bbox_top

Returns the position of the top of the bounding box.

Syntax:

bbox_top

Returns: Real

Description

This read only variable returns the y position (within the room) of the top of the bounding box for the instance, where the bounding box is defined by the maximum width and height of the mask for the instance (as set by the sprite or by the mask index). Even when a sprite has a precise collision mask, the bounding box exists and is used for certain things, and so you can use this variable to find it. Please note that when the instance has no sprite assigned the bbox_ variables will always return 1.

Example:

if bbox_top < 0
{
y = sprite_yoffset;
}

The above code checks to see if the bounding box of the instance is outside the room and if it is it sets the instance to a new position.

Back: Instance properties

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


depth

Sets the depth of the instance.

Syntax:

depth

Returns: Real

Description

When you create an object you can assign it an initial depth which defines how the instances of that object will be drawn in the room when the game is being played and this variable can be used to get and to change the depth of the instance while the game is running. In GameMaker: Studio a low depth (of negative numbers like -1000) means that the instance will be drawn "closer" to the player and on top of all instances with a lower depth, while a high depth (of positive numbers like 1000) means that the instance will be drawn "further away" from the player and beneath those instances that have a lower depth.

NOTE: Instances of an object that have the same depth can be drawn above or below each other even when they appear to be placed one on top of the other in the room editor. If you want to guarantee that something is drawn over or under everything else, you should always set the depth correctly.

WARNING: You cannot set the depth of an instance in its draw event (all other events are fine). This may lead to some unexpected behaviour and even crash your game!

Example:

depth = -y;

The above code will set the depth of the instance to the negative value of its y position in the room (this is very handy for isometric games).

Back: Instance Properties
Next: alarm

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


id

The unique identifier for the instance.

Syntax:

id

Returns: Real

Description

This read-only variable holds the unique identifying number for the instance. Every instance that you create is given a number that is used internally to identify this instance and this variable is what you can use to reference it. The id is also returned (and can be stored in a variable) when an instance is created using instance_create().

Note: The value of this variable is not the same as the identifier that the instance is given in the room editor and is also different to the instance_id array which contains all the ids of all the currently active instances.

Example:

for(var i = 0; i < instance_count; i++;)
{
if instance_id[i] != id
{
instance_id[i].scr += 5;
}
}

The above code adds 5 to the "scr" variable for every active instance in the room except the one running the code. It does this by looping through ALL the active instances (using the "instance_id" array to return each active instance's ID) and comparing them against the built in "id" variable, which is the ID of the original instance running the code.

Back: Instance Properties
Next: solid

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


image_index

The current sub-image being shown for the instance sprite.

Syntax:

image_index

Returns: Real

Description

A sprite is made up of one or more sub-images which can make the sprite appear animated as they switch from one to the other, or can they can be switched between in code to give different "states", much like a button has in windows. If the sprite is animated, then you can get the current frame of the animation by checking the image_index variable, or if you want to change the state of a static sprite, you can select a new sub-image by setting this variable to the desired sub-image for the sprite. Please note that for changes in this variable to be visible, the instance should have either no draw event (and so GameMaker: Studio will default draw the sprite) or be drawn using one of the extended drawing functions like draw_self() or draw_sprite_ext().

Please note that while using skeletal animation sprites, you can still get and set the image_index values - see the function skeleton_animation_get_duration for examples of how to do this.

Example:

if image_speed > 0
{
if image_index > image_number - 1 instance_destroy();
}

The above code checks to see if the sprite is animating, and if it is it then checks to see if the current image_index is greater than the number of sub-images and if it is it destroys the instance.

Back: Instance Properties
Next: image_number

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


image_alpha

The alpha transparency value of the image.

Syntax:

image_alpha

Returns: Real

Description

This variable is used to get or to set the alpha value for the sprite. Alpha is always calculated as a value between 0 and 1 where 0 is completely transparent and 1 is completely opaque. Please note that for changes in this variable to be visible, the instance should have either no draw event (and so GameMaker: Studio will default draw the sprite) or be drawn using one of the extended drawing functions like draw_self() or draw_sprite_ext().

NOTE: On the HTML5 platform, this variable is not clamped. Therefore if you have a value greater than one, it will "wrap" back to 0 again, giving flickering results. Likewise if you go below 0, the alpha will "wrap" back to 1. You can use the function clamp for this.

Example:

if image_alpha > 0 image_alpha -= 0.01;

The above code will slowly reduce the image_alpha until it reaches 0.

Back: Instance Properties
Next: image_angle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


image_angle

The current angle at which the instance sprite is drawn

Syntax:

image_angle

Returns: Real

Description

This value sets the angle (rotation) of the sprite and is measured in degrees, with the right being 0º, up being 90º, left being 180º and down being 270º. Set this variable to 0 to reset the sprite to be drawn as was defined in the sprite editor. Please note that for changes in this variable to be visible, the instance should have either no draw event (and so GameMaker: Studio will default draw the sprite) or be drawn using one of the extended drawing functions like draw_self() or draw_sprite_ext().

Example:

image_angle = point_direction(x, y, mouse_x, mouse_y);

The above code will rotate the sprite of the instance to always point at the mouse position.

Back: Instance Properties
Next: image_blend

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


image_blend

The colour to blend with the instance sprite.

Syntax:

image_blend

Returns: Real

Description

This variable controls the "tinting" of the instance sprite and the default value is -1 (but can also be c_white). Any other value (including internal colour constants like c_red, or c_aqua) will blend the specified colour with the original sprite. Please note that for changes in this variable to be visible, the instance should have either no draw event (and so GameMaker: Studio will default draw the sprite) or be drawn using one of the extended drawing functions like draw_self() or draw_sprite_ext().

Please note that you should try to limit blending on the HTML5 platform (unless using WebGL), as each blended sprite has to be cached separately and so having many blended sprites may adversely affect performance (you can also set the cache size using the function sprite_set_cache_size).

Example:

image_blend = make_colour_hsv(255, 255, random(255));

The above code will set the image_blend of the sprite defined for the instance to a random colour.

Back: Instance Properties
Next: image_index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


image_number

Returns the number of sub-images of an instance sprite.

Syntax:

image_number

Returns: Real

Description

This read only variable can be used to get the number of sub-images in a sprite that has been assigned to an instance (if you need the number of sub-images for a sprite other than the one assigned to the instance you should use sprite_get_number). Please note that when there is (for example) 1 sub-image this variable will return "1" but the image_index of that sub-image is 0.

Example:

if image_speed > 0
{
if image_index > image_number - 1 instance_destroy();
}

The above code checks to see if the sprite is animating, and if it is it then checks to see if the current image_index is greater than the number of sub-images and if it is it destroys the instance.

Back: Instance Properties
Next: image_speed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


image_speed

The speed with which the image_index is changed.

Syntax:

image_speed

Returns: Real

Description

This variable determines the speed in which GameMaker: Studio will cycle through the sub-images for the current instance sprite. A value of 0 will cause no cycling, while a value of 1 will cycle one image per step, but you are not limited to this range as you can use values greater than 1 to animate faster (frames will be skipped), decimal values to animate slower (frames will be shown over various steps) or even negative values to reverse the speed of the animation.

Example:

with (instance_create(x, y, obj_Explosion))
{
image_speed = 0.5;
}

The above code creates an instance of the object "obj_Explosion" and sets its image_speed to 0.5 (effectively halving the running speed).

Back: Instance Properties
Next: image_xscale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


image_xscale

Returns or sets the horizontal sprite scale for the instance.

Syntax:

image_xscale

Returns: Real

Description

This value sets the horizontal scaling applied to the sprite that has been assigned to the current instance. A scale of 1 indicates no scaling (1:1), smaller values will scale down (0.5, for example, will half the width of the sprite), larger values will scale up and negative values will flip the sprite and scale it unless the value used is exactly -1 (in which case the sprite is just flipped about its origin with no scaling).

Example:

if image_xscale < 5
{
image_xscale += 0.2;
image_yscale = image_xscale;
}
else
{
instance_create(x,y,obj_Explosion);
instance_destroy();
}

The above code scales the sprite and then once it is scaled to 5 times its original size, a new instance of another object is created and the instance destroyed.

Back: Instance Properties
Next: image_yscale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


image_yscale

Returns or sets the vertical sprite scale for the instance.

Syntax:

image_yscale

Returns: Real

Description

This value sets the vertical scaling applied to the sprite that has been assigned to the current instance. A scale of 1 indicates no scaling (1:1), smaller values will scale down (0.5, for example, will half the width of the sprite), larger values will scale up and negative values will mirror the sprite and scale it unless the value used is exactly -1 (in which case the sprite is just mirrored about its origin with no scaling).

Example:

if image_yscale < 5
{
image_yscale += 0.2;
image_xscale = image_yscale;
}
else
{
instance_create(x,y,obj_Explosion);
instance_destroy();
}

The above code scales the sprite and then once it is scaled to 5 times its original size, a new instance of another object is created and the instance destroyed.

Back: Instance Properties

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


mask_index

Sets the collision mask of the given instance.

Syntax:

mask_index

Returns: Real

Description

When you define an object in GameMaker: Studio you can assign it a mask to be used for collisions rather than the one that corresponds to the defined sprite. This variable can be used to find the sprite_index of that mask (or it will return -1 if no sprite has been assigned) or to set the mask for an instance to the chosen sprite. Setting the mask index means that you can have, for example, a sprite for the instance with an irregular shape, yet give it a circular collision mask that is gotten from a different sprite.

Example:

mask_index = spr_Round;

The above code sets the mask of the instance to that of the sprite "spr_Round".

Back: Instance properties
Next: bbox_bottom

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_index

Returns the index number of the object that the instance has been made from.

Syntax:

object_index

Returns: Real

Description

This read only variable returns the index of the object that the instance has been created from. This is not the same as the object name, which is a string and can be found using object_get_name, as this function returns the index number, which is a unique number that GameMaker: Studio assigns to every object at the time of creation.

Example:

obj_name = object_get_name(object_index);

The above code will use the object_index to find the name of the object that the current instance has been created from.

Back: Instance Properties
Next: id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


persistent

Sets the persistence of the instance.

Syntax:

persistent

Returns: Boolean

Description

This variable can be read to find out if the instance is flagged as persistent or not, or it can used to set persistence to true (persistent) or false (not persistent) for the instance. A persistent instance is one that will be "carried over" from room to room, meaning (for example) that it only has to be created once at the start of the game and it will be present in all further rooms. Care should be taken with persistence as it is easy to lose track of persistent instances which can lead to problems later in the development of the game.

A persistent object will still have its Game Start, Game End, Room Start and Room End events triggered, however if you restart the game (with, for example, the game_restart() function) all persistent objects will be removed and only exist when created again by the game. Also note that if you deactivate a persistent object, it will no longer pass from one room to another unless re-activated before the Room End event is triggered.

Example:

if !persistent
{
persistent = true;
}

The above code will check the instance to see if persistence is flagged as false and if the instance is NOT persistent the persistence flag is set to true.

Back: Instance Properties
Next: depth

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


solid

Sets the solid flag for the object to true or false.

Syntax:

solid

Returns: Boolean

Description

An instance can be flagged as solid through the object properties, or by changing the value of this variable. If solid is true, a special collision event is generated whereby the instance is returned automatically to the position it was at in the step previous to the collision. If it is set to false, all collisions must be dealt with through the collision event.

Example:

with (object_index)
{
solid = !solid;
}

The above code checks the "solid" flag of all instances that have the same object_index as that which is running the code and if "solid" is false it is changed to true.

Back: Instance Properties
Next: visible

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_index

This is the index of the current sprite for the instance.

Syntax:

sprite_index

Returns: Real

Description

This variable returns the index of the current sprite for the instance, or -1 if the instance has no sprite associated with it. You can change it to give the instance a different sprite by giving it the name of a sprite from the resource tree or by using a variable that has an externally loaded sprite indexed in it. Changing the sprite does not change the index of the currently visible sub-image, so if you change the sprite on sub-image number 3, the new sprite will be drawn with that sub-image visible (assuming it has the same number of sub-images).

Example:

with (obj_Check)
{
if !collision_line(x, y, other.x, other.y, obj_Wall, false, true)
{
sprite_index = spr_spotted;
}
else
{
sprite_index = spr_clear;
}
}

The above code will loop through all instances of "obj_Check" checking for a collision line between them and the instance running the code. The sprite of those instances will be changed depending on the return value (true or false) for the collision line.

Back: Instance Properties
Next: sprite_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_height

Returns the height of the currently assigned sprite.

Syntax:

sprite_height

Returns: Real

Description

This read only variable returns the height of the sprite that has been assigned to the instance. This height is returned in pixels and will be dependant on the image_yscale. If you need the un-scaled height you should use sprite_get_height.

Example:

if sprite_height != sprite_get_height(sprite_index)
{
image_yscale = 1;
}

The above code checks the height of the sprite assigned to the instance running the code against the height of the sprite resource and if it is not the same, it resets the image_yscale to 1,

Back: Instance Properties
Next: sprite_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_width

Returns the width of the currently assigned sprite.

Syntax:

sprite_width

Returns: Real

Description

This read only variable returns the width of the sprite that has been assigned to the instance. This width is returned in pixels and will be dependant on the image_xscale. If you need the un-scaled width you should use sprite_get_width.

Example:

if sprite_width != sprite_get_width(sprite_index)
{
image_xscale = 1;
}

The above code checks the width of the sprite assigned to the instance running the code against the width of the sprite resource and if it is not the same, it resets the image_xscale to 1,

Back: Instance Properties
Next: sprite_xoffset

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_xoffset

Returns the x component of the sprite origin.

Syntax:

sprite_xoffset

Returns: Real

Description

This read only variable returns the local xoffset (the x component of the origin as defined in the sprite editor) of the sprite that has been assigned to the instance. This xoffset is returned in pixels and will be dependant on the image_xscale, so that (for example) if a square 32x32 sprite is defined as having the x origin at 16, when that sprite is scaled by 2 this variable will return 32. If you need the un-scaled xoffset you should use sprite_get_xoffset.

Example:

if x - sprite_xoffset < 0
{
x = sprite_xoffset;
}

The above code checks to see if the left edge of the sprite of the instance is outside the room and if it is it moves the instance so that the whole sprite is visible.

Back: Instance Properties
Next: sprite_yoffset

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


sprite_yoffset

Returns the y component of the sprite origin.

Syntax:

sprite_yoffset

Returns: Real

Description

This read only variable returns the local yoffset (the y component of the origin as defined in the sprite editor) of the sprite that has been assigned to the instance. This yoffset is returned in pixels and will be dependant on the image_yscale, so that (for example) if a square 32x32 sprite is defined as having the y origin at 16, when that sprite is scaled by 2 this variable will return 32. If you need the un-scaled yoffset you should use sprite_get_yoffset.

Example:

if y - sprite_yoffset < 0
{
y = sprite_yoffset;
}

The above code checks to see if the top edge of the sprite of the instance is outside the room and if it is it moves the instance so that the whole sprite is visible.

Back: Instance Properties
Next: image_alpha

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


visible

Sets the visibility of the instance.

Syntax:

visible

Returns: Boolean

Description

An instance can be flagged as visible or not by setting this variable to true (visible) or false (invisible). This works by telling GameMaker: Studio to skip the draw event for this instance, so care must be taken when using this as it means that no code placed in the draw event will be run while the instance is not visible.

Example:

if other.visible = true
{
x = xprevious;
y = yprevious;
}

The above code will check the visible flag of the "other" instance in a collision and if it is set to true move that instance back to its previous position.

Back: Instance Properties
Next: persistent

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Objects

This section outlines the functions related to an objects properties.

GameMaker: Studio gives you a number of functions that permit you to get various details about an object. Note, an object is not an instance (an in-game entity), it is purely a resource from which all instances are created. This means that the return values of these functions may be different to the actual values shown by instances in the room, as once an instance is created it can be changed through code and D'n'D actions.

  1. object_exists
  2. object_index
  3. object_get_depth
  4. object_get_mask
  5. object_get_name
  6. object_get_parent
  7. object_get_persistent
  8. object_get_solid
  9. object_get_sprite
  10. object_get_visible
  11. object_get_physics
  12. object_is_ancestor

There are also a number of functions that permit you set the properties for an object. It should be noted that any instances of this object that already exist in the room may not be affected by these functions, but all new instances of this object created in the room will be, so it is recommend that you never change an objects properties when instances of that object are present in the current room.

  1. object_set_depth
  2. object_set_mask
  3. object_set_persistent
  4. object_set_solid
  5. object_set_sprite
  6. object_set_visible

Finally, you can also use certain functions to generate events from code within a specific instance or object. These functions can be very useful, especially when dealing with Parents and Children, and are outlined in the following section:

  1. Generating Events

Back: Objects and Instances
Next: Instances

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_exists

Returns whether an object with the given index exists or not.

Syntax:

object_exists(obj);

Argument | Description
obj | The index of the object to check.

Returns: Boolean

Description

This function returns whether an object with the specified index exists or not. Note that this checks to see if an object is present in the resource tree, and not actually in the game room. For that you should use the function instance_exists.

Example:

if object_exists(obj_temp)
{
with (obj_Temp) scr_add_event();
}

The above code checks the variable "obj_temp" to make sure that it stores the index of an object and then, if it does, it makes the object run a script.

Back: Objects
Next: object_get_depth

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_get_depth

Returns the depth of the specified object.

Syntax:

object_get_depth(obj);

Argument | Description
obj | The index of the object to check

Returns: real

Description

With this function you can get the depth that was specified for an object in the resource tree. Please note that this is not an instance function! An object can have a different depth to an instance of that same object when in a room. You can set an individual instances depth using the depth instance variable.

Example:

if depth != object_get_depth(object_index) depth = object_get_depth(object_index);

The above example will check the depth of the instance against the depth of the object_index of the instance. If they are not the same, then it will assign the same depth as the one the object index has to the instance.

Back: Objects
Next: obj_get_mask

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_get_mask

Returns the mask_index of the specified object.

Syntax:

object_get_mask(obj);

Argument | Description
obj | The index of the object to check

Returns: real

Description

This function will tell you whether the object you are checking has a mask index or not, and if it does then it will return the index of that mask, or -1 if it does not. Please note that this is not an instance function! You can have an object with no mask while an instance of that same object can have one and vice-versa, or they can even have different masks. You can set an individual instances mask index using the mask_index instance variable.

Example:

if mask_index != object_get_mask(object_index) mask_index = object_get_mask(object_index);

The above example will check the mask index of the instance against the mask of the object_index of the instance. If they are not the same, then it will assign the same mask as the one the object index has to the instance.

Back: Objects
Next: obj_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_get_name

Returns the name of the specified object as defined in the resource tree.

Syntax:

object_get_name(obj);

Argument | Description
obj | The index of the object to check.

Returns: String

Description

This function will return the name as a string of the specified object. This name is the one that has been specified for the object in the resource tree of the main GameMaker: Studio window. Please note that this is only a string and cannot be used to reference the object directly - for that you would need the object index. You can, however, use this string to get the object index using the returned string along with the function asset_get_index().

Example:

str = object_get_name(object_index);

The above code will get the name of the object index for the instance running the code and store the return value in the variable "str".

Back: Objects
Next: obj_get_parent

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_get_parent

Returns the parent of the specified object.

Syntax:

object_get_parent(obj);

Argument | Description
obj | The index of the object to check

Returns: Real

Description

This function will get you the object_index of any parent that has been assigned to the specified object, or else return -100 to show that the object has no parent assigned to it, or -1 if the object being checked does not exist. For more information on parents see the section More About Objects: Parents.

Example:

par = object_get_parent(object_index);

The above code will get the parent of the object index for the instance running the code and store the return value in the variable "par".

Back: Objects
Next: object_get_persistent

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_get_persistent

Returns if the specified object is flagged as persistent or not.

Syntax:

object_get_persistent(obj);

Argument | Description
obj | The index of the object to check.

Returns: Boolean

Description

This function will tell you whether the object you are checking has been flagged as "persistent" or not. A persistent object is one that will cause any instances of it to be carried through from room to room unless they are explicitly destroyed. Please note that this is not an instance function! So, you can have a persistent object and a non-persistent instance of the same object and vice-versa. You can set an individual instances persistent flag using the persistent instance variable.

Example:

if !persistent && object_get_persistent(object_index) persistent=true;

The above code will check the instance running it to see if it is persistent or not as well as check the object index of the instance to see if it is flagged as persistent or not. If the instance is not persistent yet the object index is flagged as persistent, it will set "persistent" to true for that instance.

Back: Objects
Next: object_get_solid

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_get_visible

object_get_physics

Returns whether an object is flagged as physics enabled or not.

Syntax:

object_get_physics(obj);

Argument | Description
obj | The index of the object to check.

Returns: Boolean

Description

This function will tell you whether the object you are checking has been flagged as "physics enabled", returning true, or not, returning false.

Example:

if object_get_physics(object_index)
   {
   phy_active = true;
   }

The above code will check the instance running it to see if the object it is created from is physics enabled, and if it is it activates the physics simulation for the instance.

Back: Objects
Next: object_is_ancestor

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_get_solid

Returns whether an object has solid flagged as true or not.

Syntax:

object_get_solid(obj);

Argument | Description
obj | The index of the object to check.

Returns: Boolean

Description

This function will tell you whether the object you are checking has been flagged as "solid" or not. A solid object generates a special collision event when using the traditional collision system (ie: the physics world is off). Please note that this is not an instance function! So, you can have a solid object and a normal instance of the same object and vice-versa. You can set an individual instances solid flag using the solid instance variable.

Example:

if !solid && object_get_solid(object_index) solid=true;

The above code will check the instance running it to see if it is solid or not as well as check the object index of the instance to see if it is flagged as solid or not. If the instance is not solid yet the object index is flagged as solid, it will set "solid" to true for that instance.

Back: Objects
Next: obj_get_sprite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_get_sprite

Returns the sprite_index of the specified object.

Syntax:

object_get_sprite(obj);

Argument | Description
obj | The index of the object to check

Returns: real

Description

This function will tell you whether the object you are checking has a sprite or not, and if it does then it will return the index of that sprite, or -1 if it does not. Please note that this is not an instance function! You can have an object with no sprite while an instance of that same object can have one and vice-versa, or they can even have different sprites. You can set an individual instances sprite using the sprite_index instance variable.

Example:

if sprite_index != object_get_sprite(object_index) sprite_index = object_get_sprite(object_index);

The above example will check the sprite index of the instance against the sprite of the object_index of the instance. If they are not the same, then it will assign the same sprite as that of the object index to the instance.

Back: Objects
Next: obj_get_visible

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_get_visible

Returns whether an object is flagged as visible or not.

Syntax:

object_get_visible(obj);

Argument | Description
obj | The index of the object to check.

Returns: Boolean

Description

This function will tell you whether the object you are checking has been flagged as "visible" (runs its draw event) or not (does not run its draw event). Please note that this is not an instance function! So, you can have a visible object and an invisible instance of the same object and vice-versa. You can set an individual instances visibility using the visible instance variable.

Example:

if !visible && object_get_visible(object_index) visible=true;

The above code will check the instance running it to see if it is visible or not as well as check the object index of the instance to see if it is flagged as visible or not. If the instance is not visible yet the object index is flagged as on, it will set "visible" to true for that instance.

Back: Objects
Next: object_get_physics

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_is_ancestor

Returns whether an object is the parent of another.

Syntax:

object_is_ancestor(obj, par);

Argument | Description
obj | The object that is being checked as the child.
par | The object that is being checked as the ancestor (parent).

Returns: Boolean

Description

This function can be used to check an object and see if it is an ancestor or not of another object. So, both arguments need to be object indices and not the instance ids, and the first one is always the object that you want to find out if it is a child of the second argument, which is always the object that want to check as the ancestor (parent).

Example:

if object_is_ancestor(object_index, obj_Enemy)
{
instance_destroy();
}

The above code checks to see if the instance running the code is a child of the object "obj_Enemy", and if so it is destroyed.

Back: Objects
Next: object_set_depth

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_set_depth

Sets the depth of the given object.

Syntax:

object_set_depth(index, depth);

Argument | Description
index | The index of the object to change.
vis | The new depth of the object.

Returns: N/A

Description

With this function you can set the depth of a specific object. This means that all instances of this object that are created after the depth has been changed will be created at this new depth, while instances that are already in the room may not be affected.

Please note that this is not an instance function! You can set the depth of individual instances using the depth variable and so have ten instances all with different depths even though the object in question has the depth set to another value in the IDE, and even if you change the depth of the object to something else using this function, all instances that currently in the room will remain as they were, and only instances created after calling the function will start with the new depth.

Example:

if !instance_exists(obj_Bonus) object_set_depth(obj_Bonus, 10000);

The above code checks to see if an instance of "obj_Bonus" exists and if it does not then the object depth is changed.

Back: Objects
Next: object_set_mask

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_set_mask

Sets the mask index of the given object.

Syntax:

object_set_mask(index, spr);

Argument | Description
index | The index of the object to change.
spr | The new sprite to use as the object's mask.

Returns: N/A

Description

With this function you can set the mask_index of a specific object (for more information on masks see Defining Objects). This means that all instances of this object that are created after the mask has been changed will be created with this new mask, while instances that are already in the room may not be affected. You can set this to -1 to remove a mask sprite and so default to the mask defined for the sprite of the object (or no masks if no sprite has been chosen).

Please note that this is not an instance function! You can set the mask index of individual instances using the mask_index variable and so have ten instances all with a different mask to the object they are created from, and even if you change the mask index of the object using this function, all instances that are currently in the room will remain as they were, and only instances created after calling the function will start with the new mask.

Example:

if global.level=10 object_set_mask(obj_Platform, spr_mask_10);

The above code checks the value of global variable and then changes the mask index of the object "obj_Platform" if it is equal to ten.

Back: Objects
Next: object_set_persistent

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_set_persistent

Sets the persistence of the given object.

Syntax:

object_set_persistent(index, pers);

Argument | Description
index | The index of the object to change.
pers | Whether the object should be flagged as persistent (true) or not (false).

Returns: N/A

Description

With this function you can set the persistence of a specific object. A persistent object is "carried over" from room to room and maintains its properties at all times (for more information on persistence see Defining Objects). Setting the persistence of the object means that all instances of this object that are created after the persistence has been changed will be created persistent, while instances that are already in the room may not be affected.

Please note that this is not an instance function! You can set the persistent flag of individual instances using the persistent variable and so have ten instances all flagged as persistent even though the object in question has the flag set to false in the IDE, and even if you change the persistent flag of the object to true using this function, all instances that currently in the room will remain as they were, and only instances created after calling the function will start with persistent flagged as true.

Example:

if room == rm_final object_set_persistent(obj_Player, 0); instance_create(32, 32, obj_Player);

The above code checks to see in which room the instance is currently in and if it is in the specified "rm_final" then it sets the persistence of the object "obj_Player" to false and then creates the instance.

Back: Objects
Next: object_set_solid

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_set_solid

Sets the solidity of the given object.

Syntax:

object_set_solid( index, solid );

Argument | Description
index | The index of the object to change.
solid | The new solidity of the object (true=solid, false=not solid).

Returns: N/A

Description

With this function you can flag a specific object as being solid or not (for more information on the "solid" flag see Defining Objects). This means that all instances of this object that are created after solid has been changed will be created with this new state, while instances that are already in the room may not be affected.

Please note that this is not an instance function! You can set the solid flag of individual instances using the solid variable and so have ten instances all flagged as solid even though the object in question has the flag set to false in the IDE, and even if you change the solid flag of the object to true using this function, all instances that currently in the room will remain as they were, and only instances created after calling the function will start with solid flagged as true.

Example:

if !object_get_solid(obj_Block) object_set_solid(obj_Block, true);

The above code checks the solid flag of the object "obj_Block" and if it is false then it is changed to be flagged as true.

Back: Objects
Next: object_set_sprite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_set_sprite

Sets the sprite of the given object.

Syntax:

object_set_sprite( index, spr );

Argument | Description
index | The index of the object to change.
spr | The sprite to assign to the object.

Returns: N/A

Description

With this function you can set the sprite index of a specific object. This means that all instances of this object that are created after the sprite_index has been changed will be created with this new sprite_index, while instances that are already in the room may not be affected.

Please note that this is not an instance function! You can set the sprite index of individual instances using the sprite_index variable and so have ten instances all with a different sprite to the object they are created from, and even if you change the sprite index of the object using this function, all instances that are currently in the room will remain as they were, and only instances created after calling the function will start with the new sprite.

Example:

switch (room)
{
case rm_start: object_set_sprite(obj_Player, spr_uniform); break;
case rm_middle: object_set_sprite(obj_Player, spr_swimsuit); break;
case rm_end: object_set_sprite(obj_Player, spr_casual); break;
}
instance_create(32, 32, obj_Player);

The above code will set the object "obj_Player" sprite index to different values depending on the room that the instance running the code is currently in. It then creates an instance of "obj_Player".

Back: Objects
Next: object_set_visible

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


object_set_visible

Sets the visibility of the given object.

Syntax:

object_set_visible( index, vis );

Argument | Description
index | The index of the object to change.
vis | The new visibility of the object (true=visible, false=invisible).

Returns: N/A

Description

With this function you can flag a specific object as being visible or not (for more information on the "visible" flag see Defining Objects). This means that all instances of this object that are created after visible has been changed will be created with this new state, while instances that are already in the room may not be affected.

Please note that this is not an instance function! You can set the visible flag of individual instances using the visible variable and so have ten instances all flagged as visible even though the object in question has the flag set to false in the IDE, and even if you change the visible flag of the object to true using this function, all instances that currently in the room will remain as they were, and only instances created after calling the function will start with visible flagged as true.

Example:

if !object_get_visible(obj_Block) object_set_visible(obj_Block, true);

The above code checks the visible flag of the object "obj_Block" and if it is false then it is changed to be flagged as true.

Back: Objects
Next: object_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Generating Events

This function lists the functions available to manipulate object events.

As you know, GameMaker is completely event driven, and that all actions happen as the result of certain events that are triggered in a specific order or by a specific occurrence within the game. There are a number of different events, each one with a specific task or timing and some of them are even split into separate "sub" events. Normally these events are run by GameMaker: Studio when it detects an in-game trigger, or every game tick (as is the case with the step and draw events), but you can also apply an event to an instance in the current room from within a piece of code.

The following functions exist that deal with generating events:

  1. event_inherited
  2. event_perform
  3. event_perform_object
  4. event_user

There are also a number of read only variables that can be used with the functions listed above which are particularly useful for debugging:

  1. event_action
  2. event_number
  3. event_object
  4. event_type

Back: Objects

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


event_action

The index of the action that is currently being executed.

Syntax:

event_action;

Returns: Real

Description

This read-only variable returned the index of the action currently being executed, starting at 0 on previous versions of GameMaker. However, this is now an obsolete function in GameMaker: Studio. It has been left in for legacy support only, and will always return 0 as all actions are concatenated together to improve execution speed.

Example:

num = event_action;

The above code stores the current action number in the variable "num".

Back: Generating Events
Next: event_number

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


event_inherited

Performs the inherited event.

Syntax:

event_inherited();

Returns: N/A.

Description

This function will call the current event of the parent object of the instance. Normally, when an instance has a parent object, it automatically inherits all the same events as the parent, but if (for example) your parent object has a create event and you add one to your child object, all instances of the child object will run the new create event that you have added and not that which is in the parent object. Should you need to use both the parent object event and the child object event of the same type, you should use this function as it will run the parent object event before continuing with the rest of the code or actions that the child event contains

Example:

event_inherited();
switch (sprite_index)
{
case spr_Enemy_1: dmg += 2; break;
case spr_Enemy_4: dmg -= 1; break;
case spr_Enemy_10: dmg +=10; break;
}

The above code calls the inherited parent event (in which we set the variable "dmg" and the sprite index) and then goes on to modify the "dmg" variable. If there is no parent specified for the instance running this code, we would get an "unknown variable" error as dmg has not been defined.

Back: Generating Events
Next: event_perform

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


event_number

Returns the number of event currently being executed.

Syntax:

event_number;

Returns: Real

Description

This read-only variable returns the number of the event currently being called, where the number is actually referring to the "sub event" of the event, ie: for the step event the event number could be any one of the constants ev_step_normal, ev_step_begin, or ev_step_end. For a full list of constants that are available for the specific sub-events see event_perform, and if you should need to know the main event itself, you should be checking the event_type.

Example:

switch (event_number)
{
case ev_step_normal: show_debug_message("Step event!"); break;
case ev_game_start: show_debug_message("Game Start""); break;
case ev_room_start: show_debug_message("Room Start!"); break;
}

The above code could be called form a script and used to show debug messages informing you which event is being currently triggered.

Back: Generating Events
Next: event_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


event_object

The object index for which the current event is being executed.

Syntax:

event_object;

Returns: Real

Description

This read-only variable returns object index of the instance which is running the event being checked.

Example:

global.obj = event_object;

The above code stores the object index of the instance performing the event in a global variable.

Back: Generating Events
Next: event_type

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


event_perform

Performs a given event of the calling instance.

Syntax:

event_perform(type, numb);

Argument | Description
type | The type of event to perform. See below.
numb | The specific event constant or value, if one is necessary (otherwise, just use 0).

Returns: N/A

Description

This function will perform the specified event, with the designated argument, for the instance running the code. There are many options here which allow complete simulation of all possible events, but note that this literally just performs all the code in the event and the game will not modify anything to make it trigger itself manually, for example if you choose to perform a keyboard press event, the event will be triggered but relevant key will not be recognised as having been pressed. Or if you perform an alarm event, the alarm counter will not be set to -1 but rather continue to count down.

Constants

The table below outlines all the constants that are included in GameMaker: Studio for referencing event types, as well as their number value. The events themselves are marked in bold text and are the same as the return values of the event_type variable, while their number values are marked with italic text and these are the same as the return values for the event_number variable:

Name | Description
ev_create | Create event.
ev_destroy | Destroy event
ev_step | Step event
---- ev_step_normal | Step
---- ev_step_begin | Begin Step
---- ev_step_end | End Step
ev_alarm | Alarm event
---- 0 ... 11 | The number relevant to which of the 12 alarms you wish to trigger the event of
ev_keyboard, ev_keypress, ev_keyrelease | Keyboard/Keyboard Pressed/Keyboard Released
---- any key code | vk_space or ord('W') for example.
ev_mouse | Mouse event
---- ev_left_button | Left button held down on object
---- ev_right_button | Right button held down on object
---- ev_middle_button | Middle button (or clickable wheel) held down on object
---- ev_no_button | No buttons held down
---- ev_left_press | Left button just pressed on object
---- ev_right_press | Right button just pressed on object
---- ev_middle_press | Middle button (or clickable wheel) just pressed on object
---- ev_left_release | Left button just released on object
---- ev_right_release | Right button just released on object
---- ev_middle_release | Middle button just released on object
---- ev_mouse_enter | Mouse just entered object's bounding box
---- ev_mouse_leave | Mouse just left object's bounding box
---- ev_mouse_wheel_up | Mouse wheel scrolled upwards
---- ev_mouse_wheel_down | Mouse wheel scrolled downwards
---- ev_global_left_button | Left button held down anywhere
---- ev_global_right_button | Right button held down anywhere
---- ev_global_middle_button | Middle button (or clickable wheel) held down anywhere
---- ev_global_left_press | Left button just pressed anywhere
---- ev_global_right_press | Right button just pressed anywhere
---- ev_global_middle_press | Middle button (or clickable wheel) just pressed anywhere
---- ev_global_left_release | Left button just released anywhere
---- ev_global_right_release | Right button just released anywhere
---- ev_global_middle_release | Middle button just released anywhere
ev_collision | Collision with an object
---- The index of the object to check. | object1 for example.
ev_other | One of the actions listed under 'Other'
---- ev_outside | Whether the instance is outside of the room
---- ev_boundary | Whether the instance is intersecting the boundary
---- ev_game_start | Only triggered at the start of the game
---- ev_game_end | Only triggered at the end of the game
---- ev_room_start | Only triggered at the start of a room
---- ev_room_end | Only triggered at the end of a room
---- ev_no_more_lives | If all lives are depleted (if lives==0)
---- ev_no_more_health | If all health is depleted (if health==0)
---- ev_animation_end | If the object's sprite has reached the end of its animation
---- ev_end_of_path | If the object has reached the end of a path it is following
---- ev_close_button | If the window's Close button has been pushed
---- ev_user0... ev_user15 | One of the 16 available user events.
ev_draw | Draw event. NOTE: This event cannot be forced outside of a draw event and the constants and the constants are only for identifying the event when performed in these cases.
---- ev_draw_begin | The draw begin event.
---- ev_draw_end | The draw end event.
---- ev_draw_pre | The pre draw event.
---- ev_draw_post | The post draw event.
---- ev_gui | The draw gui event.
---- ev_gui_begin | The draw gui begin event.
---- ev_gui_end | The draw gui end event.

Extended Example

To help understand how this function can be use, please look at the following few examples:

event_perform(ev_keypress, ord("W"));

This would perform the event associated with Keyboard Check Pressed "W" key (without actually generating a keyboard press).

event_perform(ev_step, ev_step_begin);

This would perform the Begin Step event (if called from any of the step events it would cause the begin step event code to be run twice).

event_perform(ev_create, 0);

This would perform the Create event of the instance.

Back: Generating Events
Next: event_perform_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


event_perform_object

Performs a given event of the specified object.

Syntax:

event_perform_object(obj, type, numb);

Argument | Description
obj | The object that should have its event triggered.
type | The type of event to perform. See below.
numb | The specific event, if one is necessary (otherwise, just use 0).

Returns: N/A

Description

This functions works the same as event_perform() except that this time you can specify events from another object. There are many options here which allow complete simulation of all possible events, but note that this literally just performs all the code in the event and the game will not modify anything to make it trigger itself manually, for example if you choose to perform a keyboard press event, the event will be triggered but the relevant key will not be recognised as having been pressed. Or if you perform an alarm event, the alarm counter will not be set to -1 but rather continue to count down. You can find a complete list of the available constants this function requires from the the page for the function event_perform.

NOTE: Actions in the event called with this function are applied to the current instance, and not to instances of the given object.

Example

event_perform_object(obj_Player, ev_keypress, ord("W"));

This would perform the event associated with Keyboard Check Pressed > W key from the object "obj_Player" in the current instance.

Back: Generating Events
Next: event_user

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


event_type

Returns the type of event currently being executed.

Syntax:

event_type;

Returns: Real

Description

This read-only variable returns the type of event currently being executed, which can be one of the following constants:

  • ev_create
  • ev_destroy
  • ev_step
  • ev_alarm
  • ev_keyboard
  • ev_keypress
  • ev_keyrelease
  • ev_mouse
  • ev_collision
  • ev_other
  • ev_draw

For a full list of the constants that are related to the different events see event_perform, and if you should need the event number (ie: the sub event), you should be checking the event_number.

Example:

show_debug_message("Current Event = " + string(event_type))

The above code will show a debug message with the event type currently being performed.

Back: Generating Events
Next: event_action

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


event_user

Calls one of the 16 user-defined events.

Syntax:

event_user(numb);

Argument | Description
numb | The number of event to call, between 0 and 15.

Returns: N/A

Description

With this function you tell the instance to run the actions or code that has been placed within one of the 16 user defined events. These events can only be called in this way, or using the event_perform function.

Example:

event_user(4);

This would call User Defined Event 4.

Back: Generating Events
Next: event_inherited

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Operating Systems

These functions are provided to help find details about the current OS your game is running on.

When creating cross-platform games, it is often of vital importance that you get the details of the operating system that the device running your game is using. Things like the language, the version or the network state can all be used to adapt your game to the system running it and make the end-user experience the best possible, so GameMaker: Studio has a number of special functions which can be used to get the necessary information.

The following functions exist for you to use to get certain details about the operating system or browser that is running your game:

  1. os_browser
  2. os_device
  3. os_type
  4. os_version
  5. os_is_paused
  6. os_is_network_connected
  7. os_get_config
  8. os_get_language
  9. os_get_region
  10. os_get_info
  11. os_powersave_enable
  12. os_lock_orientation

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_browser

This variable holds a different constant depending on the browser the game is currently being run in.

Syntax:

os_browser

Returns: Constant

Description

This variable holds one of various constant GameMaker: Studio has to tell you which browser you are currently running the game in (if any). The following constants can be returned:

Constant | Description
browser_not_a_browser | Game is not being played in a browser
browser_unknown | Unknown browser
browser_ie | Internet Explorer
browser_firefox | Mozilla Firefox
browser_chrome | Google Chrome
browser_safari | Safari
browser_opera | Opera
browser_safari_mobile | Safari Mobile
browser_windows_store | Windows UWP App

Example:

if os_browser == browser_not_a_browser
{
global.Config = 0;
}
else
{
global.Config = 1;
}

The above code checks to see if the game is running in a browser or not and sets a global variable to a value depending on the result of the check.

Back: Operating Systems
Next: os_device

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_device

This variable holds a different constant depending on the device the game is currently being run in.

Syntax:

os_device

Returns: Constant

Description

This variable holds one of various constant GameMaker: Studio has to tell you which device you are currently running the game on. The following constants can be returned:

Constant | Description
device_ios_ipad | iPad
device_ios_ipad_retina | Newer iPad with Retina display size of 2048 x 1536
device_ios_iphone6 | iPhone6 with display size 1334 x 750
device_ios_iphone6plus | Larger iPhone 6 with display 1920 x 1080
device_ios_iphone5 | iPhone5 with display size 640 x 1136)
device_ios_iphone | Older iPhone/iPod Touch (480 x 320 screen) or Android phone
device_ios_iphone_retina | Newer iPhone/iPod Touch with Retina display of 960 x 640
device_emulator | The device is actually an emulator (Windows Phone or Android)
device_tablet | Android tablet
device_ios_unknown | Unknown or not iOS

Example:

if os_browser = browser_not_a_browser
{
switch (os_device)
{
case device_ios_ipad: global.Config = 2; break;
case device_ios_iphone: global.Config = 3; break;
case device_ios_iphone_retina: global.Config = 4; break;
case device_ios_unknown: global.Config = 5; break;
}
}
else
{
global.Config = 1;
}

The above code checks to see if the game is running in a browser or not and sets a global variable to a value depending on the result of the check.

Back: Operating Systems
Next: os_type

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_get_config

Returns the name of the current configuration.

Syntax:

os_get_config()

Returns: String

Description

This function returns the name (as a string) of the currently selected configuration for your game. For more information on configurations please see the section Advanced Use: Configurations.

NOTE: Configurations are only available in the Professional Version of GameMaker: Studio.

Example:

if os_get_config() = "Free_Version"
{
ads_enable((room_width / 2) - 100, 0, 200, 75, 60);
}

The above code will check to see which configuration is being used and if it is the one called "Free_Version", ads will be enabled in the game.

Back: Operating Systems
Next: os_get_language

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_get_info

Returns a ds_map with information about the OS.

Syntax:

os_get_info()

Returns: Real (ds_map index)

Description

This function returns a ds_map with detailed information about the OS that the game is running on. The exact information returned will depend on the OS and the device. Note that the ds_map is not automatically cleared from memory and you should use the ds_map_destroy() function when you no longer need the data it contains.

NOTE: This function only works on Android, iOS, Mac, Ubuntu and Windows, on all other target platforms it will return -1 rather than a ds_map.

Example:

os_map = os_get_info();
if os_map != -1
{
var size, key, i;
size = ds_map_size(os_map);
key = ds_map_find_first(os_map);
for (i = 0; i < size - 1; i++;)
{
map_data[i] = ds_map_find_value(os_map, key);
key = ds_map_find_next(os_map, key);
}
ds_map_destroy(os_map);
}

The above code will check the OS information to see if a ds_map is returned. If it is, then the code will loop through the map and assign all the values to an array.

Back: Operating Systems
Next: os_powersave_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_get_language

This function returns a different value depending on the browser or device language.

Syntax:

os_get_language()

Returns: String

Description

This function returns a string with the two letter Language Code for the OS that is running the game, as set by the ISO639 standard. If the information is not available, it will hold simply an empty string "", or "en" for "English" language. Note that some languages also have a relevant Regional Code too, so to distinguish between different regions of the same country use the function os_get_region().

The following table shows some of the main two letter language codes as defined by ISO 639:

Language | Code
Arabic | ar
Chinese | zh
Danish | da
English | en
French | fr
German | de
Greek | el
Italian | it
Japanese | ja
Norwegian | no
Polish | pl
Portuguese | pt
Russian | ru
Spanish | es
Swedish | sv

NOTE: This is not the location country code that is returned, but the language code of the OS!

Example:

switch (os_get_language())
{
case "es": ini_open("spanish.ini"); break;
case "fr": ini_open("french.ini"); break;
case "it": ini_open("italian.ini"); break;
default: ini_open("english.ini"); break;
}

The above code checks the OS language and opens a different *.ini file depending on the returned value.

Back: Operating Systems
Next: os_get_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_get_region

This function returns a different value depending on the browser or device language region.

Syntax:

os_get_region()

Returns: String

Description

This function returns a string with the two or three letter Regional Code for the OS that is running the game, as set by the ISO3166-1 standard. If the information is not available, it will hold simply an empty string "".

NOTE: This is not the location regional code that is returned, but the regional language code of the OS.

Example:

switch (os_get_language())
{
case "zh":
var region = os_get_region();
if (region == "HK" || region == "MO" || region == "TW")
{
ini_open("chinese_traditional.ini");
}
else
{
ini_open("chinese_simplified.ini");
}
break;
case "fr":
ini_open("french.ini");
break;
case "it":
ini_open("italian.ini");
break;
default:
ini_open("english.ini");
break;
}

The above code checks the OS language and if it is Chinese, it then checks the OS region, opening a different *.ini file depending on the returned values.

Back: Operating Systems
Next: os_get_info

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_is_network_connected

Checks to see if the device has an internet connection or not.

Syntax:

os_is_network_connected()

Returns: Boolean

Description

With this function you can check and see if your device currently has an internet connection and it will return true if it does, or false if it does not.

NOTE: This function checks the internal device API that controls connections and so may return true if there is a bluetooth connection, a Wi-Fi connection, or even just a normal network connection that permits internet access.

Example:

if os_is_network_connected()
{
facebook_init();
}

The above code checks to see if the device has a connection to the internet and if so initialises the GameMaker: Studio Facebook API.

Back: Operating Systems
Next: os_get_config

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_is_paused

Checks to see if the device OS is paused or not.

Syntax:

os_is_paused()

Returns: Boolean

Description

When developing for mobile devices, you need to have a way to check that the device is still focused on your game or not, especially as if your game is on an iOS or Android device then it can be interrupted by phone calls and other apps. You can use this function to check if the device is paused or not.

It is worth noting that this function will run any code that is contained within the code block on devices but then GameMaker: Studio will be paused immediately after as the device caches the game as a background process. So if you have something like the example code provided below, the instance to be created will not actually appear or run any of its events until after the game has been restarted from the cached state. This means that you may prefer to have the os_is_paused function call an alarm and then in the alarm event (which will be set when the device is paused but not run until it is un-paused) create a pause menu, restart music etc...

If you are using this function on Windows, Ubuntu (Linux), MacOSX or HTML5 platforms, then the function is only toggled for one step to true when the game loses focus, and then it will return false again until the game is returned to focus (and loses it again). This is because these platforms do not cache apps and games, and so these will continue to run in the background.

NOTE: On mobile devices, sounds and music will be stopped when the os is paused. They will not restart again unless you specifically start them with the appropriate function.

Example:

if os_is_paused()
{
if !instance_exists(obj_PauseMenu) instance_create(0,0,obj_PauseMenu);
}

The above code checks to see if the game has been paused, and if it has then it creates an instance of the object "obj_PauseMenu" if none exist already.

Back: Operating Systems
Next: os_is_network_connected

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_lock_orientation

This function locks the game orientation to the device's current orientation.

Syntax:

os_lock_orientation(flag)

Argument | Description
flag | Set to true or false to enable or disable orientation locking.

Returns: N/A

Description

With this function you can "lock" your device to the current orientation until such time as you "free" it to allow all Global Game Settings enabled orientations again. Note that you likely want to confirm the orientation is as desired before locking.

Example:

if os_type == os_android || os_type == os_ios
{
os_lock_orientation(true);
}

The above code checks the OS type and if it is either Android or an iOS then the orientation locking is flagged as true.

Back: Operating Systems
Next: os_browser

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_powersave_enable

Set the powersave functions of the device.

Syntax:

os_powersave_enable(flag)

Argument | Description
flag | Set to true or false to enable or disable powersave functions.

Returns: N/A

Description

With this function you can turn on or off the power saving features of the device. This is important as certain games (for example those that use the tilt functions) may not generate events that the OS can interpret as being user input and so shut down the screen or exit the game. By setting this function to false you can disable the power saving features and ensure that the screen (and game) are always functioning.

NOTE: This is limited to iOS and Android targets.

Example:

if os_type == os_android || os_type == os_ios
{
os_powersave_enable(false);
}

The above code checks the OS type and if it is either Android or an iOS then power saving features are deactivated.

Back: Operating Systems
Next: os_lock_orientation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_type

This variable holds a different constant depending on the operating system the game is currently being run with.

Syntax:

os_type;

Returns: Constant

Description

This variable holds one of various constant GameMaker: Studio has to tell you which operating system the game has been created for. Note that this is not necessarily the same as the OS of the device running it, since - for example - your game could be running on an Amazon Fire OS, but will have been built for the Android platform (in which case os_type will be os_android).

The following constants can be returned:

Constant | Description
os_windows | Windows OS (NOTE: this replaces the deprecated os_win32 constant)
os_uwp | Windows 10 Universal Windows Platform
os_linux | Linux
os_macosx | Mac OS X
os_ios | iOS (iPhone, iPad, iPod Touch)
os_android | Android
os_ps3 | Sony PlayStation 3
os_ps4 | Sony PlayStation 4
os_psvita | Sony PlayStation Vita
os_xboxone | Microsoft XBox One
os_unknown | unknown OS

Example:

switch (os_type)
{
case os_windows: global.Config = 0; break;
case os_android: global.Config = 1; break;
case os_linux: global.Config = 2; break;
case os_macosx: global.Config = 3; break;
case os_ios: global.Config = 4; break;
}

The above code checks the OS running the game and sets a global variable accordingly.

Back: Operating Systems
Next: os_version

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


os_version

This variable holds the version number of the OS that is running the game.

Syntax:

os_version

Returns: Real

Description

This variable will tell you the version number for the OS that is running your game. For example, if you are running it on an iPad with iOS 4 installed, os_version will be equal to 83890177.

The following table outlines the values that are returned:

Operating System | Version Name (version Number) | Return Value
Android | Cupcake (1.5) Donut (1.6) Eclair (2.0) Eclair (2.0.1) Eclair (2.1) Froyo (2.2.x) Gingerbread (2.3 - 2.3.2) Gingerbread (2.3.3 - 2.3.7) Honeycomb (3.0) Honeycomb (3.1) Honeycomb (3.2.x) Ice Cream Sandwich (4.0.1 - 4.0.2) Ice Cream Sandwich (4.0.3 - 4.0.4) Jelly Bean (4.1.x) Jelly Bean (4.2.x) Jelly Bean (4.3.x) KitKat (4.4.x) Lollipop (5.0 - 5.1.1) Marshmallow (6.0 - 6.0.1) Nougat (7.0 - 7.11) | 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 21 - 22 23 24 - 25
iOS The return value is calculated as: (major_version * 16777216) + (minor_version * 4096) + build_number | iOS 3 (3.1.3) iOS 4 (4.2.1) iOS 5 (5.1.1) iOS 6 (6.0.1) iOS 6 (6.0.2) iOS 6 (6.1) iOS 7 (7.0.4) iOS 7 (7.1) iOS 8 (8.0) iOS 8 (8.1) iOS 8 (8.2) iOS 8 (8.3) iOS 8 (8.4) iOS 8 (8.4.1) iOS 9 (9.0) iOS 9 (9.0.1) iOS 9 (9.0.2) iOS 9 (9.1) iOS 9 (9.2) iOS 9 (9.2.1) iOS 9 (9.3) iOS 10 (10.0) iOS 10 (10.1) iOS 10 (10.2) | 50335747 67117057 83890177 100663297 100663298 100667392 117440516 117444608 134217728 134221824 134225920 134230016 134234112 134234113 150994944 150994945 150994946 150999040 151003136 151003137 151007232 167772160 167776256 167780352
Mac OS X The return value is calculated as: (major_version * 16777216) + (minor_version * 4096) + build_number | Cheetah (10.0.4) Puma (10.1.5) Jaguar (10.2.8) Panther (10.3.9) Tiger (10.4.11) Leopard (10.5.8) Snow Leopard (10.6.8) Lion (10.7.5) Mountain Lion (10.8.2) Mavericks (10.9.1) Yosemite (10.10) El Capitan (10.11) Sierra (10.12) | 167772164 167776261 167780360 167784457 167788555 167792648 167796744 167800837 167804930 167809025 167813120 167817216 167821312
Windows (the return value is calculated as: majorVersion * 65536 + minorVersion) | Windows 2000 (5.0) Windows XP (5.1) Windows XP 64-Bit Edition (5.2) Windows Server 2003 (5.2) Windows Server 2003 R2 (5.2) Windows Vista (6.0) Windows Server 2008 (6.0) Windows Server 2008 R2 (6.1) Windows 7 (6.1) Windows Server 2012 (6.2) Windows 8 (6.2) Windows 8.1 (6.3) Windows 10 (10.0) | 327680 327681 327682 327682 327682 393216 393216 393217 393217 393218 393218 393219 655360
Windows Phone The return value is calculated as: majorVersion * 65536 + minorVersion | Windows Phone 7 (7.0) Windows Phone 7.5 (7.1) Windows Phone 8 (8.0) | 458752 458753 524288

NOTE: Should you require further information about the Windows OS you can use the environment_get_variable.

Example:

if os_type = os_android && os_version >10 global.GFX = 1;

The above code checks the os type and version number and they are both correct then the global variable is set to 1.

Back: Operating Systems
Next: os_is_paused

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Particles

This section deals with the use of particles to create cheap graphic effects.

For complex things in GameMaker: Studio you would normally have an object and create instances of that object around the room. However, for graphics effects, this can be expensive as every instance comes with a "cost" in processing due to the variables it contains and the codes it has in the different events. You can reduce this cost by turning to tiles for drawing your graphics needs but those are generally static and cannot easily be changed or moved. However, there is one other option for drawing fast yet versatile graphics effects in your games, and that is to use particles.

What are particles?

Particles are graphic resources that have certain properties which are defined within a particle system. These properties cannot be manipulated directly for individual particles, but are changed through the code that is used to define the individual particle and the system that it belongs to. They are very useful for creating beautiful and flashy effects (or subtle and discreet ones!) like explosions, decals, rain, snow, star fields and debris in a game without the CPU overhead that using instances has.

The basic setup for a particle system follows three steps, with the third step being optional depending on how you wish to create your particle effects within the room:

  • Create a particle system: The particle system is like a container that we will use to hold our different particle types ready for use. We use code to define a series of visual aspects and behaviours for our particles, and then we place them in the "container" so that we can take them out and use them whenever and wherever we need later.

  • Create particle types: Particle types are the graphic effect itself. You can have many different types, each with their own range of colours, alphas, sizes and movements, but its important to note that you do not have control over individual particles. You define a series of parameters and the particle will be created to have a random spread of behaviours chosen from them.

  • Create emitters: Emitters are an option that can be used to burst or stream particles from within very clearly defined limits. They are optional because you can create particles from any instance using the part_particles_create and part_particles_create_colour functions but they are not always adequate for every situation.

Limitations

Although particles are an excellent tool for creating effects, they do come with certain restrictions and good practices which need to be followed unless you want your game to grind to halt and eventually crash:

  • Particle systems, particles and emitters take up memory and as such you should be very careful how you use them as it is very easy to cause a memory leak which will slow down and eventually crash your game. One way to cope with this is to have a global system with everything defined at the start of the game and removed at the end, but if you want a dynamic system then each particle and emitter (and the system itself) should be destroyed the moment it is not needed.

  • Particles may be fast and light on the CPU, but they still require some processing and so you shouldn't have 40,000 of them bursting across the screen at a time. Limit them to those that are necessary to achieve a specific effect and no more.

  • If you define your own particle sprite instead of using one of the 14 included sprites, you should try to keep them as small as possible to achieve the effect you require.

  • Particles do not interact with anything. Should you need them to have any type of interaction with the user or any other instances in your game, you should be looking at using instances instead as particles are purely graphic.

  • Even though there is no technical limit to the amount of systems, emitters and particles you can create in one game, you should try and limit everything to the minimum number possible to keep memory use as low as possible.

  • On mobile devices, take care with particles as drawing them can be slow if they cover a large area of the screen (over-draw on mobile devices is one of the main causes of slowdown).

  • With HTML5 there is no additive blending, and unless you have WebGL enabled, you cannot have colour blending either.

The following sections cover all aspects of coding your own particle systems:

  1. Simple Effects
  2. Particle Systems
  3. Particle Types
  4. Particle Emitters

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Particle Emitters

This section deals with particle emitters.

Emitters are used by GameMaker: Studio to emit particles over an area of the screen which can have different forms and distributions. They can also either create a continuous stream of particles or they can burst out a number of particles all at once, depending on the way the functions are used.

Since a particle emitter is a dynamically created resource, you must create it and store the returned index in a variable to reference the emitter in all further function calls, and it is very important that you also destroy the emitter when it is no longer needed or else you will have a memory leak that will slow down and eventually crash your game. It is also worth noting that particle emitters will live on forever after they are created, even if the index is no longer stored. So even if you change room or restart the game, the systems and the particles will remain, and be visible, in all further rooms so you better make sure you destroy them once you no longer need them.

The following functions are available to set the emitters and to let them create particles. Note that each of them gets the index of the particle system to which it belongs as a first argument.

  1. part_emitter_exists
  2. part_emitter_create
  3. part_emitter_clear
  4. part_emitter_region
  5. part_emitter_burst
  6. part_emitter_stream
  7. part_emitter_destroy
  8. part_emitter_destroy_all

Back: Particles

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_emitter_burst

Bursts particles on one step only from the given emitter.

Syntax:

part_emitter_burst(ps, ind, parttype, number);

Argument | Description
ps | The particle system that the emitter is in.
ind | The index of the emitter to burst from.
parttype | The index (type) of the particles to be created.
number | The number of particles to create.

Returns: N/A

Description

This function allows you to set an emitter to burst a specific type of particle and is typically used in alarms and destroy events as it is a one off code that creates the number of particles specified all at once following the distribution, shape and position set by the function part_emitter_region. Should you need the particles to appear every step, you should be using the function part_emitter_stream rather than calling this function every step.

Example:

part_emitter_burst(global. Sname, p_emit1, p1, 30 + irandom(30));

The above code will burst a random number of particles between 30 and 60 from the chosen emitter.

Back: Particles
Next: part_emitter_stream

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_emitter_clear

Clears the settings of a given emitter.

Syntax:

part_emitter_clear(ps, ind);

Argument | Description
ps | The particle system that the emitter is in.
ind | The index of the emitter to clear.

Returns: N/A

Description

With this function you can clear the given emitter from the specified particle system back to its default state. This will also stop any particles that are being streamed from the emitter at the time, and if you wish to use the emitter again you will need to set the region position and particle type using the part_emitter_region function.

Example:

part_emitter_clear(Sname, p_emit1 );

The above code will clear the particle emitter indexed in the variable "p_emit1".

Back: Particles
Next: part_emitter_region

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_emitter_create

Creates a new emitter in the given particle system.

Syntax:

part_emitter_create(ps);

Argument | Description
ps | The particle system to create the emitter in.

Returns: Real

Description

This function must be used to create a new emitter and assign it to a given particle system. The function will return the index value for the new emitter which must be stored in a variable and used in all further functions that reference the emitter, and the emitter itself must be destroyed when no longer being used to prevent memory leaks (this can be achieved using the specific emitter destroy functions or by destroying the whole particle system that the emitter belongs to).

Example:

p_emit1 = part_emitter_create(Sname);

This will create a new particle emitter and store its index in the variable "p_emit".

Back: Particles
Next: part_emitter_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_emitter_destroy

Destroys a given emitter in the given particle system.

Syntax:

part_emitter_destroy( ps, ind );

Argument | Description
ps | The particle system to destroy the emitter from.
ind | The index of the emitter to destroy.

Returns: N/A

Description

This function will remove the specified emitter from the given system and clear it from memory (this will also stop any particles from being produced by the given emitter, but it does NOT remove them from the room). This function should always be called when the given emitter is no longer needed for the system to prevent memory leaks and errors.

Example:

if part_emitter_exists(global.Sname, p_emit)
{
part_emitter_destroy(global.Sname, p_emit1);
}

The above code will check to see if the particle emitter indexed in the variable "p_emit" exists in the give particle system and if it does it is destroyed.

Back: Particles
Next: part_emitter_destroy_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_emitter_destroy_all

Destroys all emitters in the given particle system.

Syntax:

part_emitter_destroy_all( ps );

Argument | Description
ps | The particle system to destroy all emitters from.

Returns: N/A

Description

This function will remove all defined emitters from the given system and clear them from memory (this will also stop any particles from being produced by the given emitter, but it does NOT remove them from the room). This function should always be called when the emitters are no longer needed for the system to prevent memory leaks and errors.

Example:

if lives = 0
{
part_emitter_destroy_all(global.Sname);
room_goto(rm_Menu);
}

The above code checks the built in global variable "lives" and if it is 0, it destroys all particle emitters and then changes room.

Back: Particles
Next: part_emitter_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_emitter_exists

Checks to see if a given emitter exists in the given particle system.

Syntax:

part_emitter_exists(ps, ind);

Argument | Description
ps | The particle system to check for an emitter.
ind | The index of the emitter to search for.

Returns: Boolean

Description

With this function you can check to see if the given particle emitter indexed exists in the given system or not. Note that if the variable being checked is an uninitialised variable (that a particle emitter would otherwise have its index assigned to) this will throw an error.

Example:

if part_emitter_exists(sname, p_emit1)
{
part_emitter_burst(sname, p_emit1, part_1, 30);
}

The above code will check for the emitter indexed in the variable "permit" and if it exists, it will burst 30 particles from it.

Back: Particles
Next: part_emitter_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_emitter_region

Sets the region and distribution settings for the given emitter.

Syntax:

part_emitter_region(ps, ind, xmin, xmax, ymin, ymax, shape, distribution);

Argument | Description
ps | The particle system that the emitter is in.
ind | The index of the emitter to set.
xmin | The x coordinate of the left side of the region.
xmax | The x coordinate of the right side.
ymin | The y coordinate of the top of the region.
ymax | The y coordinate of the bottom of the region.
shape | The shape of the region.
distribution | The distribution style of the particles.

Returns: N/A

Description

This function is used to set their position of a particle emitter within the current room. You specify the bounding box of the area within the function and then use any of a series of constants to define the final emitter shape within this bounding box as well as the distribution of particles within the shape. The available constants for distribution shapes are listed below:

Constant | Description
ps_shape_rectangle | A rectangular shape that fills the given area.
ps_shape_ellipse | An ellipse, with the width and height defined by the area.
ps_shape_diamond | A diamond shape with the points at half width and half height.
ps_shape_line | A single line, where the start point is the left and top and the end point is the right and bottom.

Apart from the distribution shapes, you can also define the distribution curve for the particles that are to be emitted. The available constants for distribution curves are listed below:

Constant | Description
ps_distr_linear | A Linear distribution where all particles have an equal chance of appearing anywhere in the area.
ps_distr_gaussian | A gaussian distribution where more particles are generated in the center rather than the edges.
ps_distr_invgaussian | An inverse gaussian distribution where more particles are generated at the edges than center.

NOTE: If you need the emitter to move with an instance, you will have to use this function in the step event and update the emitter position that way. It is also worth noting that for point emissions where you do not need to create particles over an area or with a specific distribution, it is often easier to use part_particles_create.

Example:

part_emitter_region(global.Sname , emit_1, x - 50, x + 50, y - 50, y + 50, ps_shape_ellipse, ps_distr_linear)

The above code will set an emitter to the a 100px tall and 100px wide elliptical shape around the current (x,y) position of the instance running the code.

Back: Particles
Next: part_emitter_burst

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_emitter_stream

Streams particles every step from the given emitter.

Syntax:

part_emitter_stream(ps, ind, parttype, number);

Argument | Description
ps | The particle system that the emitter is in.
ind | The index of the emitter to burst from.
parttype | The index (type) of the particles to be created.
number | The number of particles to create per step.

Returns: N/A

Description

This function allows you to set an emitter to stream a specific type of particle and is typically used the create event as it is a one off code that sets the emitter to generate the number of particles specified every step of the game there-after. The particles are emitted following the distribution, shape and position set by the function part_emitter_region. You can set the number of particles being streamed to zero and call this function again to "switch off" the particle streaming, and the function will also accept negative numbers for the amount, in which case the emitter will produce particles based on random chance. For example, if you have the particle number set to -5, there is a 1:5 chance that a particle will be produced every step. Should you need the particles to appear all at once rather than every step, you should be using the function part_emitter_burst.

Example:

part_emitter_stream(global. Sname, p_emit1, p1, 1);

The above code will stream 1 particle every step of the game until the emitter is destroyed or the stream set to 0.

Back: Particles
Next: part_emitter_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Particle Systems

This section deals with setting up, maintaining and destroying particle systems.

Before you can create particles you need to create a particle system. This is a "container" where you place your particles and emitters (if you need them) ready for use, and you can put as many or as few particles into any one system as you think necessary, and you can have as many systems as you think necessary too. However, it is always better to keep this number as small as possible due to the fact that each system, emitter and particle takes up memory and having too many of them may slow your game down or cause problems. For example, if you need some effects to appear above instances, and other effects to appear beneath instances, you would create two systems and set their depths to get the desired effect, with all particles that are added to each system being drawn at the depth you specify.

System Functions

Since a particle system is a dynamically created resource, you must create it and store the returned index in a variable to reference the system in all further function calls, and it is very important that you also destroy the system when it is no longer needed or else you will have a memory leak that will slow down and eventually crash your game. It is also worth noting that particle systems will live on forever after they are created, even if the index is no longer stored. So even if you change room or restart the game, the systems and the particles will remain, and be visible, in all further rooms so you better make sure you destroy them once you no longer need them.

The basic functions for setting up a particle system are listed below:

  1. part_system_exists
  2. part_system_create
  3. part_system_clear
  4. part_system_depth
  5. part_system_position
  6. part_system_destroy
  7. part_particles_clear
  8. part_particles_count

Particle System Drawing

Once particles are added to a particle system and then burst or streamed into the room, they are normally automatically updated each step and drawn based on the parameters that you have used to define them. However it can sometimes be necessary to control when and how the system is updated as well as how the system should be drawn, and for that GameMaker: Studio provides the following functions:

  1. part_system_automatic_update
  2. part_system_automatic_draw
  3. part_system_update
  4. part_system_drawit
  5. part_system_draw_order

Creating Particles Directly

Normally you would use particle emitters to burst or stream particles from an area, but in many cases these are not necessary and it is actually better to just create the particles directly using the following functions:

  1. part_particles_create
  2. part_particles_create_colour

Back: Particles

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_particles_clear

Clears all particles in the system.

Syntax:

part_particles_clear(ind);

Argument | Description
ind | The index of the particle system.

Returns: N/A

Description

With this function you can clear all the particles currently created by the system from the room. It does not reset or remove the particle types themselves, just their visual representation, and if you have any object streaming particles from an emitter, these particles disappear but will begin to appear again the next step after calling this code.

Example:

if lives = 0
{
part_particles_clear(global.Sname);
room_goto(rm_intro);
}

The above code will check the value of the variable "lives" and if it is equal to 0, it clears all particles from the system and then changes room.

Back: Particle Systems
Next: part_particles_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_particles_count

Returns the number of particles presently created in a given system.

Syntax:

part_particles_count(ind);

Argument | Description
ind | The index of the particle system.

Returns: Real

Description

With this function you can check to see if a particle system currently has any particles created in the room, and it will return the number of them too.

Example:

if part_particles_count(Sname) = 0
{
part_system_destroy(Sname);
instance_destroy();
}

The above code will check the number of particles in the local particle system indexed in the variable "Sname" and if there are none, it will destroy the system and then the instance.

Back: Particle Systems
Next: part_system_automatic_update

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_particles_create

Create particles from a system at a given position.

Syntax:

part_particles_create(ind, x, y, parttype, number);

Argument | Description
ind | The index of the particle system.
x | The x coordinate of where to create the particles.
y | The y coordinate of where to create the particles.
parttype | The index (type) of the particles to be created.
number | The number of particles to create.

Returns: N/A

Description

This function is ideal for those effects that do not require any of the functionality offered by particle emitters (for example, to create smoke from a missile, or a simple explosion effect) as it permits you to quickly and easily create particles at any position in the game room. Note that you must have created the particle system and the particle type previously for this function to be used.

Example:

if mouse_check_button(mb_left)
{
part_particles_create(sname, mouse_x, mouse_y, p_CursorEffect, 5);
}

The above code checks for the mouse button being pressed and if it returns true it generates 5 particles at the mouse position.

Back: Particle Systems
Next: part_particles_create_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_particles_create_colour

Create particles from a system at a given position and with a given colour.

Syntax:

part_particles_create_colour(ind, x, y, parttype, colour, number);

Argument | Description
ind | The index of the particle system.
x | The x coordinate of where to create the particles.
y | The y coordinate of where to create the particles.
parttype | The index (type) of the particles to be created.
colour | The colour blending for the particles.
number | The number of particles to create.

Returns: N/A

Description

This function is ideal for those effects that do not require any of the functionality offered by particle emitters (for example, to create smoke from a missile, or a simple explosion effect) as it permits you to quickly and easily create particles at any position in the game room. You can also colour the particles "on the fly" as they are created with this function, and this colour will over-ride the predefined colour of the particle, but it does not blend this colour over the particles lifetime. Note that you must have created the particle system and the particle type previously for this function to be used.

Example:

if speed > 1
{
part_particles_create_colour(sname, x, y, p_MagicSmoke, choose(c_aqua, c_lime, c_fuschia, c_orange), 1);
}

The above code will generate a single particle every step that the instance with the code has a speed greater than one. These particles will be of a random colour.

Back: Particle Systems
Next: part_system_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_automatic_draw

Sets whether or not the particles in the particle system should be automatically drawn or not.

Syntax:

part_system_automatic_draw(ind, automatic);

Argument | Description
ind | The index of the particle system to change.
automatic | Whether automatic drawing is on (true) or not (false).

Returns: N/A

Description

This function can be used to switch off the drawing of a particle system so that any updates done to the system (automatic or otherwise) will not be seen. This is a purely visual option and when set to false you will not be able to see the particles as they are not drawn, but they still exists and are changing position, colour etc... as they would normally. When automatic drawing is off, you can explicitly order GameMaker: Studio to draw the current state of the particle system using the function part_system_drawit, and if you set this function to true again you can switch automatic drawing back on.

One thing to note is that if you are using the simple effects created by the functions effect_create_above or effect_create_below then you can use the values of 0 (for below effects) or 1 (for above effects) as the particle system index and so toggle the automatic draw for these too (this will also work to toggle drawing for the D'n'D particle effects).

Example:

part_system_automatic_draw(global.Sname, false);

The above code switches off automatic drawing for the particle system indexed in the global variable "Sname".

Back: Particle Systems
Next: part_system_update

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_automatic_update

Sets whether or not the particles in the particle system should be automatically updated or not.

Syntax:

part_system_automatic_update(ind, automatic);

Argument | Description
ind | The index of the particle system to change.
automatic | Whether automatic updating is on (true) or not (false).

Returns: N/A

Description

This function controls whether GameMaker: Studio should update the particle system automatically or not, and normally you would not need to use this function as the default value of true (automatic update is on) is what you wish to happen. However, for special effects or for pausing the game, you can set this to false and it will prevent any updates being carried out on the given particle system unless explicitly commanded by the use of the function part_system_update or you use this function again to turn automatic updates on. No updating means that particles created in this system will no longer change position, colour or any other parameter and that emitters will cease to work too, "freezing" the system at the exact point in which the automatic update was set to false.

One thing to note is that if you are using the simple effects created by the functions effect_create_above or effect_create_below then you can use the values of 0 (for below effects) or 1 (for above effects) as the particle system index and so toggle the automatic update for these too (this will also work to toggle updating for the D'n'D particle effects).

Example:

if global.Pause
{
part_system_automatic_update(global.Sname, false);
}

The above code will switch off the particle updates if the global variable "Paused" is true.

Back: Particle Systems
Next: part_system_automatic_draw

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_clear

Clears a particle system to its default settings.

Syntax:

part_system_clear(ind);

Argument | Description
ind | The index of the particle system to clear.

Returns: N/A

Description

With this function you can clear the indexed system to its default state, removing all emitters and resetting the depth and position (if they had been changed). Be careful using this function as if you have any instance setting or bursting or any other action using an emitter associated with this system, you will get an error unless you are using the part_emitter_exists function to check. There is also no need to call the part_emitter_destroy function as this is taken care of automatically too.

NOTE: this function will clear the visible particles in the room, but it does not clear the particle properties, nor does it remove them from memory. For that you should use the functions part_type_clear and part_type_destroy.

Example:

part_system_clear(global.Sname);

The above code will clear the particle system indexed in the global variable "Sname" to its default state.

Back: Particle Systems
Next: part_system_depth

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_create

Creates a new particle system and returns its index.

Syntax:

part_system_create();

Returns: Real

Description

This function is used to create a new particle system and will return a unique index number that should be stored and used in all further functions relating to that system.

Example:

global.Sname = part_system_create();

This will create a new particle system and store the index in the global variable "Sname".

Back: Particle Systems
Next: part_system_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_depth

Sets the depth of the particle system.

Syntax:

part_system_depth( ind, depth );

Argument | Description
ind | The index of the particle system to change.
depth | The depth at which to set the particle system.

Returns: N/A

Description

With this function you can set the draw depth for the particle system, much the same as you can set the depth of different instances within the room, where a low draw depth means that it will appear on top of all things drawn with a higher depth, and a high draw depth placing it below everything with a lower draw depth.

Example:

global.Sname = part_system_create();
part_system_depth(global.Sname, -100000 );

The above code will create a particle system and store its index in the global variable "Sname". this system is then given a low depth of -100000, meaning that it will appear above everything with a higher draw depth.

Back: Particle Systems
Next: part_system_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_destroy

Destroys an existing given particle system and any emitters it carries.

Syntax:

part_system_destroy(ind);

Argument | Description
ind | The index of the particle system to destroy.

Returns: N/A

Description

With this function you can destroy a given particles system and remove it from memory. This should always be called when the system is no longer needed, like at the end of a room, or in the destroy event of an instance, otherwise you could end up with particles appearing in later rooms and no way to remove them as well as a memory leak which will eventually crash your game.

NOTE: This function will also destroy and remove any emitters that may have been created and associated with the system being destroyed.

Example:

mysystem = part_system_create();
part_system_destroy( mysystem );

This will create a new particle system with the index mysystem. It will then destroy it.

Back: Particle Systems
Next: part_particles_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_draw_order

Sets the order in which new particles are drawn.

Syntax:

part_system_draw_order(ind, oldtonew);

Argument | Description
ind | The index of the particle system to change.
oldtonew | Whether old particles should be drawn behind newer ones (true) or vice versa (false).

Returns: N/A

Description

With this function you can set the way in which particles are drawn when created on the screen. The default system uses an old>new look (the function is set to true), where old particles are drawn at a higher depth than newer ones and so appear "beneath" them new particles, but by setting this function to false you can reverse this order and have the new particles drawn higher and so appear "beneath" the older ones. The images below illustrate this, with the image on the left being the default value of true and the image on the right being false:

NOTE: When the particles are being drawn with an additive blend mode, the effect of this function may not always be obvious.

Example:

mysystem = part_system_create();
part_system_clear( mysystem, 1 );

This will create a new particle system with the index mysystem. It will then set its particles to draw newer particles atop older ones.

Back: Particle Systems
Next: part_particles_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_drawit

Draws the particles in a given system.

Syntax:

part_system_drawit(ind);

Argument | Description
ind | The index of the particle system to draw the particles of.

Returns: N/A

Description

With this function you can force a particle system to draw all the current particles on the screen. If part_system_automatic_draw is switched off then this function will show the particles when used in the draw event of an instance, or it can be used when the drawing target is set to a surface (using surface_set_target) to draw the particles in the system to that surface.

Example:

if surface_exists(surf)
{
surface_set_target(surf);
part_system_drawit();
surface_reset_target();
}

The above code checks to see if the surface indexed in the variable "surf" exists, and if it does it then sets the drawing target to the surface, draws the particles and then resets the drawing target so all normal drawing appears on the screen once more.

Back: Particle Systems
Next: part_system_draw_order

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_exists

Checks to see whether a particle system exists.

Syntax:

part_system_exists(ind);

Argument | Description
ind | The index of the particle system to check for.

Returns: Boolean

Description

With this function you can check to see if the given particle system indexed exists in the game or not. Note that if the variable being checked is an uninitialised variable (that a particle system would otherwise have its index assigned to) this will throw an error.

Example:

if !part_system_exists(global.Sname)
{
global.Sname = part_system_create();
}

the above code checks to see if the particle system referenced in the global variable exists and if it does not it is created.

Back: Particle Systems
Next: part_system_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_position

Sets the position of the particle system.

Syntax:

part_system_position(ind, x, y);

Argument | Description
ind | The index of the particle system to change.
x | The new x coordinate of the particle system.
y | The new y coordinate of the particle system.

Returns: N/A

Description

With this function you can set the base position for the particle system relative to the (0,0) position of the room, meaning that all further particle functions relating to this system will now be drawn relative to the new position. By default this position is always (0,0), but in some very special circumstances you may wish to change this to something else.

NOTE: This function will change everything within the particle system, so if you have an emitter at position (100,100) and then set the particle system position to (0,100), the emitter will now draw at (100,200). The same goes if you shift the system and then create the emitter, as even though you create it at (100,100) it will be drawn at (100,200).

Example:

if mouse_check_button_pressed(mb_left)
{
part_system_position(global.Sname, mouse_x, mouse_y);
}

The above code will check for the press of the mouse button and if it detects one, the particle system indexed in the global variable "Sname" is shifted to the mouse x/y position

Back: Particle Systems
Next: part_system_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_system_update

Updates the positions of the particles in a given system.

Syntax:

part_system_update(ind);

Argument | Description
ind | The index of the particle system to update.

Returns: N/A

Description

This function will advance the given particle system one step in game time and can be used to simulate the particle system behaviour when automatic updating is off, or it can be used to advance a particle system to a specific point all in one step. For example, if you have a particle system for snow, and you want it to appear that the snow is falling right from the moment the player enters the room then you may wish to advance your snow particles for a few seconds in the create event of an instance so that the first time they are drawn, there are particles all over the screen (the code example below shows this). You can also use this function when automatic updating of the system is switched off by the function part_system_automatic_update to move the system along.

Example:

repeat (room_speed * 3)
{
part_system_update(global.RainSys);
}

The above code will advance the particle system indexed in the global variable "RainSys" by 3 seconds.

Back: Particle Systems
Next: part_system_drawit

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Particle Types

This section deals with defining particles for use in a particle system.

Particles are the graphic effects that can be created by the use of particle systems in a game. The particles that you define using these functions can be used in any system that you create and the normal procedure would be to define all your particles once at the start of a game and store their index values in global variables. These global variables can then be used to burst, emit or create particles at any time throughout the game. You can also create, use and then destroy particles as needed if memory is an issue or if you wish many different types but only at specific points in your game. Whatever you choose, particles are a very versatile resource!

Defining Particles

Particles need to be created and have their index stored in a variable so that all further particle routines can access them correctly. The following functions are used to create, check for, clear and destroy particle types:

  1. part_type_exists
  2. part_type_create
  3. part_type_destroy
  4. part_type_clear

Once you have created your particle type you should give it a shape. This can be one of the 14 built in shapes which are 64x64 pixel sprites with alpha blending, or you can use your own sprites which can be animated, static or use random sub-images. The following functions define the visual base shape of each particle:

  1. part_type_shape
  2. part_type_sprite

The following image shows the 14 built in particle types that you can choose from:

Once you have chosen the sprite for the particle type (either a default shape or your own) you can indicate the size and scale of it. The size can be specified as a range and all particles will be created with a size chosen from within the given range. The scale is the "base" value for the x and y axis scale of the particle before any size variations are added and the following functions are used to control these values:

  1. part_type_size
  2. part_type_scale

Particles can also have an orientation and motion. As with most particle functions, the speed, direction and orientation are resolved as a random value that is selected from a given range and can be set with the following functions:

  1. part_type_speed
  2. part_type_direction
  3. part_type_gravity
  4. part_type_orientation

Once you have the style and movement of your particles sorted out, you can then set their colour and alpha values, both of which can be set as an absolute value during the whole lifespan of the particle, or as a scale of values that go from one to the other gradually. Note that there is also a special function that permits you to set the blending for particles and their surroundings, and this can be either normal or additive and gives some fantastic effects- The functions governing colour, alpha and blending are:

  1. part_type_colour_mix
  2. part_type_colour_rgb
  3. part_type_colour_hsv
  4. part_type_colour1
  5. part_type_colour2
  6. part_type_colour3
  7. part_type_alpha1
  8. part_type_alpha2
  9. part_type_alpha3
  10. part_type_blend

Particles exist on-screen for a limited amount of time and this is called their "lifetime". Particle lifetimes are measured in steps and (like previous functions) this is expressed as a range of values from which the particle will be given a specific lifetime. There are also a couple of interesting functions which can be used to make particles generate other particles, either each step or when they "die" (ie: Are removed from the screen), but be very careful with these functions as they can quickly create thousands of particles and crash the game! The functions that set lifetime and step or death emitting are as follows:

  1. part_type_life
  2. part_type_step
  3. part_type_death

It is worth noting that creating particles through code can often be a laborious and time-consuming process due to the large number of parameters that can be changed and tweaked. For that reason it is recommended that you search around and get a hold of some type of Particle Designer (or make one yourself!) to take the drudgery out of particle creation.

Back: Particles

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_alpha1

Sets a particle type to have a single alpha value throughout its lifespan.

Syntax:

part_type_alpha1(ind, alpha1);

Argument | Description
ind | The index of the particle type to change.
alpha1 | The alpha of the particle.

Returns: N/A

Description

This function is used to set a particle type to have a single alpha value (transparency) for the total duration of the lifetime of each individual particle, and this can be from 0 (transparent) to 1 (opaque).

Example:

part_type_alpha1(global.Snow_Part, 0.5);

The above code will set all particles created of the particle type indexed in the global variable "Snow_Part" to have an alpha value of 0.5 (semi-transparent).

Back: Particle Types
Next: part_type_alpha2

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_alpha2

Sets a particle type to start at one alpha value and fade to another throughout its lifespan.

Syntax:

part_type_alpha2(ind, alpha1, alpha2);

Argument | Description
ind | The index of the particle type to change.
alpha1 | The start alpha of the particle.
alpha2 | The end alpha of the particle.

Returns: N/A

Description

This function can be used to set an alpha value (transparency) gradient for each particle created of the given type. The first alpha is that which all particles will start with, and the second alpha is the one on with which the particle will end with, and a smooth gradient change will occur to the alpha over the particles lifetime from one to the other. This can be from 0 (transparent) to 1 (opaque).

Example:

part_type_alpha2(global.Snow_Part, 0, 1);

The above code will set all particles created of the particle type indexed in the global variable "Snow_Part" to have an alpha value of 0 (transparent) and then fade in to have an alpha of 1 (opaque) at the end of their lifetime.

Back: Particle Types
Next: part_type_alpha3

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_alpha3

Sets a particle type to fade between three alpha values throughout its lifespan.

Syntax:

part_type_alpha3(ind, alpha1, alpha2, alpha3);

Argument | Description
ind | The index of the particle type to change.
alpha1 | The starting alpha of the particle.
alpha2 | The halfway point alpha of the particle.
alpha3 | The ending alpha of the particle.

Returns: N/A

Description

This function can be used to set a three alpha (transparency) value gradient for each particle created of the given type. The first alpha is that which all particles will start with, and the second alpha is the one that will be blended to half way through its lifetime and the third alpha is the one with which the particle will end with. A smooth gradient change will occur through the alphas over the particles lifetime from one to the other.

Example:

part_type_alpha3( part_Health, 0.5, 1, 0);

The above code will make all particles created of the type indexed in the variable "part_Health" have an alpha blend from 0.5 to 1 to 0 over their lifetime.

Back: Particle Types
Next: part_type_blend

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_blend

Sets a particle types blend mode.

Syntax:

part_type_blend(ind, additive);

Argument | Description
ind | The index of the particle type to change.
additive | Whether the particles should be blended additively (true) or normally (false).

Returns: N/A

Description

With this function you can make your particles be drawn with an additive blend mode (true) or not (false). Additive blending is a special blend mode that adds the luminosity values of each particle as they overlap, so that light colours will gradually get brighter (until they appear white) as they overlap, and dark colours become more and more transparent with black being almost invisible. This function can give some beautiful particle effects but may not always be necessary. For example, a smoke trail would have additive blending off to keep the effect gray, but a flame effect would probably have it on to make the particles more translucent and brighter.

Example:

part_type_blend(part_Fire, true);

The above code will set all particles created of the particle type indexed in the variable "part_Fire" to have an additive blend mode.

Back: Particle Types
Next: part_type_life

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_clear

Clears all of the settings of a given particle type, returning it to its defaults.

Syntax:

part_type_clear(ind);

Argument | Description
ind | The index of the particle type to clear.

Returns: N/A

Description

With this function you can "reset" a particle, returning all the values for each of the functions relating to the particle (life, colour, alpha, orientation etc...) to their default values. Note that this function does not remove any particles currently visible in the room from the screen, for that you should be using part_particles_clear.

Example:

part_type_clear(global.explode_part);

The above code will clear the particle type indexed in the global variable "explode_part" to its default values.

Back: Particle Types
Next: part_type_shape

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_colour_hsv

Set the particle colour from a hue, saturation and value range.

Syntax:

part_type_colour_hsv(ind, hmin, hmax, smin, smax, vmin, vmax);

Argument | Description
ind | The index of the particle type to change.
hmin | The minimum the final colour's hue component can be.
hmax | The maximum the final colour's hue component can be.
smin | The minimum the final colour's saturation component can be.
smax | The maximum the final colour's saturation component can be.
vmin | The minimum the final colour's value component can be.
vmax | The maximum the final colour's value component can be.

Returns: N/A

Description

With this function you can set a hue, saturation and value range for all particles of the given type. You supply a minimum value and a maximum value for each of the three components and the particles created will have a random colour based on the given range of parameters. In this way you can create particles of the same hue but different saturations, or of different hues but the same value (luminosity) etc... All values must be between 0 and 255.

Example:

part_type_hsv(global.Stars, 0, 255, 0, 255, 255, 255 );

The above code sets each particle emitted of the particle type indexed in the global variable "Stars" to have different colours and saturations, but the same value (luminosity).

Back: Particle Types
Next: part_type_colour_mix

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_colour_mix

Sets a particle type to be any blend of two given colours.

Syntax:

part_type_colour_mix(ind, colour1, colour2);

Argument | Description
ind | The index of the particle type to change.
colour1 | The first colour the blend will take from.
colour2 | The second colour the blend will take from.

Returns: N/A

Description

With this function you can set the given particle type to be a random blend of two colours.

Example:

part_type_colour_mix(global.P_Damage, c_red, c_yellow);

The above code will set the colour for each particle emitted of the particle type indexed in the global variable "P_Damage" to be a random mix between the colours red and yellow.

Back: Particle Types
Next: part_type_colour_rgb

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_colour_rgb

Set the particle colour from a red, green and blue range.

Syntax:

part_type_colour_rgb(ind, rmin, rmax, gmin, gmax, bmin, bmax p>

Argument | Description
ind | The index of the particle type to change.
rmin | The minimum the final colour's red component can be.
rmax | The maximum the final colour's red component can be.
gmin | The minimum the final colour's green component can be.
gmax | The maximum the final colour's green component can be.
bmin | The minimum the final colour's blue component can be.
bmax | The maximum the final colour's blue component can be.

Returns: N/A

Description

With this function you can set the mix of red, green and blue colours for all particles created of the given type. You supply a minimum value and a maximum value for each of the three components and the particles created will have a random colour based on the given range of parameters. All values must be between 0 and 255.

Example:

part_type_rgb(global.Blood_Part, 0, 255, 0, 0, 0, 0);

The above code sets each particle emitted of the particle type indexed in the global variable "Blood_Part" to be only different shades of red.

Back: Particle Types
Next: part_type_colour1

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_colour1

Sets a particle type to be a single colour throughout its lifespan.

Syntax:

part_type_colour1(ind, colour1);

Argument | Description
ind | The index of the particle type to change.
colour1 | The single colour to make the particle type.

Returns: N/A

Description

This function is used to set a particle type to be a single colour for the total duration of the lifetime of each individual particle.

Example:

part_type_colour1(global.Snow_Part, c_white);

The above code will set all particles created of the particle type indexed in the global variable "Snow_Part" to be white only.

Back: Particle Types
Next: part_type_colour2

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_colour2

Sets the particle type to blend between two colours

Syntax:

part_type_colour2(ind, colour1, colour2);

Argument | Description
ind | The index of the particle type to change.
colour1 | The colour the particle will start at.
colour2 | The colour the particle will end at.

Returns: N/A

Description

This function can be used to set a two colour gradient for each particle created of the given type. The first colour is that which all particles will start with, and the second colour is the one on which the particle will end with, and a smooth gradient change will occur to the colour over the particles lifetime from one colour to the other.

Example:

part_type_colour2( part_Health, c_red, c_white);

The above code will make all particles created of the type indexed in the variable "part_Health" have a colour blend from red to white over their lifetime.

Back: Particle Types
Next: part_type_colour3

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_colour3

Sets a particle type to fade between three colours throughout its lifespan.

Syntax:

part_type_colour3( ind, colour1, colour2, colour3 );

Argument | Description
ind | The index of the particle type to change.
colour1 | The colour the particle will start at.
colour2 | The colour the particle will be halfway through its lifespan.
colour3 | The colour the particle will end at.

Returns: N/A

Description

This function can be used to set a three colour gradient for each particle created of the given type. The first colour is that which all particles will start with, and the second colour is the one that will be blended to half way through its lifetime and the third colour is the one with which the particle will end with. A smooth gradient change will occur through the colours over the particles lifetime from one colour to the other.

Example:

part_type_colour3( part_Health, c_red, c_white, c_maroon);

The above code will make all particles created of the type indexed in the variable "part_Health" have a colour blend from red to white to maroon over their lifetime.

Back: Particle Types
Next: part_type_alpha1

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_create

Creates a new particle type.

Syntax:

part_type_create();

Returns: Real

Description

With this function you can create a new particle type and the return value should be stored in a variable for use in all subsequent particle functions.

Example:

mypart = part_type_create();

This will create a new particle type, storing its index in the variable "mypart".

Back: Particle Types
Next: part_type_destroy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_death

Sets a particle type to emit another particle type at the end of its lifetime.

Syntax:

part_type_death(ind, death_number, death_type);

Argument | Description
ind | The index of the particle type to change.
death_number | The quantity of the new particle to create at the particle death. If a negative value, it will instead create a fraction chance one is created (eg -3 would mean that one is created every 3 or so steps).
death_type | The index of the particle type to create.

Returns: N/A

Description

This function can be used to make your particle burst another type of particle at the end of its lifetime.

NOTE: NEVER use the same particle type as this will cause an infinite loop and can crash the game in seconds! Also, be very careful when using this as it can greatly increase the number of particles on-screen at a time and cause your games to slow down noticeably.

Example:

particle1 = part_type_create();
part_type_shape(particle1, pt_shape_flare);
part_type_size(particle1, 0.20, 0.30, 0.50, 0);
part_type_scale(particle1, 0.10, 0.20);
part_type_colour3(particle1, 33023, 8454143, 33023);
part_type_alpha3(particle1, 0.30, 0.50, 0);
part_type_speed(particle1, 0.40, 1, 0, 0);
part_type_direction(particle1, 0, 359, 0, 20);
part_type_gravity(particle1, 0.20, 90);
part_type_orientation(particle1, 90, 90, 0, 0, 1);
part_type_blend(particle1, 1);
part_type_life(particle1, 1, 40);
particle2 = part_type_create();
part_type_shape(particle2, pt_shape_smoke);
part_type_size(particle2, 1, 1, 0, 0);
part_type_scale(particle2, 0.50, 0.50);
part_type_colour1(particle2, 12632256);
part_type_alpha3(particle2, 0.10, 0.40, 0);
part_type_speed(particle2, 0.50, 0.50, 0, 0);
part_type_direction(particle2, 0, 359, 0, 0);
part_type_gravity(particle2, 0.20, 90);
part_type_orientation(particle2, 0, 359, 0, 1, 1);
part_type_blend(particle2, 0);
part_type_life(particle2, 60, 60);
part_type_death(particle1, 1, particle2);

The above code creates and defines two particles and sets the particle indexed in the variable "particle1" to create 1 particle of "particle2" at the end of its lifetime.

Back: Particle Types
Next: part_type_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_destroy

Destroys a given particle type.

Syntax:

part_type_destroy(ind);

Argument | Description
ind | The index of the particle type to destroy.

Returns: N/A

Description

With this function you can remove the specified particle type from the game. When you use this function, all particles of the given type will disappear from the room and the particle itself is removed form memory, so this function should be used only when you no longer need the particle.

Example:

if part_particles_count(smoke_sys) = 0
{
part_type_destroy(smoke_part);
part_system_destroy(smoke_sys);
instance_destroy();
}
else alarm[0] = 1;

The above code checks a particle system to see if any particles are currently visible in the room and if not, the particles, the system and the instance are destroyed.

Back: Particle Types
Next: part_type_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_direction

Sets the direction properties for the given particle type.

Syntax:

part_type_direction(ind, dir_min, dir_max, dir_incr, dir_wiggle);

Argument | Description
ind | The index of the particle type to change.
dir_min | The minimum direction the particle can start at.
dir_max | The maximum direction the particle can start at.
dir_incr | How much the particle direction should increase or decrease per step.
dir_wiggle | How much should randomly be added or subtracted from the particle's direction per step.

Returns: N/A

Description

This function is used to determine the direction of the particle when it is created and can also be used to make the particle increase or decrease its direction over its lifetime. The minimum and maximum direction values default at 0, which means that the particle will move to the right with no variation, but these values can be changed to limit the direction of movement following the standard GameMaker: Studio directions of 0 being right, 90 being up, 180 being left and 270 being down. If you set them to the same value the particles will only move in one direction.

You can also set an increment value which will add (if a positive number) or subtract (if a negative number) an amount of degrees to the direction over its lifetime. This value can be a minimum of (+/-) 0.01.

Finally, you can set the "wiggle" factor. This is a value that will be added or subtracted randomly to the direction each step of the particles lifetime. Obviously larger values are more pronounced than smaller ones, and this value can even be a negative with the maximum range being between -20 and 20.

Example:

part_type_shape(particle1, pt_shape_pixel);
part_type_size(particle1, 0.19, 0.79, 0.01, 0);
part_type_scale(particle1, 5, 5);
part_type_colour3(particle1, 32768, 8454016, 8454016);
part_type_alpha3(particle1, 0, 0.80, 0);
part_type_speed(particle1, 8, 10, -0.50, 1);
part_type_direction(particle1, 0, 359, 1, 20);
part_type_gravity(particle1, 0, 270);
part_type_orientation(particle1, 0, 359, 0, 0, 1);
part_type_blend(particle1, 1);
part_type_life(particle1, 10, 50);

The above code will set various particle values including the direction which will be random value between 0 and 359 degrees. It will also go up by 1 degree each step and has a random amount added to it of anywhere between 0 and 20 each step too.

Back: Particle Types
Next: part_type_gravity

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_exists

Checks to see if a given particle type exists.

Syntax:

part_type_exists(ind);

Argument | Description
ind | The index of the particle type to check for.

Returns: Boolean

Description

With this function you can check to see if the given particle type indexed exists in the game or not. Note that if the variable being checked is an uninitialised variable (that a particle type would otherwise have its index assigned to) this will throw an error.

Example:

if !part_type_exists(global.p1)
{
global.p1 = part_type_create();
}

The above code checks to see if the global variable "p1" stores the index of a particle type and if it does not it creates one.

Back: Particle Types
Next: part_type_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_gravity

Sets the gravity of the given particle type.

Syntax:

part_type_gravity(ind, grav_amount, grav_direction);

Argument | Description
ind | The index of the particle type to change.
grav_amount | Strength of the gravity.
grav_direction | The direction of the gravity.

Returns: N/A

Description

This function will set the gravity that is to affect each particle of the given type that is created. The gravity strength value is added to the particle speed every step and is usually a small value like 0.5, while the direction is the direction of the gravity "pull" and follows the standard GameMaker: Studio directions of 0� being right, 90� being up, 180� being left and 270� being down.

Example:

part_type_shape(global.p1, pt_shape_pixel);
part_type_size(global.p1, 1, 3, 0, 0);
part_type_scale(global.p1, 1, 1);
part_type_colour1(global.p1, c_white);
part_type_alpha2(global.p1, 1, 0);
part_type_speed(global.p1, 2, 4, 0, 0);
part_type_direction(global.p1, 0, 180, 0, 0);
part_type_gravity(global.p1, 0.20, 270);
part_type_orientation(global.p1, 0, 0, 0, 0, 1);
part_type_blend(global.p1, 1);
part_type_life(global.p1, 15, 60);

The above code will set various particle values including the gravity which will add 0.2 to the speed each step with a direction of 270�, so will pull the particle "down" towards the bottom of the screen.

Back: Particle Types
Next: part_type_orientation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_life

Sets a particle type's lifespan in steps.

Syntax:

part_type_life(ind, life_min, life_max);

Argument | Description
ind | The index of the particle type to change.
life_min | The minimum lifespan of the particles.
life_max | The maximum lifespan of the particles.

Returns: N/A

Description

This is the function that governs how long each individual particle of the indicated type remains on the screen. As with other particle functions, you provide a minimum and a maximum value (in steps)and each particle lifespan will be a random number of steps from within the specified range. To have all particles with the same lifetime, set the two values to be the same.

Example:

part_type_life(part_Flare, room_speed, room_speed * 2);

The above code will set all particles created of the particle type indexed in the variable "part_Flare" to have a lifetime of between 1 and 2 seconds, based on the current room-speed.

Back: Particle Types
Next: part_type_step

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_orientation

Sets the angle of the particle type.

Syntax:

part_type_orientation( ind, ang_min, ang_max, ang_incr, ang_wiggle, ang_relative );

Argument | Description
ind | The index of the particle type to change.
ang_min | The minimum starting angle of the particles.
ang_max | The maximum starting angle of the particles.
ang_incr | The increase (or decrease if set negative) of the angle in degrees per step.
ang_wiggle | The amount the angle wiggles clockwise/counterclockwise per step.
ang_relative | Whether to set its angle relative to the direction of the particle's motion (true) or not (false).

Returns: N/A

Description

This function is used to determine the orientation of the particle sprite when it is created and can also be used to make the particle orientation increase or decrease over its lifetime. The minimum and maximum orientation values default at 0 but these values can be changed to randomize the orientation following the standard GameMaker: Studio directions of 0 degrees being right, 90 degrees being up, 180 degrees being left and 270 degrees being down. If you set them to the same value the particles will all be created with the same orientation.

You can also set an increment value which will add (if a positive number) or subtract (if a negative number) an amount of degrees to the orientation over its lifetime. This value can be a minimum of (+/-) 0.01.

You can set the "wiggle" factor too, the same as other particle functions. This is a value that will be added or subtracted randomly to the orientation each step of the particles lifetime. Obviously larger values are more pronounced than smaller ones, and this value can even be a negative with the maximum range being between -20 and 20.

Finally, you can choose to have the orientation relative or not, which means that while the particle has a direction (and speed) the particle sprite will be orientated around that vector. Bear in mind that if you have the particle speed set to reduce and it reaches 0, the lack of speed sets the direction to the default value of 0� and so a relative orientation will cause the particle sprite to "jump" to a different angle.

Example:

part_type_shape(particle2, pt_shape_spark);
part_type_size(particle2, 0.10, 0.50, 0.01, 0);
part_type_scale(particle2, 0.30, 0.30);
part_type_colour1(particle2, 8454143);
part_type_alpha1(particle2, 0.50);
part_type_speed(particle2, 4, 4, -0.07, 1);
part_type_direction(particle2, 0, 359, 0, 20);
part_type_orientation(particle2, 0, 359, 0, 20, 1);
part_type_blend(particle2, 1);
part_type_life(particle2, 1, 5);

The above code will set various particle values including the orientation which will be random value between 0� and 359�. It will also have a random amount added to it of anywhere between 0 and 20 each step too, and the orientation is relative to the direction of motion.

Back: Particle Types
Next: part_type_colour_hsv

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_scale

Sets the horizontal and vertical scaling of the particle type.

Syntax:

part_type_scale(ind, xscale, yscale);

Argument | Description
ind | The index of the particle type to change.
xscale | The horizontal scaling of the base particle.
yscale | The vertical scaling of the base particle.

Returns: N/A

Description

This function will set the horizontal and vertical scale of the particle before any other size changes are made. This function works on the ratio of the sprite size, so a value of 1 (the default value) is a 1:1 ratio, meaning that 0.5 would be half and 2 double.

Example:

part_type_shape(particle1, pt_shape_flare);
part_type_size(particle1, 2, 2, 0.10, 1);
part_type_scale(particle1, 8, 0.50);
part_type_colour3(particle1, 8388608, 4227327, 8454143);
part_type_alpha3(particle1, 0.10, 0.10, 0);
part_type_speed(particle1, 0, 1, 0.18, 20);
part_type_direction(particle1, 0, 359, 0, 0);
part_type_orientation(particle1, 0, 0, 0, 0, 1);
part_type_blend(particle1, 1);
part_type_life(particle1, 10, 40);

The above code will set various particle values including the scale which sets the xscale to eight times the size and the yscale to half the size.

Back: Particle Types
Next: part_type_speed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_shape

Sets the shape of created particles to one of the fourteen in-built shapes.

Syntax:

part_type_shape(ind, shape);

Argument | Description
ind | The index of the particle type to set.
shape | The shape to choose.

Returns: N/A

Description

With this function you can set the sprite shape to use for the particle type, with the following constants being acceptable:

Constant | Description
ind | The index of the particle type to set.
pt_shape_pixel | A 1x1 pixel. (This is the default setting.)
pt_shape_disk | A filled circle.
pt_shape_square | A filled square.
pt_shape_line | An 8px wide horizontal line.
pt_shape_star | A five-point filled star.
pt_shape_circle | A 3px outlined circle.
pt_shape_ring | A circle with an inward glow (looks like a bubble).
pt_shape_sphere | A circle with an outward glow ' solid in the middle, glowing outwards.
pt_shape_flare | A harshly glowing point (looks like an actual star in the night).
pt_shape_spark | A spark effect ' like a star with multiple points fading out.
pt_shape_explosion | A squarish cloud of smoke ' requires multiple colours to resemble an explosion.
pt_shape_cloud | A thin cloud, requires up scaling and multiple particles to resemble a cloud.
pt_shape_smoke | A smooth version of the explosion effect. Use multiple to create a smoke cloud.
pt_shape_snow | A generic snowflake shape.

Example:

global.p1 = part_type_create();
part_type_shape(global.p1, pt_shape_square);
part_type_size(global.p1, 1, 3, 0, 0);
part_type_scale(global.p1, 1, 1);
part_type_colour1(global.p1, c_white);
part_type_alpha2(global.p1, 1, 0);
part_type_speed(global.p1, 2, 4, 0, 0);
part_type_direction(global.p1, 0, 180, 0, 0);
part_type_gravity(global.p1, 0.20, 270);
part_type_orientation(global.p1, 0, 0, 0, 0, 1);
part_type_blend(global.p1, 1);
part_type_life(global.p1, 15, 60);

The above code sets the particle type indexed in the global variable "p1" to the shape of a square, then sets various other particle properties.

Back: Particle Types
Next: part_type_sprite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_size

Sets the minimum and maximum start size of the particle type.

Syntax:

part_type_size(ind, size_min, size_max, size_incr, size_wiggle);

Argument | Description
ind | The index of the particle type to change.
size_min | The minimum size the particle can start at.
size_max | The maximum size the particle can start at.
size_incr | How much the particle should increase or decrease per step.
size_wiggle | How much should randomly be added or subtracted from the particles size per step.

Returns: N/A

Description

This function is used to determine the size of the particle when it is created and can also be used to make the particle increase or decrease in size over its lifetime. The minimum and maximum size values default at 1 (meaning that the size is the same ratio as the base particle after the part_type_scale scale has been set) and if they are set to the same value, the initial size for all particles will be the same, but if set to different values, each particle will start with a random size from within the range, for example if you have a minimum of 0.5 and a maximum of 2, all particles will be created with a size between half and double the base scale.

You can also set an increment value that will make the particle sprite grow (if a positive number) or shrink (if a negative number) over the lifetime of the particle, with the given amount being added to the particle size each step. This value can be a minimum of (+/-)0.01.

Finally, you can set the "wiggle" factor. This is a value that will be added or subtracted randomly to the size each step of the particles lifetime. Obviously larger values are more pronounced than smaller ones, and this value can even be a negative with the maximum range being between -20 and 20.

Example:

part_type_shape(particle1, pt_shape_explosion);
part_type_size(particle1, 2, 2, 0.10, 0.01);
part_type_scale(particle1, 1, 1);
part_type_colour2(particle1, 16777215, 12632256);
part_type_alpha3(particle1, 0, 0.20, 0);
part_type_speed(particle1, 0.20, 0.20, 0, 0);
part_type_direction(particle1, 0, 359, 0, 20);
part_type_orientation(particle1, 0, 359, 0, 0, 1);
part_type_blend(particle1, 0);
part_type_life(particle1, 40, 60);

The above code will set various particle values including the size which is set to double the size when each particle is created, and then increment the size by 0.01 each step with a wiggle of 0.1 too.

Back: Particle Types
Next: part_type_scale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_speed

Sets the minimum and maximum speed for any given particle.

Syntax:

part_type_speed(ind, speed_min, speed_max, speed_incr, speed_wiggle);

Argument | Description
ind | The index of the particle type to change.
speed_min | The minimum speed the particle can start at.
speed_max | The maximum speed the particle can start at.
speed_incr | How much the particle speed should increase or decrease per step.
speed_wiggle | How much should randomly be added or subtracted from the particle's speed per step.

Returns: N/A

Description

This function is used to determine the speed of the particle when it is created and can also be used to make the particle increase or decrease its speed over its lifetime. The minimum and maximum speed values default at 1, which means that the particle will move 1 pixel each step, and if they are set to the same value, the initial speed for all particles will be the same, but if set to different values, each particle will start with a random speed from within the given range. For example if you have a minimum of 3 and a maximum of 6, all particles will be created with a speed between three and six pixels per step.

You can also set an increment value that will make the particle move faster (if a positive number) or slower (if a negative number) over its lifetime, with the given amount being added to the particle speed each and every step. This value can be a minimum of (+/-)0.01.

Finally, you can set the "wiggle" factor. This is a value that will be added or subtracted randomly to the speed each step of the particles lifetime. Obviously larger values are more pronounced than smaller ones, and this value can even be a negative with the maximum range being between -20 and 20.

Example:

part_type_shape(particle2, pt_shape_flare);
part_type_size(particle2, 0.01, 0.50, 0.01, 20);
part_type_scale(particle2, 0.10, 0.10);
part_type_colour3(particle2, 4210816, 4227327, 8240895);
part_type_alpha3(particle2, 0.20, 0.80, 0);
part_type_speed(particle2, 5, 10, -0.20, 20);
part_type_direction(particle2, 0, 359, -1, 20);
part_type_gravity(particle2, 0, 270);
part_type_orientation(particle2, 0, 359, 0, 20, 1);
part_type_blend(particle2, 1);
part_type_life(particle2, 1, 20);

The above code will set various particle values including the speed which sets a minimum speed of five and a maximum speed of ten, with the speed slowing down by a value of -0.2 each step. The speed will also wiggle by a random value between 0 and 20 each step.

Back: Particle Types
Next: part_type_direction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_sprite

Sets the shape of created particles to a sprite.

Syntax:

part_type_sprite(ind, sprite, animate, stretch, random);

Argument | Description
ind | The index of the particle type to change.
sprite | The index of the sprite to set the particle type to.
animate | Whether to follow the sprite's animation normally (true) or not (false).
stretch | Whether to stretch the sprite's animation to match the particle lifespan (true) or not (false).
random | Whether to choose a random sub-image (true) or not (false).

Returns: N/A

Description

This function can be used to set a particle type to use a custom sprite from the game assets. You can select the sprite and then tell GameMaker: Studio to use the sprite and animate it or not, and if you choose animated, then you can also choose to have the sub-images changed at an interval such that the animation will begin and end at the beginning and end of the lifetime of each particle created (so that if you have a lifetime set to a15 step minimum and a 30 step maximum, no matter what value the lifetime has the animation will be made to fit, with it running faster for the shorter lifetimes and slower for the longer). You can also select to choose a random sub-image so that if the sprite is not animated, a different image will be chosen at random to create the sprite, or if the particle is animated it will start the animation at a random point.

Example:

global.p1 = part_type_create();
part_type_sprite(global.p1 , spr_Coins, 1, 0, 0);
part_type_size(global.p1, 1, 3, 0, 0);
part_type_scale(global.p1, 1, 1);
part_type_colour1(global.p1, c_white);
part_type_alpha2(global.p1, 1, 0);
part_type_speed(global.p1, 2, 4, 0, 0);
part_type_direction(global.p1, 0, 180, 0, 0);
part_type_gravity(global.p1, 0.20, 270);
part_type_orientation(global.p1, 0, 0, 0, 0, 1);
part_type_blend(global.p1, 1);
part_type_life(global.p1, 15, 60);

The above code sets the particle type indexed in the global variable "p1" to the shape of the sprite indexed in "spr_Coins", and then sets various other particle properties.

Back: Particle Types
Next: part_type_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


part_type_step

Sets a particle to create another each step throughout its lifetime.

Syntax:

part_type_step(ind, step_number, step_type);

Argument | Description
ind | The index of the particle type to change.
step_number | The quantity of the new particle to create per step.
step_type | The index of the particle type to create.

Returns: N/A

Description

This function can be used to make your particle type stream another type each step until the end of its lifetime. You can set a negative value for the step number and a particle will be emitted at a random interval based on that, so that, for example, a value of -3 will have a 1:3 chance of emitting a particle each step.

NOTE: NEVER use the same particle type as this will cause an infinite loop and can crash the game in seconds! Also, be very careful when using this as it can greatly increase the number of particles on-screen at a time and cause your games to slow down noticeably.

Example:

particle2 = part_type_create();
part_type_shape(particle2, pt_shape_smoke);
part_type_size(particle2, 0.01, 0.01, 0.01, 0);
part_type_scale(particle2, 1, 1);
part_type_colour3(particle2, 4227327, 8454143, 4227327);
part_type_alpha3(particle2,1, 0.50, 0.80);
part_type_speed(particle2, 0, 0, 0, 0);
part_type_direction(particle2, 0, 359, 0, 0);
part_type_gravity(particle2, 0, 270);
part_type_orientation(particle2, 0, 0, -2, 0, 1);
part_type_blend(particle2, 1);
part_type_life(particle2, 160, 160);
particle3 = part_type_create();
part_type_shape(particle3, pt_shape_flare);
part_type_size(particle3, 0.20, 0.20, 0.02, 0);
part_type_scale(particle3, 1, 1);
part_type_colour3(particle3, 16777215, 8454143, 16777215);
part_type_alpha3(particle3, 0, 0.50, 0);
part_type_speed(particle3, 3, 3, -0.03, 0);
part_type_direction(particle3, 0, 359, 0, 0);
part_type_gravity(particle3, 0, 270);
part_type_orientation(particle3, 0, 0, 0, 0, 1);
part_type_blend(particle3, 1);
part_type_life(particle3, 40, 80);
part_type_step(particle2, 2, particle3);

The above code creates and defines two particles and sets the particle indexed in the variable "particle2" to create 2 particles of "particle3" every step of its lifetime.

Back: Particle Types
Next: part_type_death

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Simple Effects

Here you can find the functions and constants for the built in particle system.

The easiest way of creating particles in your game with GameMaker: Studio is to use the in-built effects mechanism. There effects are created using an internal particle system which is basically a very fast method for drawing graphical effects only and as such you do not have to worry about all the details (like memory management) when using these functions. You simply specify the type of effect, the position where it must be created, the size you want it to be and finally, its colour then let GameMaker: Studio do all the work.

The following functions exists for creating the built in particle effects:

  1. effect_create_below
  2. effect_create_above
  3. effect_clear

There are also a number of different constants for each of the pre-defined effects that the above functions can use:

  1. ef_cloud
  2. ef_ellipse
  3. ef_explosion
  4. ef_firework
  5. ef_flare
  6. ef_rain
  7. ef_ring
  8. ef_smoke
  9. ef_smokeup
  10. ef_snow
  11. ef_spark
  12. ef_star

Even though these effects are limited in scope and customisation, they can still be used to create some simple, great effects with very little effort. For example by creating a small puff of grey smoke below a moving missile in each step, a pretty convincing smoke trail is created, so even when you are an expert in particles it pays to remember that these effects exists as they can still save you some time.

Back: Particles

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_cloud

Built in constant for a cloud effect.

Syntax:

ef_cloud;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a cloud effect as illustrated in the image below:

Example:

if !irandom(9)
{
effect_create_below(ef_cloud, random(room_width), random(room_height), choose(0, 1, 2), c_gray);
}

The above code has a 1 in ten chance of creating a cloud effect of random size at a random position within the room.

Back: Simple Effects
Next: ef_ellipse

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_ellipse

Built in constant for an ellipse effect.

Syntax:

ef_ellipse;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create an ellipse effect as illustrated in the image below:

Example:

effect_create_below(ef_ellipse, x, y, choose(0, 1, 2), make_colour_hsv(irandom(255), 255, 255);

The above code will create an ellipse effect with a random size and colour at the position of the instance running the code.

Back: Simple Effects
Next: ef_explosion

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_explosion

Built in constant for an explosion effect.

Syntax:

ef_explosion;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create an explosion effect as illustrated in the image below:

Example:

if health <= 0
{
effect_create_above(ef_explosion, x, y, 2, c_red);
instance_destroy();
}

The above code will create a red explosion effect with a random size at the position of the instance running the code if that instance has less than 0 health.

Back: Simple Effects
Next: ef_firework

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_firework

Built in constant for a firework effect.

Syntax:

ef_firework;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a firework effect as illustrated in the image below:

Example:

repeat(10)
{
effect_create_above(ef_firework, random(room_width), random(room_height), choose(0, 1, 2), make_colour_hsv(random(255), 255, 255));
}

The above code will create 10 random sized and coloured fireworks effects at a random position within the room.

Back: Simple Effects
Next: ef_flare

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_flare

Built in constant for a flare effect.

Syntax:

ef_flare;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a flare effect as illustrated in the image below:

Example:

if mouse_check_button_pressed(mb_left)
{
effect_create_above(ef_flare, x + lengthdir_x(32, image_angle), y + lengthdir_y(32, image_angle), 0, c_white);
instance_create(x + lengthdir_x(32, image_angle), y + lengthdir_y(32, image_angle), obj_Bullet);
}

The above code will create a small, white, flare effect at the indicated position as well as an instance of "obj_Bullet" when the mouse button has been pressed.

Back: Simple Effects
Next: ef_rain

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_rain

Built in constant for a rain effect.

Syntax:

ef_rain;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a rain effect as illustrated in the image below:

NOTE: This effect needs no x/y position as it is always drawn at the 0,0 room position to cover the full screen and the size value relates to the number of particles created, not the size of individual particles.

Example:

switch (global.weather)
{
case 1:
effect_create_above(ef_rain, 0, 0, 1, c_gray);
break;
case 2:
effect_create_above(ef_snow, 0, 0, 1, c_gray);
break;
}

The above code will create a rain or snow effect depending on the value of the global variable "weather".

Back: Simple Effects
Next: ef_ring

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_ring

Built in constant for a ring effect.

Syntax:

ef_ring;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a ring effect as illustrated in the image below:

Example:

if mouse_check_button_pressed(mb_left)
{
effect_create_below(ef_ring, mouse_x, mouse_y, 1, c_aqua);
}

The above code will create a light blue ring effect below the mouse cursor when the left button is pressed.

Back: Simple Effects
Next: ef_smoke

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_smoke

Built in constant for a smoke effect.

Syntax:

ef_smoke;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a smoke effect as illustrated in the image below:

Example:

if speed > 0
{
effect_create_below(ef_smoke, x, y, choose(0, 1, 2), c_gray);
}

The above code will create a smoke trail from the instance when the speed is greater than 0.

Back: Simple Effects
Next: ef_smokeup

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_smokeup

Built in constant for a rising smoke effect.

Syntax:

ef_smokeup;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a rising smoke effect as illustrated in the image below:

Example:

effect_create_below(ef_smokeup, x, y, choose(0, 1, 2), c_gray);

The above code will create a rising smoke cloud from the instance.

Back: Simple Effects
Next: ef_snow

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_snow

Built in constant for a snow effect.

Syntax:

ef_snow;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a snow effect as illustrated in the image below:

NOTE: This effect needs no x/y position as it is always drawn at the 0,0 room position to cover the full screen and the size value relates to the number of particles created, not the size of individual particles.

Example:

switch (global.weather)
{
case 1:
effect_create_above(ef_rain, 0, 0, 1, c_gray);
break;
case 2:
effect_create_above(ef_snow, 0, 0, 1, c_gray);
break;
}

The above code will create a rain or snow effect depending on the value of the global variable "weather".

Back: Simple Effects
Next: ef_spark

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_spark

Built in constant for a spark effect.

Syntax:

ef_spark;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a spark effect as illustrated in the image below:

Example:

if power
{
effect_create_above(ef_spark, bbox_left + random(sprite_width), bbox_top + random(sprite_height), choose(0, 1), merge_colour(c_white, c_yellow, random(1));
}

The above code will create a spark effect over the area of the instance if the variable "power" is true.

Back: Simple Effects
Next: ef_star

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ef_star

Built in constant for a star effect.

Syntax:

ef_star;

Returns: N/A.

Description

This constant is for use in the functions effect_create_above and effect_create_below, and will create a star effect as illustrated in the image below:

Example:

repeat(10)
{
effect_create_above(ef_star, x - 32 + random(64), y - 32 + random(64), choose(0, 1, 2), c_yellow);
}

The above code will create 10 random sized, yellow stars at a random position around the instance running the code.

Back: Simple Effects
Next: ef_cloud

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


effect_clear

Clears all effects created using the in-built particle system.

Syntax:

effect_clear();

Returns: N/A.

Description

This will clear all particles that are currently visible in the room which have been made using either effect_create_above or effect_create_below.

Example:

effect_clear();

Calling this will clear the room of any particles made with the effect_create_* functions.

Back: Simple Effects
Next: effect_create_below

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


effect_create_above

Creates a simple particle effect above all instances.

Syntax:

effect_create_above(kind, x, y, size, colour);

Argument | Description
kind | The kind of effect (use one of the constants listed here).
x | The x positioning of the effect if relevant.
y | The y positioning of the effect if relevant.
size | The size of the effect.
colour | The colour of the effect.

Returns: N/A

Description

With this function you can create a simple effect above all instances of your room (it is actually created at a depth of -100000). If the effect is anything other ef_rain or ef_snow then you can define an x/y position to create the effect, and the size can be a value of 0, 1, or 2, where 0 is small, 1 is medium and 2 is large.

It is worth noting that these effects can have their drawing toggled on and off, as well as have their drawing paused, by using the functions part_system_automatic_draw and part_system_automatic_update with the appropriate value for the particle system index (where 0 is for effects below and 1 is for effects above).

Example:

if health <= 0
{
effect_create_above(ef_explosion, x, y, 1, c_yellow);
instance_destroy();
}

The above code will create a medium, yellow, explosion above the instance and destroy it should the "health" variable be less than or equal to 0.

Back: Simple Effects
Next: effect_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


effect_create_below

Creates a simple particle effect beneath all instances.

Syntax:

effect_create_below(kind, x, y, size, colour);

Argument | Description
kind | The kind of effect (use one of the constants listed here).
x | The x positioning of the effect if relevant.
y | The y positioning of the effect if relevant.
size | The size of the effect.
colour | The colour of the effect.

Returns: N/A

Description

With this function you can create a simple effect beneath all instances of your room (it is actually created at a depth of 100000). If the effect is anything other ef_rain or ef_snow then you can define an x/y position to create the effect, and the size can be a value of 0, 1, or 2, where 0 is small, 1 is medium and 2 is large.

It is worth noting that these effects can have their drawing toggled on and off, as well as have their drawing paused, by using the functions part_system_automatic_draw and part_system_automatic_update with the appropriate value for the particle system index (where 0 is for effects below and 1 is for effects above).

Example:

if speed > 0
{
effect_create_below(ef_smoke, x, y, 0, c_gray);
}

The above code will create a small puff of gray smoke every step that the instance speed is greater than 0 at the instance x,y coordinates.

Back: Simple Effects
Next: effect_create_above

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Paths

This section deals with the basic path functions.

GameMaker: Studio has an extensive collection of functions and built-in variables for using paths within your game. This section deals with the basic ones that are used when dealing with paths that have previously been created in the Path Editor, but further functions exist that permit you to create your own paths using code, and to manipulate them in various ways.

The following basic functions exist that deal with paths:

  1. path_start
  2. path_end

The following variables are built-in to all instances when created and can be used to get information about a path, or to change certain properties:

  1. path_index
  2. path_position
  3. path_positionprevious
  4. path_speed
  5. path_scale
  6. path_orientation
  7. path_endaction

Further functions for paths can be found in the following two sections:

  1. Path Information
  2. Changing Paths

Back: Game Assets

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_index

The index of the path the calling instance is following.

Syntax:

path_index;

Returns: ID

Description

All resources in GameMaker: Studio have a unique identifying number, and the path_index is a read-only variable that holds the index value for a given path resource. If the instance has no path assigned, the variable will be set to -1.

Example:

if path_index = -1
{
path_start(pth_enemy3, 4, path_action_reverse, 0);
}

The above code checks to see if a path has been assigned to the instance, and if not it starts a new path (assigning it to the path_index at the same time).

Back: Paths
Next: path_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_end

Ends the path the calling instance is currently following.

Syntax:

path_end();

Returns: N/A.

Description

Calling this function will end the current path that the instance is following.

Example:

if place_meeting(x, y, all) path_end()

The above code will end the current path if the instance detects any collision with any other instance.

Back: Paths
Next: path_index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_endaction

Sets what to do when the instance reaches the end of the path.

Syntax:

path_endaction;

Returns: Constant.

Description

This variable can be used to get or to change the reaction of an instance when it reaches the end of the current path. Normally you would set this when you start the path using path_start but you may wish to change this behaviour depending on any number of events in your game. The available values are expressed using the following constants:

  • path_action_stop = stop the path
  • path_action_restart = continue from start position, jumping to the start if the path is not closed
  • path_action_continue = start the path again from the current position
  • path_action_reverse = reverse the speed of the path (run the path in reverse)

Example:

if path_endaction == path_action_stop
{
path_endaction = choose(path_action_restart, path_action_continue, path_action_reverse);
}

The above code will check the path end action and if it's set to stop, then a new path end action will be selected randomly.

Back: Paths
Next: path_start

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_orientation

Sets the rotation of the path.

Syntax:

path_orientation;

Returns: Real.

Description

This variable holds the current orientation of the path. When a path is created, its orientation is the default 0 degrees, but you can set this value to anything you wish using this. Remember that in GameMaker: Studio (unless you are using physics) the angles are calculated counter-clockwise, so setting the path orientation to 90° would rotate the path to the left.

Example:

mypath = path_duplicate(choose(path_1, path_2, path_3, path_4));
path_orientation = 90;

The above code duplicates a random, pre-made path resource into the variable "mypath". This new path is then rotated 90°.

Back: Changing Paths
Next: path_endaction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_position

The calling instance's position on its path

Syntax:

path_position;

Returns: Real

Description

This function can be used to get or to set the position of an instance along a path. The value is normalised from 0 - 1, so if you set it to, for example, 0.5, the instance will be moved to exactly the middle of the path.

Example:

path_position = random(1);

The above code sets the instance to a random position anywhere on the current path.

Back: Paths
Next: path_positionprevious

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_positionprevious

The calling instance's position on the path in the previous step.

Syntax:

path_positionprevious;

Returns: Real

Description

This variable can be used to get or to set the position of an instance along its current path in the previous step, and is a normalised value between 0 and 1 ie: 0 is the start position of the path and 1 would be the end position. It is similar to the xprevious and yprevious functions in how it works, only it is specific for paths. It can be useful for things like temporarily stopping a path follower if something is in the way (see the example code below).

Example:

var xx, yy;
xx = x + lengthdir_x(16, direction);
yy = y + lengthdir_y(16, direction);
if collision_circle(xx, yy, 16, obj_Player, false,true) path_position = path_positionprevious;

The above code checks an area in front of the instance for a collision with the object "obj_Player" and if there is one, it sets the instance back to the previous position it occupied on the current path.

Back: Paths
Next: path_speed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_scale

Sets (or gets) the scale of the path.

Syntax:

path_scale;

Returns: Real

Description

This value can be used to get or to set the scale of the currently assigned path for the instance, with a default value of 1. This is a scalar value, so 1 is a scale of 1:1, while setting it to 2, for example, will be double the scale and setting it to 0.5 would be halving the scale.

Example:

path_scale = 1 + random(2);

The above code will set the current path's scale to a random size between 1 (its original size) and 3 (3 times its original size).

Back: Paths
Next: path_orientation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_speed

The calling instance's speed at which it's following its path (in pixels per step).

Syntax:

path_speed;

Returns: Real.

Description

You can use this function to get or to set the speed of a path after it has been started. you can use negative values to signify that the instance should follow the path in reverse.

Example:

path_speed = -1 + random(2);

The above code will set the instance to travel the path at a random speed between -1 and 1.

Back: Paths
Next: path_scale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_start

Starts a path for the current instance.

Syntax:

path_start(path, speed, endaction, absolute);

Argument | Description
path | The path index to start.
speed | The speed of which to follow the path in pixels per step, negative meaning going backwards.
endaction | What to do when the end of the path is reached (see the constants listed below).
absolute | Whether the calling instance should follow the absolute path as it is in the editor (true) or a relative path to its current position (false).

Returns: N/A.

Description

A path is created from a series of defining points that are linked together and then used to plan the movements of an instance. They can be created with code, or in the Path Editor and they are assigned to an instance to use in the game. You would then use this function to tell your instance which path to follow, what speed to follow the path (measured in pixels per step), how to behave when it reaches the end of the path, and whether to follow the absolute or relative path position. This last part means that it either starts and follows the path exactly as you designed and placed it in the Path Editor (absolute), or it starts and follows the path from the position at which the instance was created (relative).

As you can see in the above image, the two instances are following the same path started with path_start(), but one of the instances is following the absolute path while the other is following the relative path. It should be noted that when relative is set to false (absolute) the instance will "jump" to the start of the path no matter where in the room it is placed.

The constants used to define the behaviour of the instance when it reaches the end of the path are as follows:

Constant | Description
path_action_stop | End the path
path_action_restart | Continue the path from the start, jumping to the start position again if the path is not closed
path_action_continue | Continue from the current position
path_action_reverse | Go backwards along the path again (achieved by reversing the path movement speed)

Example:

path_start(path, 4, path_action_reverse, 0);

This will make the calling instance follow the path indexed in the variable "path" at a speed of 4 pixels per step. It will follow the path relative to its own position, and when it reaches the end it will reverse direction and go back the way it came.

Back: Paths
Next: path_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Changing Paths

This section deals with the dynamic path functions

In GameMaker: Studio you are not just limited to the paths that you make using the Path Editor. There are a number of functions that can be used to manipulate and change those paths at run-time, or to even create new ones and then change and manipulate those.

The following functions are used for changing paths:

  1. path_add
  2. path_add_point
  3. path_change_point
  4. path_insert_point
  5. path_delete_point
  6. path_clear_points
  7. path_append
  8. path_assign
  9. path_delete
  10. path_duplicate
  11. path_flip
  12. path_mirror
  13. path_reverse
  14. path_rotate
  15. path_scale
  16. path_set_closed
  17. path_set_kind
  18. path_set_precision
  19. path_shift

Back: Paths

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_add

Adds an empty path and returns its index.

Syntax:

path_add();

Returns: Real.

Description

With this function you can create a path in GameMaker: Studio without using the path editor. this function will return the index of the path which should be stored in a variable and used as the reference for that path from then on. Please note that the created path is empty ie: it has no points defined, so you will then have to use the other available functions to add points to the path or be using mp_grids to generate the path. Once you have finished using the path, or wish to create a new one and store its index in the same variable you should first delete the old path with path_delete to prevent memory leaks which can eventually crash your game.

Example:

global.newpath = path_add();

This will create a new path and assign its index to global.newpath.

Back: Changing Paths
Next: path_add_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_add_point

Adds a point to the given path.

Syntax:

path_add_point(index, x, y, speed);

Argument | Description
index | The index of the path to add the point to.
x | The x coordinate of the new point.
y | The y coordinate of the new point.
speed | The speed factor of the point (default value is 100).

Returns: N/A

Description

With this function you can add a point to the specified path and set its speed factor. This point is added onto the end of the path, irrespective of the position of the point, and the factor is equal to the percentage of path_speed that the following instance actually goes at when it reaches this point in the path. If you wish to place a path point at some other position that is not the end, you should use path_insert_point.

Example:

path = path_add();
var i;
i = 0;
repeat(10)
{
path_add_point(path0, x + lengthdir_x(50, i), y+ lengthdir_y(50, i), 100);
i += 36;
}

The above code will create a circular path around the x/y position of the instance running the code.

Back: Changing Paths
Next: path_change_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_append

Joins two paths together.

Syntax:

path_append(index, path);

Argument | Description
index | The new index of the path.
path | The index of the path that will be appended to 'index'.

Returns: N/A

Description

With this code you can append one path onto another one, effectively joining them together, and for this to work, both paths must previously exist (either made in the path editor or created using path_add).

NOTE: This will not remove the path being appended from the resources. It is still there, only it now has no points in it and if you no longer wish to use it you should remove it with the function path_delete.

Example:

path_append(mypath, mppath); path_delete(mppath);

The above code appends the path data indexed in the variable "mppath" to the path indexed in the variable "mypath" and then deletes the "mppath" from memory.

Back: Changing Paths
Next: path_assign

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_assign

Duplicates an existing path.

Syntax:

path_assign(index, path);

Argument | Description
index | The index of the path to be overwritten.
path | The index of the path that will overwrite 'index'.

Returns: N/A

Description

With this function you can copy the path data from one path to another. The path being copied to will be cleared first (should it have any path points) and be completely overwritten by the path being copied from. Neither path is deleted in the process and the result is two paths, with two different indexes, but the exact same form and points.

Example:

mypath = path_add();
path_assign(mypath, choose(path_1, path_2, path_3));

The above code will create a new, empty path indexed in the variable "mypath" and then copy over the path data from one of the three available path resources.

Back: Changing Paths
Next: path_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_change_point

Changes an existing path points attributes.

Syntax:

path_change_point(index, n, x, y, speed);

Argument | Description
index | The index of the path to change the point of.
n | The defining point to change the attributes of.
x | The new x coordinate (relative to the path) of the point.
y | The new y coordinate (relative to the path) of the point.
speed | The new speed factor of the point.

Returns: N/A

Description

With this function you can change the position and/or the speed factor of any point previously defined for a path (the path can have been created in the path editor or through code using path_add).

Example:

for (var i = 0; i < path_get_number(path0); i ++)
{
var px = path_get_point_x(path0, i) + 32 - random(64);
var py = path_get_point_y(path0, i) + 32 - random(64);
path_change_point(path0, i, px, py, 100);
}

The above code loops through all the points in the path indexed as "path0" and re-positions all the points to a random position within an area of 64x64 pixels.

Back: Changing Paths
Next: path_insert_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_clear_points

Deletes all the points in a given path.

Syntax:

path_clear_points(index);

Argument | Description
index | The index of the path to clear.

Returns: N/A

Description

With this function you can remove all point definitions from a path, effectively making an "empty" path. This does not delete the path, for that you should use path_delete.

Example:

if path_get_number(mypath) > 0
{
path_clear_points(mypath);
}

The above code checks to see if there are any points on the path indexed in the variable "mypath" and if there are, it clears the path.

Back: Changing Paths
Next: path_append

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_delete

Deletes a given path.

Syntax:

path_delete(index);

Argument | Description
index | The index of the path to delete.

Returns: N/A

Description

You can use this code to remove a path from memory. If this path has been created dynamically using path_add, the variable that holds the path index will no longer be valid for accessing the path as it no longer exists, and if the path was created using the Path Editor that path can no longer be accessed in the whole game as you are permanently deleting it.

Example:

var t_path;
t_path = path_add();
if mp_grid_path(grid, t_path, x, y, obj_Player.x, obj_Player.y, 1)
{
path_assign(mypath, t_path);
}
path_delete(t_path);

The above code will create a path and store its index in a local variable. This path is then used to store an mp_grid_path generated path which, if it succeeds in finding its way to the target, it is then assigned to the path indexed in "mypath". Finally the "t_path" is deleted.

Back: Changing Paths
Next: path_duplicate

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_delete_point

Deletes a point from an existing path.

Syntax:

path_delete_point(ind, n);

Argument | Description
index | The index of the path to delete a point from.
n | The defining point to delete.

Returns: N/A

Description

With this function you can remove a point from the specified path. Path points are numbered from 0 so the first point is always the 0th point and the last path point will be path_get_number() - 1.

Example:

path_delete_point(mypath, path_number(mypath) - 1);

This would delete the last point on the path indexed in the variable "mypath".

Back: Changing Paths
Next: path_clear_points

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_duplicate

Duplicates an existing path, returning its index.

Syntax:

path_duplicate(index);

Argument | Description
index | The index of the existing path to duplicate.

Returns: Real

Description

This function takes a path and copies it into a new path. The new path is created in the process, and the index is returned to be used in all further calls to use this new path.

Example:

mypath = path_duplicate(choose(path_1, path_2, path_3, path_4));

The above code chooses one of four path resources and duplicates it, storing the index of the new path in the variable "mypath".

Back: Changing Paths
Next: path_flip

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_flip

Flips the given path along the horizontal axis with respect to its center.

Syntax:

path_flip(index);

Argument | Description
index | The index of the path to flip.

Returns: N/A

Description

This function takes all the path points and flips them along the horizontal axis. This function changes the actual path resource, and so will permanently affect how the path is used by all instances in the game from the moment the function is used until the end of the game.

Example:

path_flip(mypath);

This would flip "mypath" along the horizontal axis.

Back: Changing Paths
Next: path_mirror

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_insert_point

Inserts a point into the given path at a set position.

Syntax:

path_insert_point(index, n, x, y, speed);

Argument | Description
index | The index of the path to insert the point into.
n | The defining point to insert the new point BEFORE.
x | The x coordinate (relative to the path) of the new point.
y | The y coordinate (relative to the path) of the new point.
speed | The speed factor of the point.

Returns: N/A

Description

With this function you can insert a new point into a path (the path can have been created in the path editor or through code using path_add). The point will be added into the path before the point "n" that is specified in the function.

Example:

path_insert_point(mypath, 0, 50, 50, 100);

This will insert a point at the very beginning of the path indexed in the variable "mypath", at (50,50), with a speed factor of 100%.

Back: Changing Paths
Next: path_delete_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_mirror

Flips the given path along the vertical axis with respect to its center.

Syntax:

path_mirror(index);

Argument | Description
index | The index of the path to mirror.

Returns: N/A

Description

This function takes all the path points and mirrors them along the vertical axis. This function changes the actual path resource, and so will permanently affect how the path is used by all instances in the game from the moment the function is used until the end of the game.

Example:

path_mirror(mypath);

This would mirror "mypath" along the vertical axis.

Back: Changing Paths
Next: path_reverse

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_rescale

Scales the given path with respect to its center.

Syntax:

path_rescale(index, xscale, yscale);

Argument | Description
index | The index of the path to scale.
xscale | What to multiply the current horizontal scale by. Default scale is 1.
yscale | What to multiply the current vertical scale by. Default scale is 1.

Returns: N/A

Description

This function can be used to rescale the given path along both (or either) the vertical and horizontal axis, basically moving each of the path points to a new position corresponding to this scale around the centre of the path. This function changes the actual path resource, and so will permanently affect how the path is used by all instances in the game from the moment the function is used until the end of the game.

Example:

path_rescale(path0, 3, 3);

This would rescale path0 to three times its original size.

Back: Changing Paths
Next: path_set_closed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_reverse

Reverses the given path.

Syntax:

path_reverse(index);

Argument | Description
index | The index of the path to change.

Returns: N/A

Description

With this function you can reverse the order in which the individual path points are numbered, so, for example, if the path has 5 points, point 0 would become point 4, point 1 would be point 3 and point 2 would not be changed. The actual position of the points remains the same, only the order in which they are processed is changed. This function changes the actual path resource, and so will permanently affect how the path is used by all instances in the game from the moment the function is used until the end of the game.

Example:

path_reverse(path0);

This would reverse the order in which all points on the path indexed in "path0" are processed.

Back: Changing Paths
Next: path_rotate

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_rotate

Rotates the given path with respect to its center.

Syntax:

path_rotate(index, angle);

Argument | Description
index | The index of the path to flip.
angle | The angle of rotation degrees.

Returns: N/A

Description

You can use this function to rotate a given path around its center. Remember that in GameMaker: Studio (unless you are using physics) the angles are calculated counter-clockwise, so rotating the path by 90 degrees would rotate the path to the left. This function changes the actual path resource, and so will permanently affect how the path is used by all instances in the game from the moment the function is used until the end of the game.

Example:

path_rotate(path0, 90);

This would rotate path0 90 degrees counterclockwise.

Back: Changing Paths
Next: path_rescale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_set_closed

Flags the given path as being closed or open.

Syntax:

path_set_closed(index, closed);

Argument | Description
index | The index of the path to change.
closed | Whether the path is closed (true) or not (false).

Returns: N/A

Description

This function can be used to flag a given path as being open (false) or closed (true). A closed path has its start point connected to its end point, forming a loop, and an open path has a definitive, unconnected start and finish. This function changes the actual path resource, and so will permanently affect how the path is used by all instances in the game from the moment the function is used until the end of the game.

Example:

path_set_closed(path0, true);

This will set the path indexed in the resource "path0" to be a closed path.

Back: Changing Paths
Next: path_set_kind

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_set_kind

Sets the kind of connections of the path with the given index.

Syntax:

path_set_kind(index, val);

Argument | Description
index | The index of the path to change.
val | The kind of the path, 0 for straight or 1 for smooth.

Returns: N/A

Description

This function can be used to set the kind of path that you wish the specified resource to be. This can be either a straight line path (set to 0) or a smoothed path (set to 1) in which case the path precision has to be taken into account too (the precision can be set too using path_set_precision). This function changes the actual path resource, and so will permanently affect how the path is used by all instances in the game from the moment the function is used until the end of the game.

Example:

path_set_kind(path0, 1);

This will set path0 to be a smoothed path.

Back: Changing Paths
Next: path_set_precision

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_set_precision

Sets the precision of the given path.

Syntax:

path_set_precision(index, prec);

Argument | Description
index | The index of the path to change.
prec | The precision of the path. Must be an integer between 1 and 8.

Returns: N/A

Description

With this function you can change the "smoothness" of a path. This value must be between 1 and 8, with a low value creating straighter edges with sharper curves between points, while a higher value will round the points and make the path a lot more "curvy". Note that this function will have no visible effect if the path has not been set to smooth in the path editor or using the function path_set_kind. This function changes the actual path resource, and so will permanently affect how the path is used by all instances in the game from the moment the function is used until the end of the game.

Example:

path_set_precision(path0, 2);

This will set path0's precision to 2.

Back: Changing Paths
Next: path_shift

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_shift

Shifts the given path any number of pixels horizontally and vertically.

Syntax:

path_shift(index, xshift, yshift);

Argument | Description
index | The index of the path to change.
xshift | The number of horizontal pixels to shift the path. Negative=left, positive=right.
yshift | The number of vertical pixels to shift the path. Negative=up, positive=down.

Returns: N/A

Description

With this function you can shift a path along the horizontal and vertical axis. Please note that this will have no visible effect in-game if the instance following the path being shifted follows it relatively (rather than absolutely) as the path's position is disregarded then. This function changes the actual path resource, and so will permanently affect how the path is used by all instances in the game from the moment the function is used until the end of the game.

Example:

path_shift(mypath, 50, 50);

This would shift path0 50 pixels right, and 50 pixels upwards.

Back: Changing Paths

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Path Information

This section deals with the functions to get path information

Often you will need to get specific information about a path that is in the resource tree or that has been created dynamically. GameMaker: Studio provides the following functions to give you information about a path:

  1. path_exists
  2. path_get_closed
  3. path_get_kind
  4. path_get_length
  5. path_get_name
  6. path_get_number
  7. path_get_point_speed
  8. path_get_point_x
  9. path_get_point_y
  10. path_get_precision
  11. path_get_speed
  12. path_get_x
  13. path_get_y

Back: Paths
Next: Changing Paths

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_exists

Returns whether a path with the given index exists or not.

Syntax:

path_exists(index);

Argument | Description
index | The index of the path to check for.

Returns: Boolean.

Description

This function returns whether a path with the given index exists or not. Note that if you check for the existence of a path through a variable that has yet to have been declared, this will throw an error.

Example:

if path_exists(path0)
{
path_start(path0, 4, path_action_reverse, 0);
}

This will start path0, if it exists.

Back: Path Information
Next: path_get_closed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_closed

Returns the closed status of a given path.

Syntax:

path_get_closed(index);

Argument | Description
index | The index of the path to check.

Returns: Boolean.

Description

This function can be used to return whether the path is flagged as closed (true) or open (false), ie whether the path loops or if it has a definitive beginning and end.

Example:

state = path_get_closed(c_path)

This will set "state" to either true or false depending on the closed state of the path indexed in "c_path".

Back: Path Information
Next: path_get_kind

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_kind

Returns whether a path is smooth or straight.

Syntax:

path_get_kind(index);

Argument | Description
index | The index of the path to check.

Returns: Boolean.

Description

Paths can be either smooth or straight (a smooth path calculates a curved path around the defining points, whereas a straight path just goes straight from one point to another). This function can be used to find out whether the given path is smooth (true) or not (false).

Example:

kind = path_get_kind(c_path);

This will set "state" to either true or false depending on the state of path0.

Back: Path Information
Next: path_get_length

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_length

Returns the length, in pixels, of a given path.

Syntax:

path_get_length(index);

Argument | Description
index | The index of the path to measure.

Returns: Real.

Description

You can use this function to get the exact length of a path in pixels. this is not an approximate length from point to point, but rather an exact length along the shape of the path, even when the path is smooth with a high curved precision.

Example:

len = path_get_length(c_path);

This will set "len" to the total length of the path indexed in "c_path" in pixels.

Back: Path Information
Next: path_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_name

Returns the name of a given path.

Syntax:

path_get_name(index);

Argument | Description
index | The index of the path to check.

Returns: String.

Description

This function will return the name of the path that is referenced as a string. The name is whatever has been used to define the path in the editor or (if the path has been created through a code function) it will return a string with the format "_newpathXX" where "XX" is the number of the path generated, starting at 0 and incrementing by one every time a new path is created. Please note that this is only a string and cannot be used to reference the path directly - for that you would need the path index. You can, however, use this string to get the path index using the returned string along with the function asset_get_index().

Example:

name = path_get_name(mypath);

This will set "name" to the name of the path indexed in the variable "mypath".

Back: Path Information
Next: path_get_number

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_number

Returns the number of points on a path

Syntax:

path_get_number(index);

Argument | Description
index | The index of the path to check.

Returns: Real.

Description

This function can be used to return the number of points on a path.

Example:

if path_get_number(ai_path) > 1
   {
   path_start(ai_path, 4, 3, 0);
   }

The above code checks to see if a path has more than one point on it and if so it starts the instance moving along that path.

Back: Path Information
Next: path_get_point_speed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_point_speed

Returns the speed setting of a given path's given defining point.

Syntax:

path_get_point_speed(index, n);

Argument | Description
index | The index of the path to check.
n | The point identity to check.

Returns: Real.

Description

With this function you can get the speed of the point (as defined in the Path Editor or when you dynamically add a path point using path_add_point()) expressed as a percentage. So, if you have a path point set to 50 in the path editor, this function would return 50 when used.

Example:

if path_get_point_speed(c_path, 0) != 100
{
path_change_point(c_path, 0, path_get_point_x(c_path, 0), path_get_point_x(c_path, 0), 100);
}

the above code checks the path point "0" of the path indexed by "c_path" to see if the speed is not equal to 100. If it is not then it sets the speed of that point to 100.

Back: Path Information
Next: path_get_point_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_point_x

Returns the x coordinate of a given path's given defining point.

Syntax:

path_get_point_x(index, n);

Argument | Description
index | The index of the path to check.
n | The point identity to check.

Returns: Real.

Description

This function will return the x position (in room coordinates) of the point that you input for the path that you index. If the point is outside of the range of the path (ie: a path has 8 points and you ask for the x position of point 10) then a value of 0 will be returned.

Example:

if path_position = 1
{
var i;
i = floor(random(path_get_number(mypath)));
x = path_get_point_x(mypath, i);
y = path_get_point_y(mypath, i);
path_position = (1 / path_get_number(mypath)) * i;
}

The above code will check to see if an instance is at the end of a path. If it is it will then choose a random point on the path and move the instance to that point.

Back: Path Information
Next: path_get_point_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_point_y

Returns the y coordinate of a given path's given defining point.

Syntax:

path_get_point_y(index, n);

Argument | Description
index | The index of the path to check.
n | The point identity to check.

Returns: Real.

Description

This function will return the y position (in room coordinates) of the point that you input for the path that you index. If the point is outside of the range of the path (ie: a path has 8 points and you ask for the y position of point 10) then a value of 0 will be returned.

Example:

if path_position = 1
{
var i;
i = floor(random(path_get_number(mypath)));
x = path_get_point_x(mypath, i);
y = path_get_point_y(mypath, i);
path_position = (1 / path_get_number(mypath)) * i;
}

The above code will check to see if an instance is at the end of a path. If it is it will then choose a random point on the path and move the instance to that point.

Back: Path Information
Next: path_get_precision

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_precision

Returns how precise the given path is.

Syntax:

path_get_precision(index);

Argument | Description
index | The index of the path to check.

Returns: Real.

Description

This function returns with what precision the given path has been "smoothed", and will be an integer value from 1 to 8. Although you can get (and set) this value for a straight-line path it will have no influence over how an instance uses the path as it is only relevant when the path kind is set to "smooth".

Example:

if path_get_kind(mypath)
{
if path_get_precision(mypath) !=8 path_set_precision(mypath, 8);
}

The above code checks the path indexed in "mypath" to see what kind it is and if it is smooth, it then checks how precise the smoothing is. If it is less than 8, it is then set to a value of 8.

Back: Path Information
Next: path_get_speed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_speed

Returns the speed factor of a given path's given position.

Syntax:

path_get_speed(ind, pos);

Argument | Description
index | The index of the path to check.
pos | How far through the path to check. Between 0 (start) and 1 (end), can be decimal.

Returns: Real.

Description

This function returns the speed factor of any given position on a path. The position should be a value between 0 and 1 (you can use path_position, for example, if you need the current position of the instance) with 0 being the start position and 1 being the end. The value returned will be the factor by which the actual path_speed is being set. For example, on a path with only two points, 0 and 1, where the point 0 speed factor is 100 and point 1 speed factor is 0, the function path_get_speed(path, 0.5) will return 50.

Example:

speed = path_get_speed(path0, 0.5) / 20;

This will set the calling instance's speed to the speed factor of the point at exactly halfway through path0, divided by 20. So if the speed factor found is the default 100, it will set the speed of the calling instance to 5.

Back: Path Information
Next: path_get_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_x

Returns the x coordinate of a given path's given position.

Syntax:

path_get_x(ind, pos);

Argument | Description
index | The index of the path to check.
pos | How far through the path to check. Between 0 (start) and 1 (end).

Returns: Real.

Description

With this function you can get the x coordinate of a position on any given path. 0 is the start of the path, 1 is the end of the path, and anything in between equates to that far through the path. This needn't be a defining point of the path, it can be anywhere on it.

Example:

x = path_get_x( path0, 0.5 );

This will set the calling instance's x to the x coordinate of the point at exactly halfway through path0.

Back: Path Information
Next: path_get_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


path_get_y

Returns the y coordinate of a given path's given position.

Syntax:

path_get_y(ind, pos);

Argument | Description
index | The index of the path to check.
pos | How far through the path to check. Between 0 (start) and 1 (end).

Returns: Real.

Description

With this function you can get the y coordinate of a position on any given path. 0 is the start of the path, 1 is the end of the path, and anything in between equates to the normalised distance along the length of the path. This value needn't be a defining point of the path, it can be anywhere on it.

Example:

y = path_get_y( path0, 0.5 );

This will set the calling instance's y to the y coordinate of the point at exactly halfway through path0.

Back: Path Information
Next: path_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Physics Functions

GameMaker: Studio has extensive, yet easy to use, physics functions based on the Box2D and Liquid Fun open source physics libraries.

The integration of a dedicated physics library to GameMaker: Studio means that you can now take control over all aspects of the physical behaviour of objects within your game world, particularly collisions and object interaction. The "traditional" collision system (which GameMaker: Studio defaults to) is a "reactive" system, where you check for a collision and then react to that collision with code that you place in individual objects. This is fine for simple games, but when you have a large number of objects and have to code how they all react to different situations in the game world, it quickly becomes obvious that this system is just not enough! That's when you have to turn to the GameMaker: Studio physics system!

The physics system works in a very different way to normal collisions. It is more of a "passive" system where you define a series of properties for your objects in the game world, as well as the properties of the game world itself, before any collisions or interactions occur. These coded "rules" will then govern the way everything in your game world interacts. In this way, with a few simple code and the correct room setup, you can create very complex interactions between objects and the world which will occur and resolve without you having to code for every single possible outcome.

There are a few things that you should note when working with the GameMaker: Studio physics world:

  • The physics system exists "apart" from the basic room and instance structure of GameMaker: Studio meaning that its timings and functions are not necessarily tied into the room speed and step order like everything else.

  • The physics system replaces many of the normal instance functions... for example, rather than set a speed and a direction for an instance, if it has been declared as being a fully simulated physical body, you would use a force or impulse to get it to move around in the game world, or if it is not physics enabled you will need to set the x an y positions yourself. This takes a bit of getting used to, so experiment with the physics functions and get to know how everything works before trying to integrate them into your project.

  • You should limit the number of instances that are created, as well as the number of collisions and collision groups that the physics world has to deal with. You cannot have thousands of instances, all with physical properties and collisions and expect everything to work fine due to the fact that physics requires some pretty intensive calculations, so limit yourself and optimise where possible.

  • When setting up collisions, use parents as much as possible since the collision system has a limited number of collision bits available to assign to instances for Box2D to detect collisions. For example, if you have five different wall objects, don't check for five collisions, rather, create a parent object and assign it to the five walls then have ONE collision check with the parent. The physical properties of the objects are not inherited only the collisions. In this way you can keep your game optimised and error free.

  • Try not to move instances from one point of the room to another in any way other than using the physics functions (ie: do not set the x/y coordinates manual). Although this can be done and in some circumstances it may be necessary, this is generally to be avoided due to the unpredictable results that it may have on the physics engine, especially when trying to resolve collisions.

  • Care should be taken when binding fixtures, as they can be bound to objects and instances independently. This means that if you bind a fixture to (for example) "o_Wall", all instances of that object will get the fixture. If you only want to bind a fixture to one instance, then use that instance's id in the appropriate function.

  • Please be aware that due to differences in floating point precision you may find that versions of your game for different target platforms may exhibit subtly different behaviour to the standard Windows version, though each version will be self-consistent across subsequent executions.

  • To prevent instabilities in the physical simulation Box2D constrains to upper limits the amount a body may rotate and translate within a single update. The apparent limitations will vary according to the accuracy of the physical simulation in accordance with the number of updates and update speed of the physics world, and also in accordance with the physics world scaling. This means that (for example) if you have a world update speed of 60, the maximum movement speed would be 20.

Information on the physics functions can be found on the following pages:

  1. The Physics World
  2. Forces
  3. Fixtures
  4. Joints
  5. Soft Body Particles
  6. Physics Variables

Finally, there are a couple of special physics functions which may be useful for more advanced physics simulations. The first is for testing for possible collisions at a specific point in the room, and the second is for generating custom mass and inertia properties within an instance:

  1. physics_test_overlap
  2. physics_mass_properties

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_mass_properties

With this you can apply specific mass properties to a fixture.

Syntax:

physics_mass_properties(mass, local_center_x, local_center_y, inertia)

Argument | Description
mass | The new mass that you want the fixture to have.
local_center_x | The local x coordinate of the new center of mass.
local_center_y | The local y coordinate of the new center of mass.
inertia | Set the inertia for the fixture.

Returns: N/A

Description

This function can be used to set custom mass and inertia values for a physics enabled instance. Normally the mass, center of mass, and inertia for an instance is calculated using a combination the surface area of the bound fixtures and their density. However in very special occasions you may need to offset the center of mass or change the inertia and that is when you would use this function. Bear in mind that the mass is calculated in real world weight (ie:kilograms) and you should always try and keep values realistic for what you are modelling. So if your physics object is meant to represent a person, their mass would be approximately 70 kilos.

The center of mass is calculated automatically for you based on the shape of the fixture (or fixtures) you have defined. To get a general idea of where this could be, if you have a sprite that is the same shape as the fixtures you wish to create, then select the "center origin" option you will see approximately where the center of mass will be too. However, this may not be correct or you may be looking for a specific effect from your physics object, in which case this function can also be used to change the x and y coordinates for the center of mass. These are local values, so 0,0 is the point at which the fixtures are bound to the instance (the origin of the instance). So a center of mass of -4,0 would shift the center of mass to the left of the origin.

As for the inertia, this basically defines how resistant the instance is to changes in its direction and velocity, so a higher inertia makes it more resistant and a low inertia makes it less resistant (inertia and mass cannot be negative values!).

NOTE: This function does not set mass and inertia for individual fixtures, but rather for the whole physics enabled instance, no matter how many fixtures are bound to it.

NOTE: This function should only be used when necessary as the physics simulation is designed for the mass and inertia to be optimal based on the density and size of the fixture. Changing these values can have unforeseen effects.

Example:

physics_mass_properties(phy_mass, -10, -10, phy_inertia);

The above code will shift the center of mass of the physical body to the left.

Back: Physics Functions
Next: physics_test_overlap

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_test_overlap

Checks for an overlap of two fixtures at a given position.

Syntax:

physics_test_overlap(xpos, ypos, angle, obj);

Argument | Description
xpos | The x position in the room to check
ypos | The y position in the room to check
angle | The angle to check (of the calling instance)
obj | The object to check for

Returns: Boolean.

Description

This function can be used to check and see if a physical body (ie: the fixture of an instance) overlaps, or will overlap, when rotated and placed at a given position in the room. the "angle" argument is the angle of rotation that the calling instance has (or will have) at the position to be checked, and the "obj" argument can be either a single instance id, and object index or the keywords all or other.

Example:

if physics_test_overlap(x+20, y-35, 0, obj_Bomb)
{
alarm[0] = room_speed;
ignited = true;
}

The above code will check a position for a physics fixture overlap, and if there is one, it sets a variable and an alarm.

Back: Physics Functions
Next: physics_mass_properties

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Fixtures

The GameMaker: Studio physics system has a number of functions for defining fixtures which can then be applied to instances.

Before an instance in GameMaker: Studio can have physical properties it must have a fixture assigned to it. A fixture binds a shape or form to the instance and this adds material properties such as density, friction, and restitution. Fixtures can be boxes, circles, polygons or any other simple shape you wish as GameMaker: Studio provides functions that enable you to define your own shape point by point, and then once you have your shape you can go ahead and define its physical properties too. These properties are what govern the way the instance with the fixture assigned to it will react with other instance in the physics world and are listed below:

  • Density: A material's density is defined as its mass per unit volume. It is, essentially, a measurement of how tightly matter is crammed together. If you wish your fixture to be static (ie: immovable) then the density should be set to 0, essentially making it infinitely dense. Kinematic objects that move with constant velocity and are not physically affected by collisions are also defined using a density of 0.

  • Friction: Friction is the force resisting the relative motion of solid surfaces, fluid layers, and material elements sliding against each other.

  • Linear Damping: This is the generalised force that causes a moving object to lose momentum. In the "real world" things don't generally happen forever. For example, A paper aeroplane will fly for a short while but eventually it will fall due to the air friction that acts upon it causing it to slow down. In the physics world that we create such things are difficult to model and so each fixture is given its own linear damping to simulate this type of "generalised friction".

  • Angular Damping: As above, this is a generalised force that is applied to an object to stop it spinning eternally.

  • Restitution: In physics, restitution is defined as "the return of an object or system to its original state after elastic deformation", but as the fixtures in the GameMaker: Studio are really rigid bodies and cannot be deformed, think of this as basically how "bouncy" the fixture is.

So as you can see, with just a few simple functions, GameMaker: Studio can help you to create complex systems and interactions which will give your games an unprecedented sense of realism.

Note: You can define one fixture and have it bound to multiple instances (think of a pool table, where all the balls have the same physical properties, yet each one is a discreet entity)

Creating Fixtures

The following functions are for creating, binding, setting collisions and then deleting fixtures:

  1. physics_fixture_create
  2. physics_fixture_bind
  3. physics_fixture_bind_ext
  4. physics_fixture_set_collision_group
  5. physics_fixture_delete
  6. physics_remove_fixture

Defining Fixture Shapes

A fixture must be given a shape or else it will not be detected by the physics world, and this shape can be defined by the following functions:

  1. physics_fixture_set_box_shape
  2. physics_fixture_set_circle_shape
  3. physics_fixture_set_edge_shape
  4. physics_fixture_set_chain_shape
  5. physics_fixture_set_polygon_shape
  6. physics_fixture_add_point

Fixture Properties

In order for your physics enabled instance to react properly to the world around it, the fixtures you use must have specific properties defined that will give the fixture bounce, friction, mass etc... The following functions are used to set these properties of the fixture:

  1. physics_fixture_set_density
  2. physics_fixture_set_friction
  3. physics_fixture_set_linear_damping
  4. physics_fixture_set_angular_damping
  5. physics_fixture_set_restitution
  6. physics_fixture_set_sensor
  7. physics_fixture_set_kinematic
  8. physics_fixture_set_awake

You can also set certain properties of the fixture after it has been bound to an instance. When binding the "base" fixture, you can choose to store the unique index for the bound physical properties in a variable. This can then be used in the following functions to change certain properties, or to get the current values for them:

  1. physics_get_friction
  2. physics_get_density
  3. physics_get_restitution
  4. physics_set_friction
  5. physics_set_density
  6. physics_set_restitution
  7. physics_mass_properties

Back: Physics Functions
Next: Joints

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_add_point

This function adds a point to create polygon shape or a chain shape for a fixture.

Syntax:

physics_fixture_add_point(fixture, xpos, ypos)

Argument | Description
fixture | the index of the fixture
xpos | the x position of the point (relative to the fixture origin for polygon shapes)
ypos | the y position of the point (relative to the fixture origin for polygon shapes)

Returns: N/A

Description

This function defines the points of a polygon which has previously been set to the fixture using either physics_fixture_set_polygon_shape or it can be used to add points to a chain of edge fixtures using the functionphysics_fixture_set_chain_shape. For a polygon shape, the points are relative to the origin of the fixture, with the 0,0 position of the x/y axis being the centre, and the subsequent coordinates being calculated as usual in GameMaker: Studio with down/right being +x,+y and up/left being -x,-y. Here is an illustration to help you visualise this process:

As you can see, any simple convex polygon can be modelled in this way, but concave polygons are not supported at this moment. Finally, to close the polygon, you must bind the fixture to an instance. You should note too that you must also have at least three points defined for your polygon before binding it to an instance or you will get an error and that adding a point to a fixture that does not have a polygon shape set previously will also cause an error. Note too that the maximum number of points permitted for a fixture is eight.

For chain shapes (which are simply a series connected edge shapes) this function will set a point as a "connection" to chain the edges together at. Therefore you need to have defined at least two points before binding the fixture to the instance otherwise you will get an error. However, unlike for polygons, you are not limited to a maximum of eight points and can add as many as you require to create the chain and the points are defined in actual room coordinates, rather than relative to the instance.

Example:

physics_fixture_set_polygon_shape(fix_Ship);
physics_fixture_add_point(fix_Ship, 0,0);
physics_fixture_add_point(fix_Ship, -40, 100);
physics_fixture_add_point(fix_Ship, 40, 100);

The code above will apply a polygon shape to the fixture indexed in the variable "fix_Ship" and then defines three points to create a triangular shape.

Back: Fixtures
Next: physics_fixture_set_density

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_bind

This function binds a fixture to an instance.

Syntax:

physics_fixture_bind(fixture, target)

Argument | Description
fixture | the fixture that is to be bound
target | the target instance that is to receive the fixture (can be an instance id, an object id, other, or all)

Returns: Real

Description

Once we have defined our fixture it has to be bound to an instance. This means that its properties are transferred to the selected instance, not the actual fixture itself, so that one fixture can be bound to multiple instances if all are to have the same properties. You can specify an object index for the target and all instances present in the room at the time will receive that fixtures properties (but not any new instances of the object created later), or you can use the special keywords other and all. You can even specify a parent object and all children instances with that parent will also receive the fixture. Once the fixture has been bound to all the instances that you need, it can be deleted if no longer necessary and the instances with that fixtures properties will not be affected and maintain those properties.

The fixture will be bound to the instance with the center of mass being positioned at the origin of the instance, and polygon fixtures are bound based on the position of the points relative to the origin. If you require your fixture to be bound to a point other than the origin then you should be using physics_fixture_bind_ext. The function will also return a unique "id" value for the bound fixture (not the fixture itself) which can then be used to remove ("un-bind") the physics properties from the instance using the function physics_remove_fixture. This permits you to add and remove physical properties from an instance without destroying and re-creating objects.

Note: Fixtures should be deleted when no longer needed as failure to do so may cause a memory leak which will slow down and eventually crash your game.

Example:

var fix, inst;
fix = physics_fixture_create();
physics_fixture_set_circle_shape(fix, 16);
physics_fixture_set_density(fix, 1.0);
inst = instance_create(x, y, genericBodyObject);
my_fix = physics_fixture_bind(fix, inst);
physics_fixture_delete(fix);

The code above will create a fixture and assign its index to the variable "fix". It then defines the shape and density of the fixture before binding it to the instance that was created with the index for the bound fixture stored in the variable "my_fix". Finally, the fixture is deleted to prevent memory leaks as it is no longer needed.

Back: Fixtures
Next: physics_fixture_bind_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_bind_ext

This function binds a fixture to an instance, offsetting its x or y position by a given amount.

Syntax:

physics_fixture_bind_ext(fixture, target, xoffset, yoffset)

Argument | Description
fixture | the fixture that is to be bound
target | the target instance that is to receive the fixture (can be an instance id, an object id, other, or all)
xoffset | the offset along the x-axis
yoffset | the offset along the y-axis

Returns: Real

Description

Once we have defined our fixture it has to be bound to an instance. This means that its properties are transferred to the selected instance, not the actual fixture itself, so that one fixture can be bound to multiple instances if all are to have the same properties. You can specify an object index for the target and all instances present in the room at the time will receive that fixtures properties (but not any new instances of the object created later), or you can use the special keywords other and all. You can even specify a parent object and all children instances with that parent will also receive the fixture. Once the fixture has been bound to all the instances that you need, it can be deleted if no longer necessary and the instances with that fixtures properties will not be affected and maintain those properties.

Normally, the fixture will be bound to the instance with the center of mass being positioned at the origin of the instance, however this is not always what you require and so this function also permits you to offset the x and y position where the fixture is bound by a given amount (if you do not require this then use physics_fixture_bind instead). It is important to note that a fixture can only support a single offset, as adding multiple offsets to a single fixture is not supported by Box2D. The function will also return a unique "id" value for the bound fixture (not the fixture itself) which can then be used to remove ("un-bind") the physics properties from the instance using the function physics_remove_fixture. This permits you to add and remove physical properties from an instance without destroying and re-creating objects.

Note: Fixtures should be deleted when no longer needed as failure to do so may cause a memory leak which will slow down and eventually crash your game.

Example:

var fix, inst;
fix = physics_fixture_create();
physics_fixture_set_circle_shape(fix, 16);
physics_fixture_set_density(fix, 1.0);
inst = instance_create(x, y, genericBodyObject);
my_fix = physics_fixture_bind_ext(fix, inst, sprite_width / 2, -(sprite_height / 2));
physics_fixture_delete(fix);

The code above will create a fixture and assign its index to the variable "fix". It then defines the shape and density of the fixture before binding it to the instance at an offset based on the width and height of the sprite. The index for the bound fixture is stored in the variable "my_fix". Finally, the fixture itself is deleted to prevent memory leaks as it is no longer needed.

Back: Fixtures
Next: physics_fixture_set_collision_group


physics_fixture_create

This function creates a fixture and returns the id of that fixture to be used in all further calls.

Syntax:

physics_fixture_create()

Returns: Index of the fixture

Description

The first step in setting up a fixture is creating it with this function. The returning index should be stored in a variable to be used in all further functions that are used to define and use this fixture.

Example:

fix_Ball = physics_fixture_create();

The code above will create a fixture and store its index in the variable "fix_Ball";

Back: Fixtures
Next: physics_fixture_bind

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_delete

This function deletes a fixture from memory.

Syntax:

physics_fixture_delete(fixture)

Argument | Description
fixture | the fixture that is to be deleted from memory

Returns: N/A

Description

Since once a fixture has been bound to an instance that instance maintains the fixtures properties, we can remove the fixture from memory with this function, particularly if we no longer plan to use it again. Please note that failure to remove fixtures after they are no longer needed may cause a memory leak which will slow down and eventually crash your game, so you should take care to clean up properly after defining and binding fixtures.

Example:

var fix, inst;
fix = physics_fixture_create();
physics_fixture_set_circle_shape(fix, 16);
physics_fixture_set_density(fix, 1.0);
inst = instance_create(x, y, genericBodyObject);
physics_fixture_bind(fix, inst);
physics_fixture_delete(fix);

The code above will create a fixture and assign its index to the variable "fix". It then defines the shape and density of the fixture before binding it to the instance that was created with the index stored in the variable "inst". Finally, the fixture is deleted to prevent memory leaks as it is no longer needed.

Back: Fixtures
Next: physics_remove_fixture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_angular_damping

This function sets the angular damping value of a fixture.

Syntax:

physics_fixture_set_angular_damping(fixture, damping)

Argument | Description
fixture | the index of the fixture
damping | the angular damping of the fixture, usually between 0 and 1

Returns: N/A

Description

If you think about any rotating object in the "real world", unless it has a motor or is in space, it slows down over time due to the influence of external forces (like friction with the air around it). We can use the function physics_fixture_set_angular_damping() in GameMaker: Studio to simulate this effect and reduce the velocity of rotation of instances in the physics world, as, without it, any rotating instance would continue to rotate infinitely. Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity meaning full damping. Normally you will use a damping value between 0 and 1.

Example:

physics_fixture_set_angular_damping(fix_Ball, 0.1);

The code above will set the angular damping of the fixture indexed in "fix_ball" to 0.1.

Back: Fixtures
Next: physics_fixture_set_restitution

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_awake

This function tells GameMaker: Studio that the fixture is to be treated as awake or not.

Syntax:

physics_fixture_set_awake(fixture, state)

Argument | Description
fixture | the index of the fixture
flag | whether a fixture is awake (true) or not (false)

Returns: N/A

Description

When you start a room with physics, or bind fixtures to instances, the fixtures are always considered to be "awake"... that is to say, they are processing events and interacting with the surrounding instances. However this can sometimes lead to problems, especially if you have a number of instances with fixtures that are side by side when a room starts (think of a tower made of various instances with fixtures) as with them being "awake" they will move and possibly change position due to the sudden start of gravity and collisions affecting them. In these cases you can use this function to flag the fixture as been "asleep", in which case it will not be processing anything when it is first created in the room.

Example:

physics_fixture_set_awake(fix_Cloud, true);

The code above flag the fixture as being "awake" when bound to an instance.

Back: Fixtures
Next: physics_get_friction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_box_shape

This function sets the shape of the fixture to that of a box (rectangle) with the specified dimensions.

Syntax:

physics_fixture_set_box_shape(fixture, halfWidth, halfHeight)

Argument | Description
fixture | the index of the fixture
halfWidth | the half width of the box
halfHeight | the half height of the box

Returns: N/A

Description

This function defines a box shape for your fixture. It takes the half width and height as the physics world uses this value far more than whole width/height values to determine things like collisions.

Example:

physics_fixture_set_box_shape(fix_Border, room_width/2, 10);

The code above will apply a box shape to the fixture indexed in the variable "fix_Border" with a width of the room and a height of 20 pixels.

Back: Fixtures
Next: physics_fixture_set_circle_shape

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_chain_shape

This function sets the shape of the fixture to that of a chain.

Syntax:

physics_fixture_set_chain_shape(fixture, loop)

Argument | Description
fixture | The index of the fixture
loop | Whether to close the chain (true) or not (false).

Returns: N/A

Description

This function defines a "chain" fixture shape. A chain fixture is comprised of a number of points, which are then connected together using edge shapes to join them. The function itself takes the index (ID) of the fixture and can tell the fixture to loop or not. Setting this to true will connect the last point to the first point with an edge, while setting it to false will not. Note that this function on prepares the fixture to accept the points required to make the chain, and these should be added after calling this function using physics_fixture_add_point, much as you would when building a polygon fixture.

When creating a chain fixture, you must give it at least two points but you are not limited in the number of subsequent points that you can add to make up the finished fixture.

Example:

var xx = -100;
var yy = room_height / 2;
var fix = physics_fixture_create();
physics_fixture_set_chain_shape(fix, false);
for (var i = 0; i < 10; i++;)
{
physics_fixture_add_point(fix, xx, yy);
xx += 50 + random(150);
yy = (room_height / 2) - 250 + irandom(500);
}
physics_fixture_bind(fix, id);

The above code will create a line of "edge" fixtures with a variety of heights over the length of the room.

Back: Fixtures
Next: physics_fixture_set_polygon_shape

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_circle_shape

This function sets the shape of the fixture to that of a circle with the specified radius.

Syntax:

physics_fixture_set_circle_shape(fixture, rad)

Argument | Description
fixture | the index of the fixture
rad | radius of the circle

Returns: N/A

Description

This function defines a circle shape for your fixture with a radius defined by the argument "rad".

Example:

physics_fixture_set_circle_shape(fix_Ball, sprite_get_width(spr_Ball) / 2);

The code above will apply a circle shape to the fixture indexed in the variable "fix_Ball" with a radius the same as that of the width of the sprite "spr_Ball" divided by 2.

Back: Fixtures
Next: physics_fixture_set_edge_shape

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_collision_group

This function permits fixtures to be grouped to avoid or force collisions.

Syntax:

physics_fixture_set_collision_group(fixture, group)

Argument | Description
fixture | the fixture that is to be bound
group | the group that this fixture is assigned to (either a positive value, 0, or a negative value)

Returns: N/A

Description

Once you have created your fixture you can define it as being part of a collision group. This means that you can tell instances with that fixture to always collide or never collide with other instance that have fixtures bound to them with the same collision group. The values that can be assigned are based on positive or negative numbers, with 0 being the default value (meaning that the instance with this fixture setting is ignored unless a collision event is created for it). Here is an image to help explain:

As you can see, setting collision groups can be very useful to create complex physical bodies that interact with the physical world around them, but not with each other. However, it should be noted that due to the complexity of calculating collisions based on groups like this, it is recommend that you try to keep the number of groups in use in any one room to an absolute minimum.

Example:

physics_fixture_set_collision_group(fix_Wheel, -1);

The code above will set the fixture indexed in the variable "fix_Wheel" to be part of the group "-1".

Back: Fixtures
Next: physics_fixture_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_density

This function sets the density of a fixture.

Syntax:

physics_fixture_set_density(fixture, density)

Argument | Description
fixture | the index of the fixture
density | the density of the fixture calculated as kg/m²

Returns: N/A

Description

The density of something is defined as its mass per unit volume, which basically means how much mass is crammed into the space it takes up in the world. So, a balloon would have a low density as it has little mass that occupies a large space, while a lead bar would have a high density as it has a great mass, yet occupies little space.

In the GameMaker: Studio 2D physics world mass is calculated automatically for you from the values you input for the density and by the surface area of the shape you define for the fixture. This will have a direct impact on how much inertia a fixture has as well as how it reacts to collisions and forces, so if you make a small shape with a high density it will have a very large mass (like a bar of lead), but if you define a large shape with a low density it will have a much smaller mass (like a balloon).

Note: If you wish the instance that is going to receive the fixture to be static (ie: immobile in the game world) then the density should be set to 0, essentially giving it an infinite density.

Example:

physics_fixture_set_density(fix_Balloon, 0.1);

The code above will set the density of the fixture indexed in "fix_Ballon" to 0.1.

Back: Fixtures
Next: physics_fixture_set_friction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_edge_shape

This function sets the shape of the fixture to that of a circle with the specified radius.

Syntax:

physics_fixture_set_edge_shape(fixture, local_x1, local_y1, local_x2, local_y2)

Argument | Description
fixture | the index of the fixture
local_x1 | start x position for the edge
local_y1 | start y position for the edge
local_x2 | end x position for the edge
local_y2 | end y position for the edge

Returns: N/A

Description

This function defines an "edge" fixture shape. An edge shape is simply a line that will generate a collision when other fixtures over lap it, and can be very useful for generating (for example) terrain, or for creating borders around a room. The position of the edge is defined using local space, ie: the x/y position of the instance is considered (0,0), so this should be taken into consideration when creating them (in the code example below, the instance would have been placed at (0,0) in the room to avoid complications).

Example:

var xx = 0;
var y1 = room_height - 100;
var y2 = room_height - 50 - irandom(100);
for (var i = 0; i < 10; i++;)
{
var fix = physics_fixture_create();
physics_fixture_set_edge_shape(fix, xx, y1, xx + 50, y2);
physics_fixture_bind(fix, id);
physics_fixture_delete(fix);
xx += 50;
y1 = y2;
y2 = room_height - 50 - irandom(100);
}

The above code will create a line of "edge" fixtures with a variety of heights over the length of the room.

Back: Fixtures
Next: physics_fixture_set_chain_shape

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_friction

This function sets the friction of a fixture.

Syntax:

physics_fixture_set_friction(fixture, friction)

Argument | Description
fixture | the index of the fixture
friction | the friction of the fixture must be between 0 and 1

Returns: N/A

Description

Friction is the force that resists the relative motion of material elements sliding against each other, which in the GameMaker: Studio physics world, translates as the loss of momentum caused by the collision of two instances with fixtures bound to them. So, when two instances collide, their motion is affected by this value, with a high friction causing a larger loss of momentum than a lower value.

Example:

physics_fixture_set_friction(fix_Brick, 0.1);

The code above will set the friction of the fixture indexed in "fix_brick" to 0.1.

Back: Fixtures
Next: physics_fixture_set_linear_damping

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_kinematic

This function indicates that the fixture is indicated to behave kinematically.

Syntax:

physics_fixture_set_kinematic(fixture)

Argument | Description
fixture | the index of the fixture

Returns: N/A

Description

There will be certain instances in a physics based game which you want to move around but do not wish to be acted on by forces such as gravity, nor forces incurred by collisions with dynamic objects (think of moving platforms in a platform game, for example). For such objects simply setting the density of a fixture to 0 will mean that the physics will assume that the object is intended to be static. However, should you set the phy_speed_x, phy_speed_y or phy_angular_velocity variables for an instance that has had such a fixture bound to it, it will be converted into a kinematic object and begin movement. Change the instance from static to kinematic mid-simulation can be expensive in terms of processing (depending on the state of the instances in the physics world) and therefore it is recommended to set the fixture to be kinematic using this function prior to binding it to an instance, so that it will be unaffected by collisions and forces (such as gravity) but may move with constant linear and/or angular velocity.

Example:

physics_fixture_set_kinematic(fix_Cloud);

The code above will indicate that the fixture indexed in "fix_Cloud" should be marked as kinematic.

Back: Fixtures
Next: physics_fixture_set_awake

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_linear_damping

This function sets the linear damping value of a fixture.

Syntax:

physics_fixture_set_linear_damping(fixture, damping)

Argument | Description
fixture | the index of the fixture
damping | the damping of the fixture, usually between 0 and 1

Returns: N/A

Description

Damping is used to reduce the physics world velocity of instances, and differs from friction in that friction only occurs when two instances with fixtures are in contact. Damping is also much cheaper to simulate than friction, but please note that damping is not a replacement for friction; the two effects can, and should, be used together. Here is an image to illustrate damping:

Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity meaning full damping. Normally you will use a damping value between 0 and 1.

Example:

physics_fixture_set_linear_damping(fix_Ball, 0.1);

The code above will set the linear damping of the fixture indexed in "fix_ball" to 0.1.

Back: Fixtures
Next: physics_fixture_set_angular_damping


physics_fixture_set_polygon_shape

This function sets the shape of the fixture to that of a polygon.

Syntax:

physics_fixture_set_polygon_shape(fixture)

Argument | Description
fixture | the index of the fixture

Returns: N/A

Description

This function sets a polygon shape for your fixture, but you will need to use physics_fixture_add_point to actually define the shape of this polygon relative to the origin of the fixture. The polygon is closed when the fixture is bound to an instance. You should note too that this function must be called before defining any points, and you must also have at least three points defined for your polygon before binding it to an instance or you will get an error.

Example:

physics_fixture_set_polygon_shape(fix_Ship);
physics_fixture_add_point(fix_Ship, 0,0);
physics_fixture_add_point(fix_Ship, -40, 100);
physics_fixture_add_point(fix_Ship, 40, 100);

The code above will apply a polygon shape to the fixture indexed in the variable "fix_Ship" and then defines three points to create a triangular shape.

Back: Fixtures
Next: physics_fixture_add_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_restitution

This function sets the restitution value of a fixture.

Syntax:

physics_fixture_set_restitution(fixture, restitution)

Argument | Description
fixture | The index of the fixture
restitution | The restitution of the fixture (usually between 0 and 1)

Returns: N/A

Description

In physics, restitution is defined as "the return of an object or system to its original state after elastic deformation", but as the fixtures in the GameMaker: Studio are really rigid bodies and cannot be deformed, restitution is really a way of saying how "bouncy" the fixture is. This setting will affect how much an object "bounces" when it collides with other objects and is co-dependant on other forces that act on the instance like gravity and friction, and is usually a value between 0 and 1 (higher values can be used but may give un-predictable results). Here is an illustration of how it works:

Example:

physics_fixture_set_restitution(fix_Ball, 0.9);

The code above will set the restitution of the fixture indexed in "fix_ball" to 0.9.

Back: Fixtures
Next: physics_fixture_set_sensor

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_fixture_set_sensor

This function tells GameMaker: Studio that the fixture is to be treated as a sensor only.

Syntax:

physics_fixture_set_sensor(fixture, state)

Argument | Description
fixture | the index of the fixture
state | whether a fixture is a sensor (true) or not (false)

Returns: N/A

Description

Some times you will want your game to detect and recognise when two instances with fixtures collide, but not have any physical reaction to the collision. This can be done by converting the fixture into a sensor, which basically means that they will generate a collision event but with no physical response so that you can use these instances as "triggers" for other events to happen in the game room. Any fixture can be flagged as a sensor, and it makes no difference if the instance it is bound to is static or in movement.

NOTE: A sensor fixture will fire off the collision event when the collision first occurs only, meaning you don't get a stream of collision events as the two bodies continue to overlap (which is what would traditionally occur). If they stop overlapping and overlap subsequently there will be another collision event triggered.

Example:

physics_fixture_set_sensor(fix_Cloud, 1);

The code above will turn the sensor state of the fixture indexed in "fix_Cloud" to true.

Back: Fixtures
Next: physics_fixture_set_kinematic

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_get_density

This function gets the density value for a bound fixture.

Syntax:

physics_get_density(fixture)

Argument | Description
fixture | the id of the bound fixture

Returns: Real

Description

When you bind a fixture to an instance using physics_fixture_bind this returns an "id" for the bound fixture. You can use this id to get the density value of the bound fixture (not the "base" fixture) at any time using this function.

Example:

var density = physics_get_density(fix_id);
physics_set_density(fix_id, density - 0.1);

The code above gets the current density value for the bound physics properties of the instance and then sets them to a different value.

Back: Fixtures
Next: physics_get_restitution

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_get_friction

This function gets the friction value for a bound fixture.

Syntax:

physics_get_friction(fixture)

Argument | Description
fixture | the id of the bound fixture

Returns: Real

Description

When you bind a fixture to an instance using physics_fixture_bind this returns an "id" for the bound fixture. You can use this id to get the friction value of the bound fixture (not the "base" fixture) at any time using this function.

Example:

var fric = physics_get_friction(fix_id);
physics_set_friction(fix_id, fric + 0.1);

The code above gets the current friction value for the bound physics properties of the instance and then sets them to a different value.

Back: Fixtures
Next: physics_get_density

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_get_restitution

This function gets the density value for a bound fixture.

Syntax:

physics_get_restitution(fixture)

Argument | Description
fixture | the id of the bound fixture

Returns: Real

Description

When you bind a fixture to an instance using physics_fixture_bind this returns an "id" for the bound fixture. You can use this id to get the restitution (the "bounciness" property) value of the bound fixture, not the "base" fixture, at any time using this function.

Example:

var rest = physics_get_restitution(fix_id);
physics_set_restitution(fix_id, rest * 2);

The code above gets the current restitution value for the bound physics properties of the instance and then sets them to a different value.

Back: Fixtures
Next: physics_set_friction

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_remove_fixture

This function removes a fixture from an instance.

Syntax:

physics_remove_fixture(id, fixture)

Argument | Description
id | The ID of the instance to remove the fixture from
fixture | The ID of the fixture that is to be removed from the instance

Returns: N/A

Description

This function removes (or "un-binds") a fixture from an instance or instances. It requires the unique "id" of the bound fixture (as returned by the function physics_fixture_bind and it will remove all the currently defined physics properties for the instance, permitting you to redefine a new fixture and bind that to the instance. In this way you can change the instances physical properties without having to destroy and re-create it.

Example:

physics_remove_fixture(id, my_fix);

The code above will remove the fixture with the "id" stored in the variable "my_fix" from the instance.

Back: Fixtures
Next: physics_fixture_set_box_shape

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_set_density

This function sets the density value for a bound fixture.

Syntax:

physics_set_density(fixture, density)

Argument | Description
fixture | the id of the bound fixture
density | the new density value to apply

Returns: N/A

Description

When you bind a fixture to an instance using physics_fixture_bind this returns an "id" for the bound fixture. You can use this id to set the density value of the bound fixture, not the "base" fixture, at any time using this function.

Example:

var density = physics_get_density(fix_id);
physics_set_density(fix_id, density - 0.1);

The code above gets the current density value for the bound physics properties of the instance and then sets them to a different value.

Back: Fixtures
Next: physics_set_restitution

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_set_friction

This function sets the friction value for a bound fixture.

Syntax:

physics_set_friction(fixture, friction)

Argument | Description
fixture | the id of the bound fixture
friction | the new friction value to apply

Returns: N/A

Description

When you bind a fixture to an instance using physics_fixture_bind this returns an "id" for the bound fixture. You can use this id to set the friction value of the bound fixture, not the "base" fixture, at any time using this function.

Example:

var fric = physics_get_friction(fix_id);
physics_set_friction(fix_id, fric + 0.1);

The code above gets the current friction value for the bound physics properties of the instance and then sets them to a different value.

Back: Fixtures
Next: physics_set_density

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_set_restitution

This function sets the restitution value for a bound fixture.

Syntax:

physics_set_restitution(fixture, restitution)

Argument | Description
fixture | the id of the bound fixture
restitution | the new restitution value to apply

Returns: N/A

Description

When you bind a fixture to an instance using physics_fixture_bind this returns an "id" for the bound fixture. You can use this id to set the restitution value of the bound fixture, not the "base" fixture, at any time using this function.

Example:

var rest = physics_get_restitution(fix_id);
physics_set_restitution(fix_id, rest * 2);

The code above gets the current restitution value for the bound physics properties of the instance and then sets them to a different value.

Back: Fixtures
Next: physics_mass_properties

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Forces

The physics system in GameMaker: Studio has a number of functions to apply distinct forces within the world.

In the GameMaker: Studio physics world, instances aren’t only affected by gravity and collisions, they are also affected by the forces that you choose to apply to them, and knowing the right force to apply is very important when you want to control an instance correctly within the physics simulation.

The following functions exist to apply different types of forces to physics enabled instances:

  1. physics_apply_force
  2. physics_apply_impulse
  3. physics_apply_local_force
  4. physics_apply_local_impulse
  5. physics_apply_torque
  6. physics_apply_angular_impulse

Back: Physics Functions
Next: Fixtures

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_apply_angular_impulse

This function applies an angular impulse to a physics enabled instance.

Syntax:

physics_apply_angular_impulse(impulse)

Argument | Description
impulse | The impulse (in Newton metres) to be applied

Returns: N/A

Description

This function will give an angular impulse to a physics enabled instance. This impulse will set the angular rotation by the amount given, ignoring the current torque, essentially setting the amount of "spin" that a fixture has. If you wish to apply an angular force to an instance using torque, then you should be using the function physics_apply_torque().

Example:

if keyboard_check(vk_up) physics_apply_angular_impulse(10);

The code above will give the physics enabled fixture an angular impulse if a key is pressed.

Back: Forces
Next: physics_apply_force

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_apply_force

This function applies a force to the current instance at a position in the room with a strength defined by a vector.

Syntax:

physics_apply_force(xpos, ypos, xforce, yforce)

Argument | Description
xpos | The x coordinate in the room where the force will be applied
ypos | The y coordinate in the room where the force will be applied
xforce | the x component of the force vector
yforce | the y component of the force vector

Returns: N/A

Description

When working with physics you need to apply not only gravity to objects, but forces as well. A force is any influence that causes an object to undergo a change in speed, a change in direction, or a change in shape, and is defined in the GameMaker: Studio physics world the same as we define gravity, by getting the vector from the two xforce/yforce components. It should be noted that forces are not applied to the center of mass of the object, but rather at a point in the room and they will change the direction and speed as well as the torque (spin) dependant on any other forces that are working on the object (like gravity). Here is an example image to help illustrate:

In the above example the spring object at the bottom has created a force on the ball object getting it to move in a different direction. The exact force is defined by the vector we get from the components xforce/yforce in relation to the xpos/ypos coordinates - which simply means that the force is calculated as the distance from xpos/ypos to xforce/yforce in Newtons (a Newton being defined as the amount of net force required to accelerate a mass of one kilogram at a rate of one meter per second squared)and the direction is the angle that we get from xpos/ypos to xforce/yforce. The code for a collision like the above would go in the collision event of the spring object and would look something like that provided in the example below.

NOTE: The physics world uses metres for all its calculations, and the ratio of pixels per metre is defined in the room editor or using physics_world_create.

Example:

with (other)
{
physics_apply_force(x, y, 0, -30);
}

The code above will apply code to the other object in the collision with a force of 30 Newtons and a direction.

Back: Forces
Next: physics_apply_impulse

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_apply_impulse

This function applies an impulse to a position in the room with a strength defined by a vector.

Syntax:

physics_apply_impulse(xpos, ypos, ximpulse, yimpulse)

Argument | Description
xpos | The x coordinate in the room where the impulse will be applied
ypos | The y coordinate in the room where the impulse will be applied
ximpulse | the x component of the impulse vector
yimpulse | the y component of the impulse vector

Returns: N/A

Description

Not only can you apply force and gravity to an object with the physics in GameMaker: Studio but you can also apply an impulse. This is slightly different to a force in that when it is applied it will immediately affect the speed, and, potentially the torque (or "spin") of the object, particularly if the point chosen to apply the impulse is not aligned with the center of mass (note: the center of mass is not necessarily the same as the origin!). Here is an illustration:

As you can see, the player has clicked on the ball and this has given it an impulse to move to the upper right, spinning as it goes. The exact impulse is defined by the vector we get from the components ximpulse/yimpulse in relation to the xpos/ypos coordinates - which simply means that the impulse is calculated as the distance from xpos/ypos to ximpulse/yimpulse in Newtons, and the direction is the angle that we get from xpos/ypos to ximpulse/yimpulse.

NOTE: The physics world uses metres for all its calculations, and the ratio of pixels per metre is defined in the room editor or using physics_world_create.

Example:

if mouse_check_button_pressed(mb_left)
{
with (place_meeting(mouse_x, mouse_y, all))
{
physics_apply_impulse(mouse_x, mouse_y, -10 + irandom(20), -10 + irandom(20));
}
}

The code above will apply an impulse with a random vector to an instance that is at the mouse position when the left button is pressed.

Back: Forces
Next: physics_apply_local_force

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_apply_local_force

This function applies a force to an instance at a position relative to its origin and with a strength and direction defined by a vector.

Syntax:

physics_apply_local_force(xlocal, ylocal, xforce, yforce)

Argument | Description
xlocal | The x coordinate relative to the origin where the force will be applied
ylocal | The y coordinate relative to the origin where the force will be applied
xforce | the x component of the force vector
yforce | the y component of the force vector

Returns: N/A

Description

Another way to use force in the physics world is to apply it locally to an instance. What this means is that the strength and direction of the force are calculated based on the origin (or the position if it has no sprite) of the instance, without taking into consideration the direction or rotation it may have in the game room or physics world. It should be noted that with this function, forces are not applied to the center of mass of the object, but rather at a point relative to the instance and they will not be instantly applied as they are dependant on any other forces that are working on the object (like gravity). This illustration demonstrates how a local force works:

As you can see, the xlocal and ylocal coordinates are calculated based on the axis position always being considered as the origin of the instance (0,0), so no matter where in the room the object is, xlocal and ylocal are always going to be the same. You then have to decide where the vector components of the force (xforce and yforce) should be positioned relative to the xlocal/ylocal position. The exact force is defined by the vector we get from the components xforce/yforce in relation to those coordinates - which simply means that the force is calculated as the distance from xlocal/ylocal to xforce/yforce in Newtons, and the direction is the angle that we get from xlocal/ylocal to xforce/yforce. This may seem slightly confusing, but you just have to look at the illustration to see how this works, and it saves you some complicated maths!

NOTE: The physics world uses metres for all its calculations, and the ratio of pixels per metre is defined in the room editor or using physics_world_create.

Example:

if keyboard_check(vk_right)
{
physics_apply_local_force(-25, 0, -50, 0);
}

The code above will apply a force to the instance of 50 Newtons from left to right relative to the origin while the right arrow key is pressed.

Back: Forces
Next: physics_apply_local_impulse

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_apply_local_impulse

This function applies an impulse to a position in the room with a strength defined by a vector.

Syntax:

physics_apply_local_impulse(xpos, ypos, ximpulse, yimpulse)

Argument | Description
xpos | The x coordinate relative to the origin where the impulse will be applied
ypos | The y coordinate relative to the origin where the impulse will be applied
ximpulse | the x component of the impulse vector (relative to the xpos coordinate)
yimpulse | the y component of the impulse vector (relative to the ypos coordinate)

Returns: N/A

Description

Not only can you apply force and gravity to an object with the physics in GameMaker: Studio but you can also apply an impulse. This is slightly different to a force in that when it is applied it will immediately affect the speed, and, potentially the torque (or "spin") of the object, particularly if the point chosen to apply the impulse has a vector that is not aligned with the centre of mass (note: the center of mass is not necessarily the same as the origin!). This function applies an impulse locally to an instance. What this means is that the strength and direction of the impulse are calculated based on the origin (or the position if it has no sprite) of the instance, without taking into consideration the direction or rotation it may have in the game room or physics world. Here is an illustration:

As you can see, the frog in the image gets an impulse from below to make it "jump". The exact impulse is defined by the vector we get from the components ximpulse/yimpulse in relation to the xpos/ypos coordinates - which simply means that the impulse is calculated as the distance from xpos/ypos to ximpulse/yimpulse in Newtons, and the direction is the angle that we get from xpos/ypos to ximpulse/yimpulse.

NOTE: The physics world uses metres for all its calculations, and the ratio of pixels per metre is defined in the room editor or using physics_world_create.

Example:

if jump physics_apply_local_impulse(0, 20, 0, 50);

The code above will apply an impulse with force of 30 Newtons and a direction going from bottom to top relative to the instance origin if the variable "jump" is true.

Back: Forces
Next: physics_apply_torque

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_apply_torque

This function applies torque (spin) to an instance.

Syntax:

physics_apply_torque(torque)

Argument | Description
torque | The torque (in Newton metres) to be applied

Returns: N/A

Description

When we talk about torque, we are generally talking about the tendency of a force or impulse to rotate an instance about its centre of mass, but in GameMaker: Studio you can also apply torque independently to an instance, causing it to rotate in a given direction. How much torque you apply to get the desired rotation all depends on the size and density of the fixture you assign to your instance, as both these properties go towards defining its mass, which defines its inertia, which affects torque! The general rule of thumb is that if an instance has a lot of inertia, you will need a lot of torque to get it to start rotating. It should also be noted that other factors like gravity and collisions can also affect the torque of an instance. Here is an image to help explain:

As you can see, the amount of torque you need to rotate the object depends on the underlying mass and inertia that it gives. This is all calculated for you by GameMaker: Studio based on the size and density of the fixture that is assigned to the instance when it is created. Also note that for anti-clockwise rotation, the value should be negative.

Example:

if keyboard_check(vk_left) physics_apply_torque(-100);

The code above will rotate the instance to the anti-clockwise (to the left) with a torque of 100Nm when the left arrow key is pressed.

Back: Forces
Next: physics_apply_angular_impulse

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Joints

The physics system in GameMaker: Studio has a number of functions to apply joints between fixtures.

In the GameMaker: Studio physics world, joints are used to constrain instances to the world or to each other. Typical examples in games include ragdolls, teeters, and pulleys, but joints can be combined in many different ways to create interesting motions or add realism to your game world.

Note: A joint does not need to be deleted when you destroy an instance joined to another instance, nor does it need to be deleted at the end of a room. Except in very specific cases (see the gear joint) as this is dealt with automatically by GameMaker: Studio.

Creating joints

The following pages explain the available joints and how they can be created:

  1. physics_joint_distance_create
  2. physics_joint_revolute_create
  3. physics_joint_prismatic_create
  4. physics_joint_pulley_create
  5. physics_joint_gear_create
  6. physics_joint_rope_create
  7. physics_joint_wheel_create
  8. physics_joint_weld_create
  9. physics_joint_friction_create
  10. physics_joint_delete

Joint Values

Once a joint has been created, it can often be necessary to know its properties in order to change them at specific times in your game. The following functions (with their corresponding internal constants) are available to test and change joint values:

  1. physics_joint_enable_motor
  2. physics_joint_get_value
  3. physics_joint_set_value

Joint Constants

Finally, you can use a number of constants from within GameMaker: Studio functions to get (or set) different properties of certain joints. These constants can all be found in the following section:

  1. Physics Joint Constants

Back: Physics Functions
Next: Soft Body Particles

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Physics Joint Constants

This section lists the constants associated with physics joints.

There are a great number of constants included within the GameMaker: Studio GML that are specific to joints between fixtures in the physics world. These can be used in conjunction with many of the different joint functions to set or get information from them in real time while the physics simulation is running. You should be aware, however, that complex calculations are done when you call these, so they should be used with care and only when necessary and note that many are unique to a specific type of joint. Also note that while you can get all these values with the appropriate function, you can only set those that are marked as not being read-only.

General

The following constants can be applied to any of the available joint types:

Constant | Description | Read Only
phy_joint_anchor_1_x | The x coordinate of the first anchor point of the joint in the room | Yes
phy_joint_anchor_1_y | The y coordinate of the first anchor point of the joint in the room | Yes
phy_joint_anchor_2_x | The x coordinate of the second anchor point of the joint in the room | Yes
phy_joint_anchor_2_y | The y coordinate of the second anchor point of the joint in the room | Yes
phy_joint_reaction_force_x | This is the reaction force being applied to the second instance in a joint at the x anchor position | Yes
phy_joint_reaction_force_y | This is the reaction force being applied to the second instance in a joint at the y anchor position | Yes
phy_joint_reaction_torque | This is the torque being applied to the second instance in a joint at the anchor position | Yes

Motors

These constants are for those joints that have a motor attached to them (revolute, prismatic, wheel):

Constant | Description | Read Only
phy_joint_max_motor_force | The value specified when the joint was created for the maximum motor force | No
phy_joint_max_motor_torque | The value specified when the joint was created for the maximum motor torque | No
phy_joint_motor_force | The current motor force | Yes
phy_joint_motor_speed | The current motor speed | No
phy_joint_motor_torque | The current motor torque | Yes

Revolute Joints

For a revolute joint you can use the following constant (as well as the motor constants if one has been added):

Constant | Description | Read Only
phy_joint_angle | The angle that a line between the two anchor points of the joint makes. This is calculated using the physics world coordinates (not the GameMaker: Studio room coordinates) in radians. | Yes
phy_joint_angle_limits | Enable or disable angle limiting for the joint. Set the value to true to enable or false to disable. | No
phy_joint_upper_angle_limit | The upper angle limit for the joint in degrees. | No
phy_joint_lower_angle_limit | The lower angle limit for the joint in degrees. | No

Prismatic Joints

For a prismatic joint you can use the following constant:

Constant | Description | Read Only
phy_joint_translation | Gets the distance between the anchor x/y coordinates and the local x/y coordinates. | Yes
phy_joint_speed | The current joint movement speed. | Yes

Pulley Joints

For a pulley joint you can use the following constants (as well as those for distance joints):

Constant | Description | Read Only
phy_joint_length_1 | This will return the length of the joint from the first local x/y coordinates to the first anchor x/y coordinates | No
phy_joint_length_2 | This will return the length of the joint from the second local x/y coordinates to the second anchor x/y coordinates | Yes

Distance Joints, Weld Joints and Wheel Joints

For a distance, weld, and wheel joints you can use the following constants (as well as those for pulley joints):

Constant | Description | Read Only
phy_joint_damping_ratio | The damping ratio is non-dimensional and defines the "springiness" of the joint. The value for this constant is typically between 0 and 1, but can be larger, and at 1, the damping is critical meaning that all oscillations should vanish. | No
phy_joint_frequency | This will return (or set) the oscillation frequency for the joint, in hertz, and typically the frequency should be less than a half the frequency of the time step, as set by the function physics_world_update_speed. | No

Friction Joints

For a friction joint you can use the following constants:

Constant | Description | Read Only
phy_joint_max_torque | The maximum torque value for the joint. | No
phy_joint_max_force | The maximum force value for the joint. | No

Rope Joints

For a rope joint you can use the following constant:

Constant | Description | Read Only
phy_joint_max_length | The maximum extension for the connection between the two anchor points. | No

Back: Joints

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_delete

Delete a joint from the physics world.

Syntax:

physics_joint_delete(joint)

Argument | Description
joint | The index of the joint that you wish to delete

Returns: N/A

Description

Once two instances with physics representations have been bound by a joint, this can be deleted again at any time. Normally this will happen automatically when one of the two instances is destroyed, or when the room ends, but there are times when you may wish to do this manually. In those cases you would use this function.

It should also be noted that whenever an instance that is part of a gear joint is destroyed, the gear joint should be deleted using this function before any of the instances involved in forming the gear (but the remaining joints will be deleted automatically), for example in the destroy event of the instance.

Example:

var reactionForceX, reactionForceY, reactionForce;
if shipJoint
{
reactionForceX = physics_joint_get_value(shipJoint, phy_joint_reaction_force_x);
reactionForceY = physics_joint_get_value(shipJoint, phy_joint_reaction_force_x);
reactionForce = sqrt((reactionForceX + reactionForceX) + (reactionForceY + reactionForceY));
if reactionForce > 2
{
physics_joint_delete(shipJoint);
shipJoint = -1;
}
}

The above code checks to see if the variable "shipJoint" holds a joint index and if it does, it then calculates the force being applied to that joint using the two constants. Finally, if the total force is greater than 2, the joint is deleted.

Back: Joints
Next: physics_joint_enable_motor

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_distance_create

Create a straight line joint connecting two instances, both of which have had fixtures defined and assigned to them.

Syntax:

physics_joint_distance_create(inst1, inst2, w_anchor1_x, w_anchor1_y, w_anchor2_x, w_anchor2_y, col)

Argument | Description
inst1 | The first instance to connect with the joint
inst2 | The second instance to connect with the joint
w_anchor1_x | The first x coordinate for the joint, within the game world
w_anchor1_y | The first y coordinate for the joint, within the game world
w_anchor2_x | The second x coordinate for the joint, within the game world
w_anchor2_y | the second y coordinate for the joint, within the game world
col | Whether the two instances can collide (true) or not (false)

Returns: Index of the joint

Description

One of the simplest joint is a distance joint which says that the distance between two points on two instances must be constant. When you specify a distance joint the two instances should already be created and have a fixture assigned, then you define the two anchor points in room coordinates. The first anchor point is connected to instance 1, the second anchor point is connected to instance 2 and the distance between these points imply the length of the distance constrain. The image below shows how this works:

As you can see, the anchor points are specified as room coordinates so care must be taken when defining them, especially if the instances are being created at the same time as the joints rather than being placed in the room through the room editor. You should also realise that the joints are created independently of the size of the sprite of the instances or the fixtures they have attached. So, if you create a distance joint somewhere other than the origin of the instance, it is still valid and will constrain the two instances relative to the position at which it was created. If you set the "col" value to true then the two instances can interact and collide with each other but only if they have collision events, however if it is set to false, they will not collide no matter what.

Example:

var mainFixture, o_id;
mainFixture = physics_fixture_create();
physics_fixture_set_circle_shape(mainFixture, sprite_get_width(sprite_index) / 2);
o_id=instance_create(x+300, y, obj_Rudder);
physics_fixture_bind(mainFixture, id);
physics_fixture_bind(mainFixture, o_id);
physics_joint_distance_create(id, o_id, x + 50, y, o_id.x - 50, o_id.y, 0);
physics_fixture_delete(mainFixture);

The above code creates and defines a new fixture and then creates an instance of "obj_Rudder". The fixture is then assigned to the instance that is running the code as well as the newly created one and a joint is created between them. Finally the fixture is deleted as it is no longer needed.

Back: Joints
Next: physics_joint_revolute_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_enable_motor

Enables (or disables) the motor of a joint that permit this behaviour.

Syntax:

physics_joint_enable_motor(joint, motor)

Argument | Description
joint | The joint that you wish to enable or disable the motor on
motor | Whether you wish to turn the motor on (true) or off (false)

Returns: N/A

Description

When you have a joint with a motor (prismatic or revolute), you may want to be able to switch the motor on or off depending on variables and conditions within the game. For this, you need to have stored the index of the joint previously in a variable and then you can switch the motor on or off by using this function and setting the "motor" argument to true or false.

Example:

var t_fix = physics_fixture_create();
physics_fixture_set_circle_shape(t_fix, sprite_get_width(sprite_index) / 2);
var o_id=instance_create(x+300, y, obj_Door);
physics_fixture_bind(t_fix, id);
physics_fixture_bind(t_fix, o_id);
perma_joint = physics_joint_revolute_create(id, o_id, x+25, y, -90, 90, 1, 10, 2, 0, 0);
physics_joint_enable(perma_joint, 1);
physics_fixture_delete(t_fix);

The above code creates and defines a new fixture and then creates an instance of "obj_Door", binding the created fixture to the two instances. They are then joined by a revolute joint with no motor and the angles limited to a +/- 90 degree swing, and we store the joint index in the variable "perma_joint". We then switch the motor on using this variable, before finally deleting the fixture from memory as it is no longer needed.

Back: Joints
next: physics_joint_get_value


physics_joint_friction_create

A joint for reducing the relative motion between two fixtures.

Syntax:

physics_joint_friction_create(inst1, inst2, anchor_x, anchor_y, max_force, max_torque, col)

Argument | Description
inst1 | The first instance to connect with the joint
inst2 | The second instance to connect with the joint
anchor_x | The x coordinate for the joint, within the game world
anchor_y | The y coordinate for the joint, within the game world
max_force | The maximum frictional force that will be applied
max_torque | The maximum rotational force that will be applied
col | Whether the two instances can collide (true) or not (false)

Returns: Index of the joint

Description

The friction joint is a bit different to all other joints in the physics simulation in that the connection created will not constrain the instances position or movement, but rather its speed and rotation. This works by taking the maximum input values for force and torque and applying those to the second fixture to bring the speed and angular momentum down to the same values as that of the first instance. So, if you have a stationary instance and a moving instance then connect them with a friction joint, the moving instance will gradually slow down until it too is stationary. If both instances were moving then the second instance will have its movement speed modified to match that of the first instance.

As with most other joints, you supply the instances to join together, as well as the position for the joint to be created at within the room. You then supply the maximum force and maximum torque (directional and rotational friction), and if you set the "col" value to true then the two instances can interact and collide with each other but only if they have collision events, however if it is set to false, they will not collide no matter what.

Example:

var mainFixture, o_id;
mainFixture = physics_fixture_create();
physics_fixture_set_circle_shape(mainFixture, sprite_get_width(sprite_index) / 2);
o_id = instance_create(x+300, y, obj_Rudder);
physics_fixture_bind(mainFixture, id);
physics_fixture_bind(mainFixture, o_id);
physics_joint_friction_create(id, o_id, x, y, 10, 0.3, true);
physics_fixture_delete(mainFixture);

The above code will create a fixture then bind it to two instances, before connecting them both using a friction joint.

Back: Joints
Next: physics_joint_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_gear_create

Create a gear joint using two revolute joints or a revolute and a prismatic joint.

Syntax:

physics_joint_gear_create(inst1, inst2, joint_1, joint_2, ratio)

Argument | Description
inst1 | The first instance to connect with the joint
inst2 | The second instance to connect with the joint
joint_1 | A previously defined revolute joint
joint_2 | A previously defined revolute or prismatic joint
ratio | Set the velocity ratio between the two joints

Returns: index of the joint

Description

If you want to create a sophisticated mechanical contraption you might want to use gears. In principle you can create gears in GameMaker: Studio by using compounding instances to model gear teeth, but this is not very efficient and might be tedious to author! Thankfully there is a simpler method, and that is to use a gear joint. To make one you need to have previously defined your fixtures and created the two basic joints that are going to comprise your gear - these must be made up of one revolute joint and either a prismatic joint or another revolute joint. The image below shows how a gear would typically be created in a game: So what happens? Well, once the two joints are added into the gear, interaction with one will have an effect on the other, so in the example image above, if you rotate inst2, inst3 will move up and down, or if you move inst3 up and down then inst2 will rotate. You can also change the gear ratio, meaning that you need to move one instance more (or less) to get the desired effect. The code in the example at the bottom shows how something like the image above can be created.

Note: If you need to delete either of the two instances that are involved in the gear joint (or just delete their joints) then you must delete the gear joint first using physics_joint_delete() or else you will get an error!

Example:

var t_fix, g_fix, inst1, inst2, inst3, r_joint, p_joint;
g_fix = physics_fixture_create();
physics_fixture_set_box_shape(g_fix, 40, 10);
t_fix = physics_fixture_create();
physics_fixture_set_circle_shape(t_fix, 10);
physics_fixture_set_density(t_fix, 0.5);
inst1 = instance_create(60, room_height - 30, obj_Ground);
inst2 = instance_create(40, room_height - 300, obj_Cog);
inst3 = instance_create(150, room_height - 300, obj_Barrel);
physics_fixture_bind(g_fix, inst1);
physics_fixture_bind(t_fix, inst2);
physics_fixture_bind(t_fix, inst3);
r_joint = physics_create_revolute_joint(inst1, inst2, 40, room_height - 300, -80, 80, 1, 10, 0.5, 1, 0);
p_joint = physics_create_prismatic_joint(inst1, inst3, 150, room_height - 300, 0, 1, -10, 10, true, 0, 0, 0, 0);
physics_create_gear_joint(inst2, inst3, r_joint, p_joint, 0.5);

The above code creates and defines two fixture and then creates three instances, one "obj_Ground" and two others, "obj_Cog" and "obj_Barrel". The fixtures are then bound to these instances and two joints are created. A revolute joint between the ground and the cog, and a prismatic joint between the ground and the barrel. Finally a gear joint is created between the cog and barrel instances using the previously defined revolute and prismatic joints.

Back: Joints
Next: physics_joint_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_get_value

This function tests a joint and returns a value depending on the type of joint being tested and the constant being used.

Syntax:

physics_joint_get_value(joint, value)

Argument | Description
joint | The index of the joint that you wish to test
value | The constant for the joint property that you wish to test

Returns: Real

Description

By using a series of predefined constants, you can ask GameMaker: Studio to tell you a number of things about the state of any given joint. This is very useful as it gives you the ability to delete joints or change an instances behaviour depending on whatever your needs are at the time. There are a number of constants that can be used in this function and they can be found here: Physics Joint Constants, but be aware that complex calculations are done when you call these, so they should be used with care and only when necessary and note that many are unique to a specific type of joint.

If the property does not exist (if, for example, you check a pulley joint for prismatic translation) then 0 will be the return value.

Example:

var reactionForceX, reactionForceY, reactionForce;
if shipJoint
{
reactionForceX = physics_joint_get_value(shipJoint, phy_joint_reaction_force_x);
reactionForceY = physics_joint_get_value(shipJoint, phy_joint_reaction_force_y);
reactionForce = point_distance(0, 0, reactionForceX, reactionForceY);
if reactionForce > 2
{
physics_joint_delete(shipJoint);
shipJoint = -1;
}
}

The above code checks to see if the variable "shipJoint" holds a joint index and if it does, it then calculates the force being applied to that joint using the two constants. Finally, if the total force is greater than 2, the joint is deleted.

Back: Joints
Next: physics_joint_set_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_prismatic_create

Create a prismatic joint connecting two instances and permitting movement along one fixed axis.

Syntax:

physics_joint_prismatic_create(inst1, inst2, w_anchor_x, w_anchor_y, w_axis_x, w_axis_x, lower_trans_limit, upper_trans_limit, limit, max_motor_force, motor_speed, motor, col)

Argument | Description
inst1 | The first instance to connect with the joint
inst2 | The second instance to connect with the joint
w_anchor_x | The x coordinate where the joint is anchored, within the game world
w_anchor_y | The y coordinate where the joint is anchored, within the game world
w_axis_x | The x component of the axis vector
w_axis_y | The y component of the axis vector
lower_trans_limit | The lower permitted limit for the joint movement
upper_trans_limit | The lower permitted limit for the joint movement
limit | Whether to limit the movement of the joint (true) or not (false)
max_motor_force | Sets the maximum movement speed for the motor
motor_speed | This is the speed at which the motor should move
motor | Whether the motor should be active (true) or not (false)
col | Whether the two instances can collide (true) or not (false)

Returns: index of the joint

Description

Like a revolute joint, the prismatic joint only has one degree of freedom, but with this joint it is directional relative to an axis rather than rotational and actually prevents any form of rotation. Here is an image to help you visualise how this works:

We have two instances joined at the anchor point, with an axis for movement defined from the vector the two w_axis x/y coordinates relative to the (0,0) coordinates of the physics world (so an x component of 0 and a y component of 1 (0,1) would make the joint a vertical prismatic joint). This joint can then only move relative to this axis, like a spring or a piston. If you set the lower or upper trans limit, you are basically limiting the amount of movement along this axis, where the 0 position is the exact spot that you defined with w_anchor x/y, so a negative value would go to the "left" of that point along the axis and a positive value to the "right" as shown in the following diagram (realise that "left" and "right" are relative terms!): You can also define the joint as having a motor or not. This means that when un-influenced by a collision the joint will move in a direction along the axis. this direction is defined by the motor speed, with a positive number being towards the axis coordinates ("right") and a negative number being towards the anchor point ("left"). The "max_motor_force" argument is for limiting the speed of the movement so that you don't get a perpetually accelerating motor and to limit the influence that a collision may have on the movement. In this way you can use a joint motor to simulate joint friction by setting the joint speed to zero and maximum force to some small, but significant value. The motor will try to prevent the joint from moving, but will yield to a significant load.

As with all the joints, if you set the "col" value to true then the two instances can interact and collide with each other but only if they have collision events, however if it is set to false, they will not collide no matter what.

Example:

var mainFixture, o_id;
mainFixture = physics_fixture_create();
physics_fixture_set_circle_shape(mainFixture, sprite_get_width(sprite_index) / 2);
o_id = instance_create(x+25, y, obj_Piston);
physics_fixture_bind(mainFixture, id);
physics_fixture_bind(mainFixture, o_id);
physics_joint_prismatic_create(id, o_id, x, y, 0, 10, 0, 0, 0, 5, 0, 1, 1);
physics_fixture_delete(mainFixture);

The above code creates and defines a new fixture and then creates an instance of "obj_Piston", binding the created fixture to the two new objects. They are then joined by a prismatic joint with the anchor position at the same x/y coordinates of the first instance and an axis formed by the vector of the x/y position and the axis x/y (in this case 0,10, which is "down"). There are no limits placed on the amount of movement along this axis, but we have added a motor with 0 speed and a maximum force of 5 to simulate joint friction.

Back: Joints
Next: physics_joint_pulley_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_pulley_create

Create a pulley joint connecting two instances in such a way that the movement of one will have a direct influence over the movement of the other.

Syntax:

physics_joint_pulley_create(inst1, inst2, w_anchor1_x, w_anchor1_y, w_anchor2_x, w_anchor2_y, l_anchor1_x, l_anchor1_y, l_anchor2_x, l_anchor2_y, ratio, max_len1, max_len2, col)

Argument | Description
inst1 | The first instance to connect with the joint
inst2 | The second instance to connect with the joint
w_anchor1_x | The x coordinate where the first part of joint is anchored, within the game world
w_anchor1_y | The y coordinate where the first part of the joint is anchored, within the game world
w_anchor2_x | The x coordinate where the second part of the joint is anchored, within the game world
w_anchor2_y | The y coordinate where the second part of the joint is anchored, within the game world
l_anchor1_x | The local x coordinate where joint 1 is anchored to the first instance
l_anchor1_y | The local y coordinate where joint 1 is anchored to the first instance
l_anchor2_x | The local x coordinate where joint 2 is anchored to the second instance
l_anchor2_y | The local y coordinate where joint 2 is anchored to the second instance
ratio | Set the velocity ratio between two instances
col | Whether the two instances can collide (true) or not (false)

Returns: index of the joint

Description

The pulley joint is used to connect two instances within the physics world in such a way that moving one will directly influence the movement of the other. These joints are first anchored in the world space at two points, each one connected to an instance at its center of mass. This can be changed by setting the local anchor x/y coordinates relative to the origin of the instance, meaning that the actual connection from the instance to the physics world anchor point can be offset somewhere other than its origin. The following image illustrates this:

If you look at inst2 you can see that its local anchor point has been offset 20 pixels to the "left" of its origin (Remember! The world anchor points are defined using the room coordinates, while the local anchor points are defined relative to the origin of the instance). You can also specify a ratio for the pulley joint, which tells one side or the other to move faster, with a value below 1 making the first instance move faster (E.G. 0.5 will make it move twice as fast) and a value above 1 making the second instance move faster (E.G. 2 will make it move twice as fast).

As with all the joints, if you set the "col" value to true then the two instances can interact and collide with each other but only if they have collision events, however if it is set to false, they will not collide no matter what.

Example:

var t_fix, inst1, inst2;
t_fix = physics_fixture_create();
physics_fixture_set_circle_shape(t_fix, 20);
inst1 = instance_create(150, room_height - 90, obj_Block);
inst2 = instance_create(300, room_height - 90, obj_block);
physics_fixture_bind(t_fix, inst1);
physics_fixture_bind(t_fix, inst2);
physics_joint_pulley_create(inst1, inst2, 150, room_height - 140, 300, room_height - 140, 0, 0, 0, 0, 2, 0);
physics_fixture_delete(t_fix);

The above code creates and defines a new fixture, creates two instances of "obj_Block", and then binds this fixture two them. It then goes on to define a pulley joint between these instance, with no offset for the joints, a ratio of 2:1 (meaning that inst2 will move faster). No collisions occur between the two instances in the pulley.

Back: Joints
Next: physics_joint_gear_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_revolute_create

Create a revolute joint connecting two instances at one common point.

Syntax:

physics_joint_revolute_create(inst1, inst2, w_anchor_x, w_anchor_y, ang_min_limt, ang_max_limit, ang_limit, max_motor_torque, motor_speed, motor, col)

Argument | Description
inst1 | The first instance to connect with the joint
inst2 | The second instance to connect with the joint
w_anchor_x | The x coordinate for the joint, within the game world
w_anchor_y | The y coordinate for the joint, within the game world
ang_min_limit | The lower permitted limit for the joint angle
ang_max_limit | The upper permitted limit for the joint angle
ang_limit | Whether the to limit the angle of the joint (true) or not (false)
max_motor_torque | Sets the maximum motor torque used to achieve the desired motor speed (in Newtons per meter)
motor_speed | This is the speed at which the motor should rotate
motor | Whether the motor should be active (true) or not (false)
col | Whether the two instances can collide (true) or not (false)

Returns: index of the joint

Description

A revolute joint forces two bodies to share a common anchor point (often called a hinge point) and the joint has a single degree of freedom - the relative rotation of the two bodies around this point. To specify a revolute you need to provide two instances and a single anchor point in the room, as you can see in the image provided:

If you look at the image, you can see that the two instances have been created to over-lap and at the point where they are touching, we have defined a revolute joint. Now, this joint can be limited in its freedom of rotation thanks to the "ang_min_limit" and "ang_max_limit" values. How does this work? Well, let's look at another image:

As you can see, angles in the physics world are not the same as the standard GameMaker: Studio angles where right is 0 degrees and then it goes anti-clockwise so that up is 90, left is 180, and down is 270. No, when dealing with the revolute joint, the 0 degrees axis runs from the joint position to the origin of the second instance defined by the function and the angles are then calculated in a clockwise direction. If you switch on angle limiting, the limits are defined as being relative to this 0 degree axis and the limit range should include zero, otherwise the joint will lurch when the room begins. Finally, you can define the joint as having a motor or not. This means that when uninfluenced by a collision the joint will move in a direction, which is defined by the motor speed with a positive number being clockwise and a negative number being anti-clockwise. The "max_motor_torque" argument is for limiting the speed of the rotation so that you don't get a perpetually accelerating motor and to limit the influence that a collision may have on the rotation. In this way you can use a joint motor to simulate joint friction by setting joint speed to zero and maximum torque to some small, but significant value. The motor will try to prevent the joint from rotating, but will yield to a significant load.

As with all the joints, if you set the "col" value to true then the two instances can interact and collide with each other but only if they have collision events, however if it is set to false, they will not collide no matter what.

Example:

var mainFixture, o_id;
mainFixture = physics_fixture_create();
physics_fixture_set_circle_shape(mainFixture, sprite_get_width(sprite_index) / 2);
o_id=instance_create(x+25, y, obj_Door);
physics_fixture_bind(mainFixture, id);
physics_fixture_bind(mainFixture, o_id);
physics_joint_revolute_create(id, o_id, x+25, y, -90, 90, 1, 0, 0, 0, 0);
physics_fixture_delete(mainFixture);

The above code creates and defines a new fixture and then creates an instance of "obj_Door", binding the created fixture to the two new objects. They are then joined by a revolute joint with no motor and the angles limited to a +/- 90 degree swing. Finally the fixture is deleted as it is no longer needed.

Back: Joints
Next: physics_joint_prismatic_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_rope_create

Create a straight line joint connecting two instances, both of which have had fixtures defined and assigned to them.

Syntax:

physics_joint_rope_create(inst1, inst2, w_anchor1_x, w_anchor1_y, w_anchor2_x, w_anchor2_y, maxlength, col)

Argument | Description
inst1 | The first instance to connect with the joint
inst2 | The second instance to connect with the joint
w_anchor1_x | The first x coordinate for the joint, within the game world
w_anchor1_y | The first y coordinate for the joint, within the game world
w_anchor2_x | The second x coordinate for the joint, within the game world
w_anchor2_y | the second y coordinate for the joint, within the game world
maxlength | The maximum length that the joint can "stretch"
col | Whether the two instances can collide (true) or not (false)

Returns: Index of the joint

Description

A rope joint is one which is used to join two instances that you want to keep a constant distance apart, no matter what other forces are acting on it. With a distance joint, you can get "joint stretching" where the two fixtures will sperate and behave strangely should too much stress be put on the joint, however the rope joint does not do this and will not stretch any further than the maximum defined length. When you create a rope joint the two instances should already be created and have a fixture assigned, then you define the two anchor points in room coordinates. The first anchor point is connected to instance 1, the second anchor point is connected to instance 2 and the distance and the maxlength argument sets the maximum length constraint on the joint. The image below shows how this works:

As you can see, the anchor points are specified as room coordinates so care must be taken when defining them, especially if the instances are being created at the same time as the joints rather than being placed in the room through the room editor. You should also realise that the joints are created independently of the size of the sprite of the instances or the fixtures they have attached. So, if you create a rope joint somewhere other than the origin of the instance, it is still valid and will constrain the two instances relative to the position at which it was created. If you set the "col" value to true then the two instances can interact and collide with each other but only if they have collision events, however if it is set to false, they will not collide no matter what.

Example:

var mainFixture, o_id;
mainFixture = physics_fixture_create();
physics_fixture_set_circle_shape(mainFixture, sprite_get_width(sprite_index) / 2);
o_id=instance_create(x+300, y, obj_Rudder);
physics_fixture_bind(mainFixture, id);
physics_fixture_bind(mainFixture, o_id);
physics_joint_rope_create(id, o_id, x + 50, y, o_id.x - 50, o_id.y, 300, 0);
physics_fixture_delete(mainFixture);

The above code creates and defines a new fixture and then creates an instance of "obj_Rudder". The fixture is then assigned to the instance that is running the code as well as the newly created one and a rope joint is created between them. Finally the fixture is deleted as it is no longer needed.

Back: Joints
Next: physics_joint_wheel_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_set_value

This function set a particular joint property to the specified value.

Syntax:

physics_joint_set_value(joint, field, value)

Argument | Description
joint | The index of the joint that you wish to change
field | The constant for the joint property that you wish to change
value | The new value for the joint property

Returns: N/A

Description

Certain joint properties can be changed and set even after the creation of the joint, but only on those joints that have a motor, ie - revolute joints and prismatic joints. There are a number of constants that can be used in this function and they can be found here: Physics Joint Constants.

Example:

if physics_joint_get_value(revJoint, phy_joint_max_motor_torque) < 2
{
physics_joint_set_value(revJoint, phy_joint_max_motor_torque, 2);
{

The above code checks to see if the joints maximum motor torque is set to less than 2 and if it is it then sets it to 2.

Back: Joints
Next: physics_joint_distance_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_weld_create

Create a strong but flexible straight line joint connecting two instances along a given angle.

Syntax:

physics_joint_weld_create(inst1, inst2, anchor_x, anchor_y, ref_angle, freq_hz, damping_ratio, col)

Argument | Description
inst1 | The first instance to connect with the joint
inst2 | The second instance to connect with the joint
anchor_x | The x coordinate for the joint, within the game world
anchor_y | The y coordinate for the joint, within the game world
ref_angle | The joint angle to maintain
freq_hz | This is the oscillation frequency for the joint, in hertz
damping_ratio | This damping ratio for the joint
col | Whether the two instances can collide (true) or not (false)

Returns: Index of the joint

Description

The weld joint is designed to attach two fixtures together in a strong, yet flexible bond. The weld joint will permit flexing between the two joined fixtures but without the stretching associated with, for example, a distance joint, and will always try to "spring" back to the reference angle when put under any stress or load. You define the point in the room where the joint should be created, as well as the angle that you wish the joint to try and maintain at all times, as shown in the image below:

As you can see, the anchor points are specified as room coordinates so care must be taken when defining them, especially if the instances are being created at the same time as the joints rather than being placed in the room through the room editor. You should also realise that the joints are created independently of the size of the sprite of the instances or the fixtures they have attached. So, if you create a weld joint somewhere other than the origin of the instance, it is still valid and will constrain the two instances relative to the position at which it was created.

Since the weld joint is flexible and will bend and flex when under any stress, you can set the oscillation frequency (in Hz) as well as the damping ratio for the joint to get different effects - you may need to play with these values to fine tune them and it is recommended that you start off with smaller values and increment them until you get the effect that you desire.

If you set the "col" value to true then the two instances can interact and collide with each other but only if they have collision events, however if it is set to false, they will not collide no matter what.

Example:

var i, fix, o_id, p_id;
p_id = noone;
o_id = noone;
fix = physics_fixture_create();
physics_fixture_set_box_shape(fix, 64, 32);
for (i = 0; i < 5; i++;)
{
o_id = instance_create(x + (128 * i), y, obj_BridgePart);
physics_fixture_bind(fix, o_id);
if i > 0 && i < 4
{
physics_joint_weld_create(p_id, o_id, x + (128 * i) - 64, y, 0, 10, 12, true);
}
p_id = o_id;
}
physics-fixture_delete(fix);

The above code will create a fixture, then use a loop to create a number of instances, binding the fixture to each new instance and then joining them all together using a weld joint. Finally the fixture is deleted from memory.

Back: Joints
Next: physics_joint_friction_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_joint_wheel_create

Create a wheel joint connecting two instances at a common point.

Syntax:

physics_joint_wheel_create(inst1, inst2, anchor_x, anchor_y, axis_x, axis_y, enableMotor, max_motor_torque, motor_speed, freq_hz, damping_ratio, col)

Argument | Description
inst1 | The first instance to connect with the joint
inst2 | The second instance to connect with the joint
anchor_x | The x coordinate where the joint is anchored, within the game world
anchor_y | The y coordinate where the joint is anchored, within the game world
axis_x | The x component of the wheel axis vector
axis_y | The y component of the wheel axis vector
enableMotor | Whether the motor should be active (true) or not (false)
max_motor_torque | Sets the maximum motor torque used to achieve the desired motor speed (in Newtons per meter)
motor_speed | This is the speed at which the motor should rotate
freq_hz | This is the oscillation frequency for the joint, in hertz
damping_ratio | This damping ratio for the joint
col | Whether the two instances can collide (true) or not (false)

Returns: index of the joint

Description

A wheel joint simply combines a piston and a revolute joint, like a wheel mounted on the shock absorber of a car. You specify the anchor point for the joint well as the two physics enabled instances to joint, and the first instance will act as the "body" for the joint, while the second will be the "wheel", and be permitted to move freely around the joint axis. You can also set an axis vector, which is the imaginary line along which the joint will act as a "spring" permitting the wheel to bounce up and down along it as it encounters obstacles (much like the piston joint). The following image illustrates this:

If you choose to enable a motor, then the second instance will rotate around the anchor position, and you can set the maximum motor torque used to achieve the desired motor speed (N/m) as well as the speed at which the motor should turn. Since the wheel joint also has an axis along which it may move, you can set the oscillation frequency (in Hz) as well as the damping ratio for the joint - you may need to play with these values to fine tune them and it is recommended that you start off with smaller values and increment them until you get the effect that you desire.

As with all the joints, if you set the "col" value to true then the two instances can interact and collide with each other but only if they have collision events, however if it is set to false, they will not collide no matter what.

Example:

var mainFixture = physics_fixture_create();
physics_fixture_set_box_shape(mainFixture, 128, 32);
var wheelFixture = physics_fixture_create();
physics_fixture_set_circle_shape(wheelFixture, 32);
var o_id = instance_create(x+25, y + 100, obj_Wheel);
physics_fixture_bind(mainFixture, id);
physics_fixture_bind(wheelFixture, o_id);
physics_joint_wheel_create(id, o_id, o_id.x, o_id.y, 0, 1, true, 10, 1, 15, 6, false);
physics_fixture_delete(mainFixture);
physics_fixture_delete(wheelFixture);

The above code creates and defines two new fixtures. These are then bound to the calling instance and a new instance that is created before having a wheel joint applied to connect them, after which the fixtures are deleted from memory.

Back: Joints
Next: physics_joint_weld_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Physics Variables

Objects have certain variables associated with them automatically when used in the physics world.

As with the "traditional" collisions and movement system, the physics system also has a series of instance variables assigned to each instance of an object when it is created. Some of these properties can be defined by the user in GML, but many are read-only and still more are only applicable in the collision event.

Variables

The following variables exists in all physics enabled objects and they can be read to and written to (ie: changed) using code from instances and scripts:

  1. phy_active
  2. phy_angular_velocity
  3. phy_angular_damping
  4. phy_linear_velocity_x
  5. phy_linear_velocity_y
  6. phy_linear_damping
  7. phy_speed_x
  8. phy_speed_y
  9. phy_position_x
  10. phy_position_y
  11. phy_position_xprevious
  12. phy_position_yprevious
  13. phy_rotation
  14. phy_fixed_rotation
  15. phy_bullet

Read Only Variables

Certain variables are read-only variables, which means that the information they contain cannot be changed through instance code or scripts (but it can be changed internally by GameMaker: Studio which is why these are variables and not constants). The following table shows the read-only variables that exist in all physics enabled objects:

  1. phy_speed
  2. phy_com_x
  3. phy_com_y
  4. phy_dynamic
  5. phy_kinematic
  6. phy_inertia
  7. phy_mass
  8. phy_sleeping

Collision Only Variables

Finally, there are a number of temporary variables that exist in physics enabled objects and are created only in the collision event. These variables are like those listed above and are read-only:

  1. phy_collision_points
  2. phy_collision_x
  3. phy_collision_y
  4. phy_col_normal_x
  5. phy_col_normal_y

Back: Physics

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


phy_active

Enables (or disables) an instance in the physics world.

Syntax:

phy_active;

Returns: Boolean

Description

This variable controls whether or not the instance is currently "active". Setting it to false will prevent the instance from participating in the physics world, and setting it to true will have it participating again. Please note that this is not the same as deactivating the instance, as the instance is still visible on the screen and can still be changed through code, rather this function just prevents it from participating in the physics simulation.

Example:

if keyboard_check_pressed(ord"P")
{
global.Pause = !global.Pause
with (obj_Parent)
{
phy_active = !global.Pause;
}
}

The above code will detect a keypress of the letter "P" and then toggle the global variable "Pause" from true to false and back again. This variable is then used to set whether physics is active or not in the children instances of the object indexed in the variable "obj_Parent".

Back: Physics Variables
next: phy_angular_velocity


phy_angular_damping

Gets or sets the angular damping of an instance.

Syntax:

phy_angular_damping;

Returns: Real

Description

This variable can be used to set the angular damping of the instance, or it can be used to get the current angular damping. The damping is the amount of "resistance" to angular rotation that the physics enabled instance has, with a lower value permitting the instance to rotate faster after a collision (for example) and a higher value making it require a more forceful push and rotate slower.

Example:

if place_meeting(phy_position_x, phy_position_y, obj_Water)
{
phy_angular_damping = 10;
}
else
{
phy_angular_damping = 3;
}

The above code will check for a collision between the calling instance and instances of "obj_Water" and change the angular damping accordingly.

Back: Physics Variables
next: phy_linear_velocity_x


phy_angular_velocity

Gets or sets the angular velocity of an instance.

Syntax:

phy_angular_velocity;

Returns: Real

Description

This variable can be used to set the angular velocity of the instance, or it can be used to get the current angular velocity, in degrees per second and the value used can be either positive (for clockwise rotation) or negative (for anticlockwise rotation). If you set this on an instance that was previously static (ie: it has a density of 0) it will become a kinematic object and begin rotating.

Example:

if abs(phy_angular_velocity) > 0
{
phy_angular_velocity -= sign(phy_angular_velocity) * 0.01;
}
else
{
phy_angular_velocity = 0;
}

The above code will check the angular velocity of the instance and if it is not 0 it will then add (or subtract) a small amount every step until the value is 0.

Back: Physics Variables
next: phy_angular_damping


phy_bullet

Tells the physics engine that this object is a bullet.

Syntax:

phy_bullet;

Returns: Boolean

Description

This variable defines whether or not the instance is extremely fast moving (for example a bullet). The default value is false but if set to true this tells GameMaker: Studio that the instance will be moving at such high speeds that it will require more expensive collision detection to ensure it doesn't pass through other instances undetected.

Example:

with (instance_create(x, y, obj_Shoot))
{
phy_bullet = true;
physics_apply_local_impulse(0, 10, 0, 200);
}

The above code creates a new instance and then defines it as being a "bullet" in the physics world before giving it a massive impulse along the y axis.

Back: Physics Variables
next: phy_speed


phy_col_normal_x

Returns the x component of the collision normal for the associated collision point.

Syntax:

phy_col_normal_x;

Returns: Boolean

Description

This read-only variable returns the x component of the collision normal corresponding to the phy_collision_x array value. For each contact point there is an associated contact normal (which is usually the same normal for all points of contact in the collision). This contact normal is a unit vector that points from one instance in the collision to another, and can be used, for example, to calculate the correct "push" direction to resolve collisions.

NOTE: This variable is only available in the collision event of a physics enabled instance.

Example:

repeat(5 + irandom(5))
{
with (instance_create(x, y, obj_Debris)
{
physics_apply_local_impulse(0, 0, other.phy_col_normal_x[0], other.phy_col_normal_y[0]);
}
}

The above code uses the contact normal to set the direction of movement for an instance created in the collision event between two physics enabled instances.

Back: Physics Variables
next: phy_col_normal_y


phy_col_normal_y

Returns the y component of the collision normal for the associated collision point.

Syntax:

phy_col_normal_y;

Returns: Boolean

Description

This read-only variable returns the y component of the collision normal corresponding to the phy_collision_y array value. For each contact point there is an associated contact normal (which is usually the same normal for all points of contact in the collision). This contact normal is a unit vector that points from one instance in the collision to another, and can be used, for example, to calculate the correct "push" direction to resolve collisions.

NOTE: This variable is only available in the collision event of a physics enabled instance.

Example:

repeat(5 + irandom(5))
{
with (instance_create(x, y, obj_Debris)
{
physics_apply_local_impulse(0, 0, other.phy_col_normal_x[0], other.phy_col_normal_y[0]);
}
}

The above code uses the contact normal to set the direction of movement for an instance created in the collision event between two physics enabled instances.

Back: Physics Variables
next: phy_active


phy_collision_points

Returns the number of points of contact in a collision.

Syntax:

phy_collision_points;

Returns: Real

Description

This read-only variable returns the number of points of collision detected between the two objects in the collision.

NOTE: This variable is only available in the collision event of a physics enabled instance.

Example:

var i;
for(i = 0; i < phy_collision_points; i += 1;)
{
part_particles_create(global.Sname, phy_collision_x[i], phy_collision_x[1], global.Spark, 5);
}

The above code creates particles at all the defined points of a collision between two physics enabled instances.

Back: Physics Variables
next: phy_collision_x


phy_collision_x

Returns the x position of a collision point.

Syntax:

phy_collision_x;

Returns: Real

Description

This read-only array returns the x position of all points detected in a collision between two physics enabled instances.

NOTE: This variable is only available in the collision event of a physics enabled instance.

Example:

var i;
for(i = 0; i < phy_collision_points; i += 1;)
{
part_particles_create(global.Sname, phy_collision_x[i], phy_collision_y[i], global.Spark, 5);
}

The above code creates particles at all the defined points of a collision between two physics enabled instances.

Back: Physics Variables
next: phy_collision_y


phy_collision_y

Returns the y position of a collision point.

Syntax:

phy_collision_y;

Returns: Real

Description

This read-only array returns the y position of all points detected in a collision between two physics enabled instances.

NOTE: This variable is only available in the collision event of a physics enabled instance.

Example:

var i;
for(i = 0; i < phy_collision_points; i += 1;)
{
part_particles_create(global.Sname, phy_collision_x[i], phy_collision_y[i], global.Spark, 5);
}

The above code creates particles at all the defined points of a collision between two physics enabled instances.

Back: Physics Variables
next: phy_col_normal_x


phy_com_x

The x position of the center of mass.

Syntax:

phy_com_x;

Returns: Real

Description

This read-only variable will return the x position of the instances center of mass. This is calculated automatically based on the density, inertia and mass of the instance as defined by the appropriate functions.

Example:

xx = phy_com_x;
yy = phy_com_y;

The above code sets two variables to the x and y position of the instances center of mass.

Back: Physics Variables
next: phy_com_y


phy_com_y

The y position of the center of mass.

Syntax:

phy_com_y;

Returns: Real

Description

This read-only variable will return the y position of the instances center of mass. This is calculated automatically based on the density, inertia and mass of the instance as defined by the appropriate functions.

Example:

xx = phy_com_x;
yy = phy_com_y;

The above code sets two variables to the x and y position of the instances center of mass.

Back: Physics Variables
next: phy_dynamic


phy_dynamic

Returns whether the instance is dynamic or not.

Syntax:

phy_dynamic;

Returns: Boolean

Description

A dynamic instance is one that is fully simulated within the physics world and this read-only variable will return true if the instance being checked is fully simulated or false if it is not.

Example:

if other.phy_dynamic
{
with (other)
{
var dir;
dir = point_direction(x, y, other.x, other.y);
physics_apply_impulse(x, y, x + lengthdir_x(100, dir), y + lengthdir_y(100, dir));
}
}

The above code creates a new instance and then defines it as being a "bullet" in the physics world before giving it a massive impulse along the y axis.

Back: Physics Variables
next: phy_kinematic


phy_fixed_rotation

Enables (or disables) rotation from external forces.

Syntax:

phy_fixed_rotation;

Returns: Boolean

Description

This variable can be used to set whether or not the instance can be affected by rotational forces (default is false). If this is set to true, no external force (either from coded impulses or forces, or from collisions) will affect the rotation value of the instance and this would have to be set manually using the phy_rotation variable.

Example:

phy_rotation = 0;
phy_fixed_rotation = true;

The above code will switch the instance to have a fixed rotation, then set the rotation angle.

Back: Physics Variables
next: phy_bullet


phy_inertia

Returns the inertia of the instance.

Syntax:

phy_inertia;

Returns: Real

Description

Inertia is the measure of how hard it is to make something start or stop moving, so the lower the value for this read-only variable and the easier it will be to set the instance in motion, while higher values will require more force to start it moving.

Example:

physics_mass_properties(70, -10, -10, phy_inertia);

The above code will change the mass and center of mass of the instance while maintaining the inertia value.

Back: Physics Variables
next: phy_mass


phy_kinematic

Returns whether the instance is a kinematic body or not.

Syntax:

phy_kinematic;

Returns: Boolean

Description

This read-only variable will return true if the instance is classed as being a kinematic object, or false if it is not. A kinematic instance is one that has infinite mass (a density of 0) but can move. So, to make an instance kinematic, you would first create a static instance and then set one or more of the instance variables related to movement (ie: phy_speed_x).

Example:

if !phy_kinematic
{
phy_speed_x = 5;
}

The above code checks to see if the instance is kinematic and if it is not, it sets the horizontal speed to 5.

Back: Physics Variables
next: phy_inertia


phy_linear_damping

Gets or sets the linear damping of an instance.

Syntax:

phy_linear_damping;

Returns: Real

Description

This variable can be used to set the linear damping of the instance, or it can be used to get the current linear damping. The damping is the amount of "resistance" to forward movement that the physics enabled instance has, with a lower value permitting the instance to move and accelerate faster and a higher value making it require a more forceful push.

Example:

if place_meeting(phy_position_x, phy_position_y, obj_Water)
{
phy_linear_damping = 10;
}
else
{
phy_linear_damping = 3;
}

The above code will check for a collision between the calling instance and instances of "obj_Water" and change the linear damping accordingly.

Back: Physics Variables
next: phy_speed_x


phy_linear_velocity_x

The x component of the velocity vector.

Syntax:

phy_linear_velocity_x;

Returns: Real

Description

This variable can be used to get or to change the x component the instances linear velocity vector and is defined in pixels per second (for pixels per step, see phy_speed_x). Altering this for a static instance (ie: an instance with 0 density) will turn it into a kinematic instance.

Example:

if phy_linear_velocity_x != 0
{
phy_linear_velocity_x = 0;
}

The above code will check the x component of the linear velocity vector and if it is anything other than 0 it will set it to 0.

Back: Physics Variables
next: phy_linear_velocity_y


phy_linear_velocity_y

The y component of the velocity vector.

Syntax:

phy_linear_velocity_y;

Returns: Real

Description

This variable can be used to get or to change the y component the instances linear velocity vector and is defined in pixels per second (for pixels per step, see phy_speed_y). Altering this for a static instance (ie: an instance with 0 density) will turn it into a kinematic instance.

Example:

if phy_linear_velocity_y != 0
{
phy_linear_velocity_y = 0;
}

The above code will check the y component of the linear velocity vector and if it is anything other than 0 it will set it to 0.

Back: Physics Variables
next: phy_linear_damping


phy_mass

Returns the mass of the instance.

Syntax:

phy_mass;

Returns: Real

Description

This read-only variable returns the mass of the instance in kilograms. This value is calculated automatically based on the surface area of the assigned fixtures and their density values, but it can be changed using the function physics_mass_properties.

Example:

if phy_mass < other.phy_mass
{
instance_destroy();
}

The above code is from the collision event of the instance with another and it compares the mass of each instance and destroys that which has less mass.

Back: Physics Variables
next: phy_sleeping


phy_position_x

The x position of the instance in the physics world.

Syntax:

phy_position_x;

Returns: Real

Description

This variable can be used to get (or to set) the x position of the instance within the game room physics world. Please note that the physics world may present errors when instances are moved by directly setting this variable as it will interrupt the continuous simulation.

Example:

xx = phy_position_x;
yy = phy_position_y;

The above code stores the instance x and y position in two variables.

Back: Physics Variables
next: phy_position_y


phy_position_xprevious

The previous x position of the instance in the physics world.

Syntax:

phy_position_xprevious;

Returns: Real

Description

This variable can be used to get (or to set) the previous x position of the instance within the game room physics world. This is the position of the instance within the physics world in the previous step to the current one.

Example:

xx = phy_position_xprevious;
yy = phy_position_yprevious;

The above code stores the previous x and y position for the physics enabled instance in two variables.

Back: Physics Variables
next: phy_position_yprevious


phy_position_y

The y position of the instance in the physics world.

Syntax:

phy_position_y;

Returns: Real

Description

This variable can be used to get (or to set) the y position of the instance within the game room physics world. Please note that the physics world may present errors when instances are moved by directly setting this variable as it will interrupt the continuous simulation.

Example:

xx = phy_position_x;
yy = phy_position_y;

The above code stores the instance x and y position in two variables.

Back: Physics Variables
next: phy_position_xprevious


phy_position_yprevious

The previous y position of the instance in the physics world.

Syntax:

phy_position_yprevious;

Returns: Real

Description

This variable can be used to get (or to set) the previous y position of the instance within the game room physics world. This is the position of the instance within the physics world in the previous step to the current one.

Example:

xx = phy_position_xprevious;
yy = phy_position_yprevious;

The above code stores the previous x and y position for the physics enabled instance in two variables.

Back: Physics Variables
next: phy_rotation


phy_rotation

The angle of rotation of the instance.

Syntax:

phy_rotation;

Returns: Real

Description

This variable can be used to get (or to set) the angle of the instances fixture in degrees, similar to setting or getting the image_angle. However note that in the physics world rotations are calculated in the opposite way to the normal GameMaker: Studio game world, meaning that vector functions like point_direction should have there return values modified (simply making positive to negative should resolve this).

Example:

if phy_speed_x > 0 || phy_speed_y > 0
{
phy_rotation += sqrt(sqr(phy_speed_x) + sqr(phy_speed_y)) /10;
}

The above code checks the linear speed and if either vector is not 0, it then calculates the actual speed and uses that to set the rotation.

Back: Physics Variables
next: phy_fixed_rotation


phy_sleeping

Returns the active state of the instance.

Syntax:

phy_sleeping;

Returns: Boolean

Description

This read-only variable returns whether or not the instance is currently "sleeping" (true) or not (false), A "sleeping" instance is one that is not actively engaged in any physical simulation. GameMaker: Studio will put objects to sleep to save simulation cycles when an instance is at rest and not in collision with another instance.

Example:

if phy_sleeping
{
instance_destroy();
}

The above code checks to see if the object is being actively simulated or not and if it is not it is destroyed.

Back: Physics Variables
next: phy_collision_points


phy_speed

Returns the speed of the physics enabled instance.

Syntax:

phy_speed;

Returns: Real

Description

This read-only variable returns the speed as a value in pixels-per-second of the physics enabled instance. Should you need to change this value, you must do so by changing the x and y vectors using the variables phy_speed_x and phy_speed_y.

Example:

if phy_speed > 10
{
phy_linear_damping += 0.01;
}
else
{
phy_linear_damping = 2;
}

The above code checks the speed of the physics enabled instance and then changes the linear damping based on the returned value.

Back: Physics Variables
next: phy_com_x


phy_speed_x

The x component of the speed vector.

Syntax:

phy_speed_x;

Returns: Real

Description

This variable can be used to get or to change the x component the instances linear speed vector and is defined in pixels per step (for pixels per second, see phy_linear_velocity_x). Altering this for a static instance (ie: an instance with 0 density) will turn it into a kinematic instance.

Example:

if phy_speed_x != 0
{
phy_speed_x = 0;
}

The above code will check the x component of the linear speed vector and if it is anything other than 0 it will set it to 0.

Back: Physics Variables
next: phy_speed_y


phy_speed_y

The y component of the speed vector.

Syntax:

phy_speed_y;

Returns: Real

Description

This variable can be used to get or to change the y component the instances linear speed vector and is defined in pixels per step (for pixels per second, see phy_linear_velocity_y). Altering this for a static instance (ie: an instance with 0 density) will turn it into a kinematic instance.

Example:

if phy_speed_y != 0
{
phy_speed_y = 0;
}

The above code will check the y component of the linear speed vector and if it is anything other than 0 it will set it to 0.

Back: Physics Variables
next: phy_position_x


Soft Body Particles

Functions and information relevant to the use of the soft body particles in the physics world.

GameMaker: Studio uses the Box2D rigid body physics library, and as such does not permit soft body physics. However the Liquid Fun extension adds particles to the physics system, which permit the creation of simulated soft-bodies using rigid body physics. Basically, you can create a shape of particles that maintain cohesion and so simulate a full body, which, due to the interaction of the particles, gives the impression of a soft body. You can also use the physics particles to simulate liquids and other particle based physics systems.

Getting and Setting Particle Data

Before you start to create your physics particles you will need to set the basic physics properties for them, as you would a fixture in the regular physics. Note though that setting these properties will affect all particles created previously as well as any new particles that you create, so you would normally only use these functions at the start of the game or level. However there are specific functions available to set the particle flags for individual particles (and groups of particles) which will change their properties like "bounciness" or "viscosity", enabling you to create different types of particle within the ranges of these global settings.

The following functions are available for setting and getting global particle system data:

  1. physics_particle_count
  2. physics_particle_group_count
  3. physics_particle_set_max_count
  4. physics_particle_set_radius
  5. physics_particle_set_density
  6. physics_particle_set_damping
  7. physics_particle_set_gravity_scale
  8. physics_particle_get_max_count
  9. physics_particle_get_radius
  10. physics_particle_get_density
  11. physics_particle_get_damping
  12. physics_particle_get_gravity_scale

You also have the following functions available for setting flags on individual particles (or groups of particles), as well as for getting information, like position or colour, from a single particle or a single group:

  1. physics_particle_set_flags
  2. physics_particle_set_category_flags
  3. physics_particle_set_group_flags
  4. physics_particle_get_group_flags
  5. physics_particle_group_get_inertia
  6. physics_particle_group_get_centre_x
  7. physics_particle_group_get_centre_y
  8. physics_particle_group_get_vel_x
  9. physics_particle_group_get_vel_y
  10. physics_particle_group_get_ang_vel
  11. physics_particle_group_get_x
  12. physics_particle_group_get_y
  13. physics_particle_group_get_angle
  14. physics_particle_get_data
  15. physics_particle_get_data_particle
  16. physics_particle_group_get_data

Creating Particles

You can create particles in two ways - individually or in groups. Individual particles will behave exactly as defined by the global settings and the flags that were set when they were created, but groups of particles can exhibit different behaviours depending on their group flags. These group flags can be set to different values to give the group different properties, like penetration and rigidity.

The following functions are available for creating particles:

  1. physics_particle_create
  2. physics_particle_group_begin
  3. physics_particle_group_circle
  4. physics_particle_group_box
  5. physics_particle_group_polygon
  6. physics_particle_group_add_point
  7. physics_particle_group_end
  8. physics_particle_group_join
  9. physics_particle_group_delete

Deleting Particles

Not only can you create particles, but you can delete them too, either individually or in a region. The following functions are available for deleting particles from the system:

  1. physics_particle_delete
  2. physics_particle_delete_region_circle
  3. physics_particle_delete_region_box
  4. physics_particle_delete_region_poly

Drawing Particles

Unless you have activated the debug drawing using physics_draw_debug(), you won't see any particles on the screen when you create them. Therefore to actually see the particles, you need to draw them to the screen in the Draw Event of an instance using the following functions (note that you can also draw them using the regular draw_sprite functions if you get the data for each particle using the functionphysics_particle_get_data):

  1. physics_particle_draw
  2. physics_particle_draw_ext

Back: Physics
Next: Physics Variables

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_count

Retrieve the number of particles currently active in a physics simulation.

Syntax:

physics_particle_count()

Returns: Real

Description

This function will return the number of particles that are active in a physics enabled room.

Example:

if physics_particle_count() < physics_particle_get_max_count()
{
physics_particle_create(0, x, y, 0, 0, c_white, 1, 1)
}

The above code will check to see if there are less than the maximum number of permitted particles in the room, and if so create one more.

Back: Soft Body Particles
Next: physics_particle_group_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_create

Create a single soft body particle with the given parameters.

Syntax:

physics_particle_create(flags, x, y, xv, yv, col, alpha, category)

Argument | Description
flags | The flags to set on the particle.
x | The x position to create the particle at.
y | The y position to create the particle at.
xv | The initial horizontal velocity.
yv | The initial vertical velocity.
col | The base colour to use for the particle.
alpha | The base alpha to use for the particle.
category | The user defined category to which the particle belongs.

Returns: Real

Description

With this function you can create a single particle anywhere within your game room, setting certain flags and properties. The "flags" are the return value of a combination of the following constants:

Constant | Description
phy_particle_flag_water | The default properties for a soft body particle.
phy_particle_flag_zombie | A zombie particle is one that will be destroyed after a single step with all others flagged in this way.
phy_particle_flag_wall | This defines the particle as static, essentially creating it as an immovable object in the physics simulation, as they will remain in a fixed position no matter what collides with them. You should use this flag rather than set the density to 0.
phy_particle_flag_spring | Spring particles produce the effect of being attached to one another, as if by a spring. Particles created with this flag are "connected" in pairs, with each particle being connected to the one that was closest to it at the time of creation. Once paired, particles do not change "partners" , and the farther an external force pulls them from one another, the greater the power with which they will collide when that external force is removed. Note that no matter how far paired particles get from each another, the connection between them will not snap.
phy_particle_flag_elastic | Elastic particles deform and may also bounce when they collide with other rigid bodies in the physics simulation.
phy_particle_flag_viscous | A viscous particle is one that exhibits "clinginess" or "stickiness", like oil. Viscous particles will clump and stick together more.
phy_particle_flag_powder | Powder particles produce a scattering effect such as you might see with sand or dust.
phy_particle_flag_tensile | Tensile particles are used to produce the effect of surface tension, or the taut curvature on the surface of a body of liquid. They might be used, for example, to create the surface tension you would see on a drop of water. Once the tension is broken, the particles bounce as if they were elastic, but also continue to attract each other. As a result, particles tend to form clusters as they bounce.
phy_particle_flag_colourmixing | Colour-mixing particles take on some of the colour of other particles with which they collide. Note that if only one of the two colliding particles is a colour-mixing one, the other particle retains its pre-collision colour.

These flags use bit-masking to create a final output value that is then checked to set the different basic properties of the particle (with the base property always being that of phy_particle_flag_water). For example, if you want to simulate a viscous liquid with surface tension you would use the bitwise or "|" to flag the appropriate bits as shown in the example below. In this way you can set different properties (other than the global properties) for each individual particle created.

Other than the flags, you can also set the position in the room to create the particle at, the initial horizontal and vertical velocity, the initial colour and alpha, as well as the user category. The colour and alpha values are only used when drawing the particle using the function physics_particle_draw(), but the category value is used in multiple other functions. This value is an arbitrary integer value that you give each particle that you want to have similar properties, and it can be used to set flags later for that specific category as well as a number of other things. For example, if you have defined a "water" and an "oil" particle, you would give all those particles flagged as "water" the user category of 1 and all those particles created as "oil" the user category of 2, permitting you to later target a single category to change it's flags or get specific data.

NOTE: You can use any integer value for the category except 0 which is reserved by the simulation and is used to select all categories in other functions (like for drawing).

The function returns a unique index (or ID) value for the particle which can be stored in a variable to be used in other functions that reference the particle directly.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
var x_vel = lengthdir_x(5, image_angle);
var y_vel = lengthdir_y(5, image_angle);
var p = physics_particle_create(flags, x, y, x_vel, y_vel, c_white, 1, 1)

The above code will create variables to set the particle type and it's initial velocity, then use these to create a particle at the instances x/y position.

Back: Soft Body Particles
Next: physics_particle_group_begin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_delete

Delete a particle group from the physics simulation.

Syntax:

physics_particle_group_delete(ind)

Argument | Description
ind | The index (ID) of the particle to delete.

Returns: N/A

Description

With this function you can delete (remove) a particle from the physics simulation in the current room. The function takes the unique ID of the particle to delete, as returned by the function physics_particle_create().

Example:

physics_particle_delete(part);

The above code will delete the particle with the ID stored in the variable "part" from the simulation.

Back: Soft Body Particles
Next: physics_particle_delete_region_circle


physics_particle_delete_region_box

Delete all particles from a rectangular area within the physics simulation.

Syntax:

physics_particle_delete_region_box(x, y, halfWidth, halfHeight)

Argument | Description
x | The x position of the center of the area to delete.
y | The y position of the center of the area to delete.
halfWidth | The half width of the rectangle.
halfHeight | The half height of the rectangle.

Returns: N/A

Description

With this function you can delete (remove) all the particles that fall within the bounds of the defined rectangular area from the physics simulation in the current room. The function takes the x and y position for the center of the area to delete as well as the half width and height of the rectangle (in pixels) which defines the area.

Example:

physics_particle_delete_region_box(mouse_x, mouse_y, 32, 32);

The above code will delete all particles found in a rectangular area around the mouse position.

Back: Soft Body Particles
Next: physics_particle_delete_region_poly


physics_particle_delete_region_circle

Delete all particles from a circular area within the physics simulation.

Syntax:

physics_particle_delete_region_circle(x, y, radius)

Argument | Description
x | The x position of the center of the area to delete.
y | The y position of the center of the area to delete.
radius | The radius (in pixels) of the circular area to delete.

Returns: N/A

Description

With this function you can delete (remove) all the particles that fall within the bounds of the defined circular area from the physics simulation in the current room. The function takes the x and y position for the center of the area to delete as well as the radius (in pixels) which defines the circular area.

Example:

physics_particle_delete_region_circle(mouse_x, mouse_y, 32);

The above code will delete all particles found in a circular area around the mouse position.

Back: Soft Body Particles
Next: physics_particle_delete_region_box

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_delete_region_poly

Delete all particles from a polygonal area within the physics simulation.

Syntax:

physics_particle_delete_region_poly(pointList)

Argument | Description
pointList | A ds_list of points to use to create the polygon.

Returns: N/A

Description

With this function you can delete (remove) all the particles that fall within the bounds of the defined polygonal area from the physics simulation in the current room. The function takes a (previously created) ds_list() containing the x/y position of each point of the polygon, with the even numbered positions in the list being the x coordinates, and odd numbered positions the y coordinates, ie: for a triangle, your list would have six entries, with entry 0, 2, and 4 being the x coordinates and 1, 3, and 5 being the y coordinates. The polygon will then be used to delete all the particles that fall within the defined area.

Note that the polygon defined must have at least three points, and at most 8.

Example:

var list = ds_list_create(p_list);
for (var i = 0; i < 5; i ++;)
{
ds_list_add(p_list, mx[i]);
ds_list_add(p_list, my[i]);
}
physics_particle_delete_region_poly(p_list);
ds_list_destroy(p_list);

The above code will delete all particles found in the polygonal area defined by the points added to the ds_list.

Back: Soft Body Particles
Next: physics_particle_draw

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_draw

Draw a set of particles using a sprite with the default values.

Syntax:

physics_particle_draw(typemask, category, sprite, subimg)

Argument | Description
typemask | The mask to compare the particles flags with.
category | The user defined category to draw (use 0 to draw all categories).
sprite | The sprite to use for each particle.
subimg | The image_index of the sprite to draw.

Returns: N/A

Description

This function will draw a sprite at the position of all the particles that share the same user defined category value, and that have flags which coincide with those set for the mask. The mask value is defined in the same way as you would define the flags when creating the particle (see the function physics_particle_create for an example), ie: using the bitwise or "|" to mask off the appropriate bits for each flag.

NOTE: This function will draw all particles in the physics simulation with flags that coincide with those of the mask, whether they are individual particles or groups, if the user category is the same.

The drawn particle will use the colour and alpha values set when you created it, and will rotate with the angular momentum of the particle. However should you wish to scale the sprite or change any other of its drawn properties you should use the function physics_particle_draw_ext.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
physics_particle_draw(flags, 2, sprBlob, 0);

The above code will draw a sprite for all the particles in the user defined category "2" which have the same flags as the given mask.

Back: Soft Body Particles
Next: physics_particle_draw_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_draw_ext

Draw a set of particles using a sprite with the default values.

Syntax:

physics_particle_draw_ext(typemask, category, sprite, subimg, xscale, yscale, ang, col, alpha)

Argument | Description
typemask | The mask to compare the particles flags with.
category | The user defined category to draw (use 0 to draw all categories).
sprite | The sprite to use for each particle.
subimg | The image_index of the sprite to draw.
xscale | The scale factor to apply to the sprite along the x axis.
yscale | The scale factor to apply to the sprite along the y axis.
ang | The angle (in degrees) to draw the sprite at.
col | The colour to blend with the sprite (default is c_white).
alpha | The alpha value to use when drawing (0 - 1).

Returns: N/A

Description

This function will draw a sprite at the position of all the particles that share the same user defined category value, and that have flags which coincide with those set for the mask. The mask value is defined in the same way as you would define the flags when creating the particles (see the functions physics_particle_create for an example), ie: using the bitwise or "|" to mask off the appropriate bits for each flag.

NOTE: This function will draw all particles in the physics simulation with flags that coincide with those of the mask, whether they are individual particles or groups, if the user category is the same.

The drawn particle will ignore the colour and alpha values set when you created it, and will instead be drawn using the scale, angle, colour and alpha parameters given in this function. Note that this is purely for drawing a sprite at the particle position and in no way affects the behaviour of the particle.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
physics_particle_draw_ext(flags, 2, sprBlob, 0, 2, 2, 0, c_white, 0.5);

The above code will draw a sprite for all the particles in the user defined category "2" which have the same flags as the given mask, scaled by 2 along both axis and with an alpha of 0.5.

Back: Soft Body Particles
Next: physics_particle_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_get_damping

Get the current linear damping value as defined for all particles.

Syntax:

physics_particle_get_damping()

Returns: Real

Description

With this function you can find out what the current linear damping is for particles in the physics simulation (you can set this value using physics_particle_set_damping()).

Example:

if physics_particle_get_damping() < 1
{
physics_particle_set_damping(physics_particle_get_damping() + 0.01);
}

The above code will check the current damping value for all particles in the system and if it is less than 1 then it will add 0.01 to it.

Back: Soft Body Particles
Next: physics_particle_get_gravity_scale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_get_data

Get data on individual particles in your physics simulation.

Syntax:

physics_particle_get_data(buffer, flags)

Argument | Description
buffer | The (previously created) buffer to use to store the data.
flags | The flags to use to extract data about specific particle types.

Returns: Buffer data

Description

This function returns various pieces of information about each particle in the physics simulation using the given flags checked. The buffer used must have been created previously using the function buffer_create(), and should be of the "grow" type, with the size being approximately that of the expected return data. The flags are set using any of the constants given below, and you would use the bitwise or "|" to create a single flag value to get the desired information.

Constant | Description | Data Type
phy_particle_data_flag_typeflags | The flags value for the particle. | buffer_u32
phy_particle_data_flag_position | The x and y position of the particle. | 2 x buffer_f32
phy_particle_data_flag_velocity | The horizontal and vertical speed. | 2 x buffer_f32
phy_particle_data_flag_colour | The colour and alpha value (hexadecimal). | buffer_f32
phy_particle_data_flag_category | The particle category (as defined when you created the particle or group to which it belongs). | buffer_f32

Example:

var count = physics_particle_count();
var flags = phy_particle_data_flag_position | phy_particle_data_flag_colour;
if (count > 0)
{
var buffer = buffer_create(count * 12, buffer_grow, 4);
physics_particle_get_data(buffer, flags);
for (var n = 0; n < count; n++;)
{
var xx = buffer_read(buffer, buffer_f32);
var yy = buffer_read(buffer, buffer_f32);
var argb = buffer_read(buffer, buffer_u32);
var alpha = (argb >> 24) & 255;
draw_sprite_ext(sprBlob, 0, xx, yy, 1, 1, 0, c_green, alpha);
}
buffer_delete(buffer);
}

The above code gets the number of particles and creates a variable with the data flags to check, then checks to see if there are any particles in the room. If there are, a buffer is created and then filled with the particle data, which is checked and used to draw a sprite at the particle position.

Back: Soft Body Particles
Next: physics_particle_get_data_particle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_get_data_particle

Get data on individual particles in your physics simulation.

Syntax:

physics_particle_get_data_particle(ind, buffer, flags)

Argument | Description
ind | The index (ID) of the particle to get the data from.
buffer | The (previously created) buffer to use to store the data.
flags | The flags to use to extract data about specific particle types.

Returns: Buffer data

Description

This function returns various pieces of information about a single particle in the physics simulation using the given flags checked. The particle index (its ID) is that which was returned by the function physics_particle_create(), and the buffer used must have been created previously using the function buffer_create(). It should be of the "grow" type, with the size being approximately that of the expected return data. The flags themselves are set using the constants given below, and you would use the bitwise or "|" to create a single flag value to get the desired information.

Constant | Description | Data Type
phy_particle_data_flag_typeflags | The flags value for the particle. | buffer_u32
phy_particle_data_flag_position | The x and y position of the particle. | 2 x buffer_f32
phy_particle_data_flag_velocity | The horizontal and vertical speed. | 2 x buffer_f32
phy_particle_data_flag_colour | The colour and alpha value (hexadecimal). | buffer_f32
phy_particle_data_flag_category | The particle category (as defined when you created the particle). | buffer_f32

Example:

var part = physics_particle_create(flags, x, y, x_vel, y_vel, c_white, 1, 1)
var flags = phy_particle_data_flag_position | phy_particle_data_flag_velocity;
var buffer = buffer_create(16, buffer_grow, 4);
physics_particle_get_data_particle(part, buffer, flags);
px = buffer_read(buffer, buffer_f32);
py = buffer_read(buffer, buffer_f32);
pvelx = buffer_read(buffer, buffer_f32);
pvely = buffer_read(buffer, buffer_f32);
buffer_delete(buffer);

The above code gets the position and velocity of the particle indexed by the variable "part" and stores the data in a number of variables.

Back: Soft Body Particles
Next: physics_particle_group_get_data

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_get_density

Get the current density of all particles in the system.

Syntax:

physics_particle_get_damping()

Returns: Real

Description

With this function you can find out what the current density is for particles in the physics simulation (you can set this value using physics_particle_set_density()).

Example:

if physics_particle_get_density() < 1
{
physics_particle_set_density(physics_particle_get_density() + 0.01);
}

The above code will check the current density value for all particles in the system and if it is less than 1 then it will add 0.01 to it.

Back: Soft Body Particles
Next: physics_particle_get_damping

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_get_gravity_scale

Get the current gravity scale factor as defined for all particles.

Syntax:

physics_particle_get_gravity_scale()

Returns: Real

Description

With this function you can find out what the current gravity scale factor is for particles in the physics simulation (you can set this value using physics_particle_set_gravity_scale()).

Example:

physics_particle_set_gravity_scale(physics_particle_get_gravity_scale() + 0.1);

The above code will set the gravity scale.

Back: Soft Body Particles
Next: physics_particle_set_flags

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_get_group_flags

Get the group type flags for a group of particles.

Syntax:

physics_particle_get_group_flags(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the group flags for a group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

var flags = physics_particle_get_group_flags(group, flags);
if flags != phy_particle_group_flag_solid | phy_particle_group_flag_rigid
{
flags = phy_particle_group_flag_solid | phy_particle_group_flag_rigid;
physics_particle_set_group_flags(group, flags);
}

The above code will create a variable to store the flags value and then use it to check the flags of the group indexed in the variable "group". If they are not the same, the group is set with these flags.

Back: Soft Body Particles
Next: physics_particle_group_get_inertia

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_get_max_count

Get the maximum number of particles permitted in the physics simulation.

Syntax:

physics_particle_get_max_count()

Returns: Real

Description

With this function you can find out what the current cap value is on particles permitted in the physics simulation (you can set this value using physics_particle_set_max_count()).

Example:

if physics_particle_count() < physics_particle_get_max_count()
{
physics_particle_create(0, x, y, 0, 0, c_white, 1, 1)
}

The above code will check to see if there are less than the maximum number of permitted particles in the room, and if so create one more.

Back: Soft Body Particles
Next: physics_particle_get_radius

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_get_radius

Get the current radius defined for all particles.

Syntax:

physics_particle_get_radius()

Returns: Real

Description

With this function you can find out what the current radius (in pixels) is for particles in the physics simulation (you can set this value using physics_particle_set_radius()).

Example:

if physics_particle_get_radius() < 32
{
physics_particle_set_radius(physics_particle_get_radius() + 1);
}

The above code will check the current radius of the particles in the simulation and if it is less than 32, then it will increase their size by 1.

Back: Soft Body Particles
Next: physics_particle_get_density

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_add_point

Set the points of the polygon shape which will be used to create a group of soft body particles.

Syntax:

physics_particle_group_add_point(x, y)

Argument | Description
x | The x position in the room for the point.
y | The y position in the room for the point.

Returns: N/A

Description

This function sets a point in the room to define the shape of a polygon which will be used to create a group of soft body particles. You must have previously signalled to GameMaker: Studio that you are going define a polygon shape using the function physics_particle_group_polygon() and then use this function to define the individual points of the polygon. You must give at least three points when defining the polygon shape, but can give up to eight, and the function will permit the definition of concave polygons. However, if you generate a polygon with any cavities, the points within will be ignored and a convex shape will be created for the particle group.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
var groupflags = phy_particle_group_flag_solid;
physics_particle_group_begin(flags, groupflags, mouse_x, mouse_y, 0, 0, 0, 0, c_white, 1, 1, 2);
physics_particle_group_polygon();
physics_particle_group_add_point(200, 200);
physics_particle_group_add_point(300, 300);
physics_particle_group_add_point(100, 300);
mLastGroup = physics_particle_group_end();

The above code stores the flags for the particle type and the particle group properties in variables then uses these to create a polygon particle group of three sides at the mouse position.

Back: Soft Body Particles
Next: physics_particle_group_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_begin

Begin the creation of a soft body particle group with the given parameters.

Syntax:

physics_particle_group_begin(flags, groupflags, x, y, ang, xv, yv, ang_velocity, col, alpha, strength, category)

Argument | Description
flags | The flags to set on the particle.
groupflags | The group flags to set on the particle (see Description below).
x | The x position to create the particle group at.
y | The y position to create the particle group at.
ang | The angle (in degrees) to rotate the group to on create.
xv | The initial horizontal velocity.
yv | The initial vertical velocity.
ang_velocity | The initial angular velocity.
col | The base colour to use for the particle group.
alpha | The base alpha to use for the particle group.
strength | Set the cohesion strength between particles in the group.
category | The user defined category to which the group belongs.

Returns: N/A

Description

With this function you can create a group of particles in a room. A group of particles is one where the particles necessary to create a specific form are created all at once as a group, permitting you to create simulated soft-bodies with various properties set by the flags used. The "flags" are the return value of a combination of the particle constants (see the function physics_particle_create for details of these), while the "groupFlags" are a combination of the following group constants (or 0 for no flags):

Constant | Description
phy_particle_group_flag_solid | A solid particle group prevents other fixtures from lodging inside of it. Should anything penetrate it, the solid particle group pushes the offending fixture back out to its surface, making a a solid particle group possess an especially strong repulsive force.
phy_particle_group_flag_rigid | Rigid particle groups are ones whose shape does not change, even when they collide with other fixtures.

These group flags use bit-masking to create a final output value that is then checked to set the different basic properties of the group, apart from those set by the particle flags. You can use none, one or both of these constants by using the bitwise or "|" to mask the appropriate bits (as shown in the example below).

Other than the flags, you can also set the position in the room to create the particle group at (the position given will be the center of mass of the finished group), the initial horizontal and vertical velocity, as well as the angular velocity of the group, permitting you to create moving, rotating groups.

You can also set initial colour and alpha of all particles in the group, with the values being used when drawing the particles using the function physics_particle_draw(). After that you set the cohesive strength of particles in the group, which is another way of saying how stongly they "stick" to each other. The strength can be a value between 0 and 1, where 0 is no cohesion, and 1 is maximum cohesion.

Finally you have to give the category for your particle group. This value is an arbitrary integer value that you give each particle group that you want to have similar properties, and it can be used to set flags later for that specific category as well as a number of other things.

NOTE: You can use any integer value for the category except 0 which is reserved by the simulation and is used to select all categories in other functions (like for drawing).

It is important to note that calling this function does not create the group in the physics room. This function simply begins the process and sets the base particle properties for the group. To actually create the particle group you need to give it a form (see the example below) and then call the function physics_particle_group_end(), at which point it will be created.

NOTE: The particle type flags that you set will also influence the cohesion of the particle group, such that if you flag the particles as being of the water type (for example), when the group collides with another fixture it will break apart, while if you flag the particle as a spring type, then it will maintain its cohesion on collision.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
var groupflags = phy_particle_group_flag_solid | phy_particle_group_flag_rigid;
physics_particle_group_begin(flags, groupflags, mouse_x, mouse_y, 0, 0, 0, 0, c_white, 1, 1, 2);
physics_particle_group_circle(100);
mLastGroup = physics_particle_group_end();

The above code stores the flags for the particle type and the particle group properties in variables then uses these to create a circular particle group with a 100px radius at the mouse position.

Back: Soft Body Particles
Next: physics_particle_group_circle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_box

Set the form of a soft body particle group that is to be created to be a rectangle.

Syntax:

physics_particle_group_box(halfWidth, halfHeight)

Argument | Description
halfWidth | The half width of the box.
halfHeight | The half height of the box.

Returns: N/A

Description

This function will set the shape of the particle group that is being created. You must first have begun the group definition using the function physics_particle_group_begin(), and then you would use this function to set the approximate half width and half height of the group in pixels - approximate because the exact width and height will depend on the size of the base particles, as defined by the physics_particle_set_radius() function, as the physics simulation tries to "fit" as many of the particles as possible into the defined shape. Finally you need to call physics_particle_group_end() to create the group of particles in the room.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
var groupflags = phy_particle_group_flag_solid;
physics_particle_group_begin(flags, groupflags, mouse_x, mouse_y, 0, 0, 0, 0, c_white, 1, 1, 2);
physics_particle_group_box(100, 100);
mLastGroup = physics_particle_group_end();

The above code stores the flags for the particle type and the particle group properties in variables then uses these to create a rectangular particle group with with sides of 200px at the mouse position.

Back: Soft Body Particles
Next: physics_particle_group_polygon

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_circle

Set the form of a soft body particle group that is to be created to be a circle.

Syntax:

physics_particle_group_circle(radius)

Argument | Description
radius | The radius (in pixels) of the circle to create.

Returns: N/A

Description

This function will set the shape of the particle group that is being created. You must first have begun the group definition using the function physics_particle_group_begin(), and then you would use this function to set the approximate radius of the group in pixels - approximate because the exact radius will depend on the size of the base particles, as defined by the physics_particle_set_radius() function, as the physics simulation tries to "fit" as many of the particles as possible into the defined shape. Finally you need to call physics_particle_group_end() to create the group of particles in the room.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
var groupflags = phy_particle_group_flag_solid;
physics_particle_group_begin(flags, groupflags, mouse_x, mouse_y, 0, 0, 0, 0, c_white, 1, 1, 2);
physics_particle_group_circle(100);
mLastGroup = physics_particle_group_end();

The above code stores the flags for the particle type and the particle group properties in variables then uses these to create a circular particle group with a 100px radius at the mouse position.

Back: Soft Body Particles
Next: physics_particle_group_box

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_count

Retrieve the number of particles currently active in a single group.

Syntax:

physics_particle_group_count(group)

`
Argument | Description
group | The group index (ID) of the particle group to count.

Returns: Real

Description

This function will return the number of particles that are active in a single group. The group index (ID) is the value that is returned when you call the function physics_particle_group_end().

Example:

gp_num = physics_particle_group_count(group1);

The above code will get the number of particles used to make the group indexed in the variable "group1" and store the value in a variable.

Back: Soft Body Particles
Next: physics_particle_set_max_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_delete

Delete a particle group from the physics simulation.

Syntax:

physics_particle_group_delete(ind)

Argument | Description
ind | The index (ID) of the particle group to delete.

Returns: N/A

Description

With this function you can delete (remove) a particle group from the physics simulation in the current room. The function takes the unique group ID of the group to delete, as returned by the function physics_particle_group_end().

Example:

physics_particle_group_delete(gp1);

The above code will delete all the particles that comprise the group with the ID stored in the variable "gp1" from the simulation.

Back: Soft Body Particles
Next: physics_particle_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_end

Ends the definition of a particle group and creates it in the room.

Syntax:

physics_particle_group_end()

Returns: Real

Description

This function ends the definition of a particle group (which you should have begun using the function physics_particle_group_begin()), which in turn creates all the particles for the group within the game room. This function returns a unique ID value for the group just created which you can then store in a variable and use in other funtions.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
var groupflags = phy_particle_group_flag_solid;
physics_particle_group_begin(flags, groupflags, mouse_x, mouse_y, 0, 0, 0, 0, c_white, 1, 1, 2);
physics_particle_group_circle(100);
mLastGroup = physics_particle_group_end();

The above code stores the flags for the particle type and the particle group properties in variables then uses these to create a circular particle group with a 100px radius at the mouse position. The ID for the group that has been created is stored in the variable "mLastGroup".

Back: Soft Body Particles
Next: physics_particle_group_join

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_get_ang_vel

Get the angular velocity of a whole group of particles.

Syntax:

physics_particle_group_get_ang_vel(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the angular velocity of a group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

ang_v = physics_particle_group_get_ang_vel(group1);

The above code will get the angular velocity of the particle group indexed in the variable "group1" and store it in a variable.

Back: Soft Body Particles
Next: physics_particle_group_get_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_get_angle

Get the angle of a whole group of particles.

Syntax:

physics_particle_group_get_angle(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the rotation (angle) in the room of a group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

ang = physics_particle_group_get_angle(group1);

The above code will get the angle of the particle group indexed in the variable "group1" and store it in a variable.

Back: Soft Body Particles
Next: physics_particle_get_data

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_get_centre_x

Get the x position of the center of mass for a whole group of particles.

Syntax:

physics_particle_group_get_centre_x(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the x component of the center of mass of an entire group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

xx = physics_particle_group_get_centre_x(group1);
yy = physics_particle_group_get_centre_y(group1);

The above code will get the x and y position for the center of mass of the particle group indexed in the variable "group1" and store them in variables.

Back: Soft Body Particles
Next: physics_particle_group_get_centre_y


physics_particle_group_get_centre_y

Get the y position of the center of mass for a whole group of particles.

Syntax:

physics_particle_group_get_centre_y(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the y component of the center of mass of an entire group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

xx = physics_particle_group_get_centre_x(group1);
yy = physics_particle_group_get_centre_y(group1);

The above code will get the x and y position for the center of mass of the particle group indexed in the variable "group1" and store them in variables.

Back: Soft Body Particles
Next: physics_particle_group_get_vel_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_get_data

Get data on a group of particles in your physics simulation.

Syntax:

physics_particle_group_get_data(group, buffer, flags)

Argument | Description
group | The group index (ID) of the particle group to get the data from.
buffer | The (previously created) buffer to use to store the data.
flags | The flags to use to extract data about specific particle types.

Returns: Buffer data

Description

This function returns various pieces of information about a group of particles in the physics simulation using the given flags checked. The group index (its ID) is that which was returned by the function physics_particle_group_end(), and the buffer used must have been created previously using the function buffer_create(). It should be of the "grow" type, with the size being approximately that of the expected return data. The flags themselves are set using the constants given below, and you would use the bitwise or "|" to create a single flag value to get the desired information.

Constant | Description | Data Type
phy_particle_data_flag_typeflags | The flags value for the particle. | buffer_u32
phy_particle_data_flag_position | The x and y position of the particle. | 2 x buffer_f32
phy_particle_data_flag_velocity | The horizontal and vertical speed. | 2 x buffer_f32
phy_particle_data_flag_colour | The colour and alpha value (hexadecimal). | buffer_f32
phy_particle_data_flag_category | The particle category (as defined when you created the group to which it belongs). | buffer_f32

Example:

var count = physics_particle_group_count(gp);
var flags = phy_particle_data_flag_position | phy_particle_data_flag_colour;
if (count > 0)
{
var buffer = buffer_create(count * 12, buffer_grow, 4);
physics_particle_group_get_data(gp, buffer, flags);
for (var n = 0; n < count; n++;)
{
var xx = buffer_read(buffer, buffer_f32);
var yy = buffer_read(buffer, buffer_f32);
var argb = buffer_read(buffer, buffer_u32);
var alpha = (argb >> 24) & 255;
draw_sprite_ext(sprBlob, 0, xx, yy, 1, 1, 0, c_green, alpha);
}
buffer_delete(buffer);
}

The above code gets the position and velocity of the every particle in the group indexed by the variable "gp", stores the buffer data in a number of variables, and then uses that to draw a sprite at the position of each particle in the group.

Back: Soft Body Particles
Next: physics_particle_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_get_inertia

Get the inertia of a whole group of particles.

Syntax:

physics_particle_group_get_inertia(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the inertia of an entire group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

i = physics_particle_group_get_inertia(group1);

The above code will get the inertia of the particle group indexed in the variable "group1" and store it in a variable.

Back: Soft Body Particles
Next: physics_particle_group_get_centre_x


physics_particle_group_get_vel_x

Get the horizontal velocity of a whole group of particles.

Syntax:

physics_particle_group_get_vel_x(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the horizontal velocity of a group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

vx = physics_particle_group_get_vel_x(group1);
vy = physics_particle_group_get_vel_y(group1);

The above code will get the horizontal and vertical velocity of the particle group indexed in the variable "group1" and store them in variables.

Back: Soft Body Particles
Next: physics_particle_group_get_vel_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_get_vel_y

Get the vertical velocity of a whole group of particles.

Syntax:

physics_particle_group_get_vel_y(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the vertical velocity of a group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

vx = physics_particle_group_get_vel_x(group1);
vy = physics_particle_group_get_vel_y(group1);

The above code will get the horizontal and vertical velocity of the particle group indexed in the variable "group1" and store them in variables.

Back: Soft Body Particles
Next: physics_particle_group_get_ang_vel

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_get_x

Get the x position of a whole group of particles.

Syntax:

physics_particle_group_get_x(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the x position in the room of a group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

xx = physics_particle_group_get_x(group1);
yy = physics_particle_group_get_y(group1);

The above code will get the x and y positions of the particle group indexed in the variable "group1" and store them in variables.

Back: Soft Body Particles
Next: physics_particle_group_get_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_get_y

Get the y position of a whole group of particles.

Syntax:

physics_particle_group_get_y(group)

Argument | Description
group | The particle group to get.

Returns: Real

Description

With this function you can retrieve the y position in the room of a group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, and the function will return a value which is the combined value of the currently set flags.

Example:

xx = physics_particle_group_get_x(group1);
yy = physics_particle_group_get_y(group1);

The above code will get the x and y positions of the particle group indexed in the variable "group1" and store them in variables.

Back: Soft Body Particles
Next: physics_particle_group_get_angle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_join

Join two particle groups together.

Syntax:

physics_particle_group_join(to, from)

Argument | Description
to | The first particle group to join.
from | The second particle group to join.

Returns: N/A

Description

With this function you can join two particle groups together, and the joined groups will then behave as if they were both part of a single entity. The groups should have been created with over-lapping edges, as, if they are not already touching, they will not be joined. The function takes the unique group IDs of the groups to join, as returned by the function physics_particle_group_end(), and you can use the function any number of times for a single group to join various soft bodies together.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
var groupflags = phy_particle_group_flag_solid;
physics_particle_group_begin(flags, groupflags, mouse_x- 45, mouse_y, 0, 0, 0, 0, c_white, 1, 1, 2);
physics_particle_group_circle(50);
var g1 = physics_particle_group_end();
physics_particle_group_begin(flags, groupflags, mouse_x + 45, mouse_y, 0, 0, 0, 0, c_white, 1, 1, 2);
physics_particle_group_circle(50);
var g2 = physics_particle_group_end();
physics_particle_group_join(g1, g2);

The above code creates two circular particle groups and joins them together.

Back: Soft Body Particles
Next: physics_particle_group_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_group_polygon

Set the form of a soft body particle group that is to be created to be a polygon.

Syntax:

physics_particle_group_polygon()

Returns: N/A

Description

This function will set the shape of the particle group that is being created. You must first have begun the group definition using the function physics_particle_group_begin(), and then you would use this function to tell GameMaker: Studio that you are going to add in the approximate points that will be used to define the polygon shape - approximate because the exact shape will depend on the size of the base particles, as defined by the physics_particle_set_radius() function, as the physics simulation tries to "fit" as many of the particles as possible into the defined shape.

You would then define the points of the polygon calling the function physics_particle_group_add_point, setting the x/y position in the room for each one (minimum of 3, maximum of 8, and they can be defined as concave but the points inside the shape will be ignored). Finally you need to call physics_particle_group_end() to create the group of particles in the room.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
var groupflags = phy_particle_group_flag_solid;
physics_particle_group_begin(flags, groupflags, mouse_x, mouse_y, 0, 0, 0, 0, c_white, 1, 1, 2);
physics_particle_group_polygon();
physics_particle_group_add_point(200, 200);
physics_particle_group_add_point(300, 300);
physics_particle_group_add_point(100, 300);
mLastGroup = physics_particle_group_end();

The above code stores the flags for the particle type and the particle group properties in variables then uses these to create a polygon particle group of three sides at the mouse position.

Back: Soft Body Particles
Next: physics_particle_group_add_point

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_set_category_flags

Set the particle type flags for a category of particles.

Syntax:

physics_particle_set_category_flags(category, flags)

Argument | Description
category | The particle category to set.
flags | The flags to set on the particle.

Returns: N/A

Description

With this function you can change the particle flags for a category of particles. The category value is that which you defined in the function physics_particle_create or (if you created a group) physics_particle_group_begin, while the flags are the return value of a combination of the following constants:

Constant | Description
phy_particle_flag_water | The default properties for a soft body particle.
phy_particle_flag_zombie | A zombie particle is one that will be destroyed in a single step with all others flagged in this way.
phy_particle_flag_wall | This defines the particle as static, essentially creating it as an immovable object in the physics simulation, as they will remain in a fixed position no matter what collides with them. You should use this flag rather than set the density to 0.
phy_particle_flag_spring | Spring particles produce the effect of being attached to one another, as if by a spring. Particles created with this flag are "connected" in pairs, with each particle being connected to the one that was closest to it at the time of creation. Once paired, particles do not change "partners" , and the farther an external force pulls them from one another, the greater the power with which they will collide when that external force is removed. Note that no matter how far paired particles get from each another, the connection between them will not snap.
phy_particle_flag_elastic | Elastic particles deform and may also bounce when they collide with other rigid bodies in the physics simulation.
phy_particle_flag_viscous | A viscous particle is one that exhibits "clinginess" or "stickiness", like oil. Viscous particles will clump and stick together more.
phy_particle_flag_powder | Powder particles produce a scattering effect such as you might see with sand or dust.
phy_particle_flag_tensile | Tensile particles are used to produce the effect of surface tension, or the taut curvature on the surface of a body of liquid. They might be used, for example, to create the surface tension you would see on a drop of water. Once the tension is broken, the particles bounce as if they were elastic, but also continue to attract each other. As a result, particles tend to form clusters as they bounce.
phy_particle_flag_colourmixing | Colour-mixing particles take on some of the colour of other particles with which they collide. Note that if only one of the two colliding particles is a colour-mixing one, the other particle retains its pre-collision colour.

These flags use bit-masking to create a final output value that is then checked to set the different basic properties of the particle category (with the base property always being that of phy_particle_flag_water). For example, if you want to simulate a viscous liquid with surface tension you would use the bitwise or "|" to mask off the appropriate bits as shown in the example below. In this way you can set different properties (other than the global properties) for each category of particle created.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
physics_particle_set_category_flags(1, flags);

The above code will create a variable to store the flags value and then use it to set the flags of all particles created with the category value of 1.

Back: Soft Body Particles
Next: physics_particle_set_group_flags

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_set_damping

Set the damping value for all particles in a physics simulation.

Syntax:

physics_particle_set_damping(damping)

Argument | Description
damping | The linear damping to be applied to the particle fixture.

Returns: N/A

Description

With this function you can set the linear damping of particles in the simulation. Damping is used to reduce the physics simulation velocity of instances over time, much like air resistance in the real world. This function is global in scope, in that it will change the damping not just for new particles created after the change, but also for those already present in the simulation.

Example:

physics_particle_set_radius(15);
physics_particle_set_density(0.5);
physics_particle_set_damping(1);
physics_particle_set_gravity_scale(1);

The above code will set the base properties for all particles in the simulation.

Back: Soft Body Particles
Next: physics_particle_set_gravity_scale

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_set_density

Set the density for all particles in a physics simulation.

Syntax:

physics_particle_set_density(density)

Argument | Description
density | The density of the particle fixture.

Returns: N/A

Description

With this function you can set the density of the particles in a physics simulation. Setting the density of the particle will have a direct impact on how much inertia it has as well as how it reacts to collisions, so if you make a small particle with a high density it will have a very large mass, but if you define a large particle with a low density it will have a much smaller mass. This function is global in scope, in that it will change the density not just for new particles created after the change, but also for those already present in the simulation.

Example:

physics_particle_set_radius(15);
physics_particle_set_density(0.5);
physics_particle_set_damping(1);
physics_particle_set_gravity_scale(1);

The above code will set the base properties for all particles in the simulation.

Back: Soft Body Particles
Next: physics_particle_set_damping

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_set_flags

Set the particle type flags for a given particle.

Syntax:

physics_particle_set_flags(index, flags)

Argument | Description
index | The index of the particle.
flags | The flags to set on the particle.

Returns: Real

Description

With this function you can change the particle flags for an individual particle. The index value is the particle ID as returned by the function physics_particle_create, while the flags are the return value of a combination of the following constants:

Constant | Description
phy_particle_flag_water | The default properties for a soft body particle.
phy_particle_flag_zombie | A zombie particle is one that will be destroyed in a single step with all others flagged in this way.
phy_particle_flag_wall | This defines the particle as static, essentially creating it as an immovable object in the physics simulation, as they will remain in a fixed position no matter what collides with them. You should use this flag rather than set the density to 0.
phy_particle_flag_spring | Spring particles produce the effect of being attached to one another, as if by a spring. Particles created with this flag are "connected" in pairs, with each particle being connected to the one that was closest to it at the time of creation. Once paired, particles do not change "partners" , and the farther an external force pulls them from one another, the greater the power with which they will collide when that external force is removed. Note that no matter how far paired particles get from each another, the connection between them will not snap.
phy_particle_flag_elastic | Elastic particles deform and may also bounce when they collide with other rigid bodies in the physics simulation.
phy_particle_flag_viscous | A viscous particle is one that exhibits "clinginess" or "stickiness", like oil. Viscous particles will clump and stick together more.
phy_particle_flag_powder | Powder particles produce a scattering effect such as you might see with sand or dust.
phy_particle_flag_tensile | Tensile particles are used to produce the effect of surface tension, or the taut curvature on the surface of a body of liquid. They might be used, for example, to create the surface tension you would see on a drop of water. Once the tension is broken, the particles bounce as if they were elastic, but also continue to attract each other. As a result, particles tend to form clusters as they bounce.
phy_particle_flag_colourmixing | Colour-mixing particles take on some of the colour of other particles with which they collide. Note that if only one of the two colliding particles is a colour-mixing one, the other particle retains its pre-collision colour.

These flags use bit-masking to create a final output value that is then checked to set the different basic properties of the particle (with the base property always being that of phy_particle_flag_water). For example, if you want to simulate a viscous liquid with surface tension you would use the bitwise or "|" to mask off the appropriate bits as shown in the example below. In this way you can set different properties (other than the global properties) for each individual particle created, should you wish.

Example:

var flags = phy_particle_flag_water | phy_particle_flag_viscous | phy_particle_flag_tensile;
physics_particle_set_flags(p, flags);

The above code will create a variable to store the flags value and then use it to set the flags on a previously created particle with the index stored in the variable "p".

Back: Soft Body Particles
Next: physics_particle_set_category_flags


physics_particle_set_gravity_scale

Set the gravity scale factor for all particles in a physics simulation.

Syntax:

physics_particle_set_gravity_scale(scale)

Argument | Description
scale | The scaling factor to be applied to gravity for all particles.

Returns: N/A

Description

With this function you can set the gravity scale factor for particles in the physics simulation. The function is designed to help prevent instability in the physics simulation, especially when using very small particles which may behave unpredictably (i.e. break conservation of momentum) in scenarios such as explosions. Slowing these particles down by reducing gravity scale can stabilize their behaviour. This function is global in scope, in that it will change the gravity scale not just for new particles created after the change, but also for those already present in the simulation.

NOTE: Adjusting the number of update iterations per step (using the function physics_world_update_iterations can also affect the effect of gravity on particles. Larger iteration sizes confer greater resistance to gravity.

Example:

physics_particle_set_radius(15);
physics_particle_set_density(0.5);
physics_particle_set_damping(1);
physics_particle_set_gravity_scale(1);

The above code will set the base properties for all particles in the simulation.

Back: Soft Body Particles
Next: physics_particle_get_max_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_set_group_flags

Set the group type flags for a group of particles.

Syntax:

physics_particle_set_group_flags(group, flags)

Argument | Description
group | The particle group to set.
flags | The flags to set on the particle.

Returns: N/A

Description

With this function you can change the group flags for a group of particles. The group value is that which was returned when you created the group of particles using the function physics_particle_group_end, while the flags are the return value of a combination of the following constants:

Constant | Description
phy_particle_group_flag_solid | A solid particle group prevents other fixtures from lodging inside of it. Should anything penetrate it, the solid particle group pushes the offending fixture back out to its surface, making a a solid particle group possess an especially strong repulsive force.
phy_particle_group_flag_rigid | Rigid particle groups are ones whose shape does not change, even when they collide with other fixtures.

These group flags use bit-masking to create a final output value that is then checked to set the different basic properties of the group, apart from those set by the particle flags. You can use none, one or both of these constants by using the bitwise or "|" to mask the appropriate bits (as shown in the example below).

Example:

var flags = phy_particle_group_flag_solid | phy_particle_group_flag_rigid;
physics_particle_set_group_flags(group, flags);

The above code will create a variable to store the flags value and then use it to set the flags of all particles created in the group indexed by the variable "group".

Back: Soft Body Particles
Next: physics_particle_get_group_flags

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_set_max_count

Set the maximum number of particles permitted in a physics simulation.

Syntax:

physics_particle_set_max_count(count)

Argument | Description
count | The maximum number of particles to permit.

Returns: N/A

Description

This function will set the total permitted number of particles in a physics simulation. If you set this value to 0, then there is no cap the particles created, and setting it to any other value will stop any further particles being created when the total number of particles is equal to the value. Note that the minimum number of particles you can create in a simulation is 128, so setting this value any lower will have no effect (unless set to 0).

Example:

physics_particle_set_max_count(500);

The above code will set the particle cap of the physics simulation to 500.

Back: Soft Body Particles
Next: physics_particle_set_radius

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_particle_set_radius

Set the radius for all particles in a physics simulation.

Syntax:

physics_particle_set_radius(radius)

Argument | Description
radius | The radius (in pixels) of the particle fixture.

Returns: N/A

Description

With this function you can set the radius (in pixels) for the particles in a physics simulation. This function is global in scope, in that it will change the radius not just for new particles created after the change, but also for those already present in the simulation.

Example:

physics_particle_set_radius(15);
physics_particle_set_density(0.5);
physics_particle_set_damping(1);
physics_particle_set_gravity_scale(1);

The above code will set the base properties for all particles in the simulation.

Back: Soft Body Particles
Next: physics_particle_set_density

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Physics World

The GameMaker: Studio physics system has a number of functions for defining the properties of the physics world.

Before any physical reactions can occur in GameMaker: Studio you must first define the physics world in which they are going to happen. If you do not do this, GameMaker: Studio will default to the basic collision functions, and all other physics related code or settings will be ignored.

These functions are all involved in the creation of the physics world:

  1. physics_world_create
  2. physics_world_gravity
  3. physics_world_update_iterations
  4. physics_world_update_speed
  5. physics_world_draw_debug
  6. physics_draw_debug
  7. physics_pause_enable

Back: Physics
Next: Forces

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_draw_debug

This function draws a basic schematic of the physics properties for the instance.

Syntax:

physics_draw_debug()

Returns: N/A

Description

When creating a physics system in GameMaker: Studio, it is often important to have a visual representation of what is actually happening with an instance. This can be achieved by using physics_draw_debug, which draws a schematic outline of the physical properties associated with the instance running the code. Here is an image of how it looks:

It should be noted that for this to work it must be in the draw event of the instance, and it will be drawn using the currently defined draw colour.

Example:

draw_set_colour(c_red);
physics_draw_debug();

The code above will draw a representation of the physical properties associated with that instance using the colour red.

Back: The Physics World
Next: physics_pause_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_pause_enable

Pauses or un pauses the physics simulation.

Syntax:

physics_pause_enable(flag)

Argument | Description
flag | This can be set to true to pause the simulation, or false to start it again.

Returns: N/A

Description

Normally for a physics simulation to work, it must be continuous and cannot be stopped and started, or have instances suddenly moved from one place to another in the room. However, there are moments when you need to pause the simulation as (for example) the device os has paused, and so you would use this function. It pauses the simulation if the flag is set to true and no further physics calculations will be done until the flag is set to false again.

NOTE: This is of particular use should you wish to deactivate all the instances in a room as even when deactivated a physical body will still continue being calculated and simulated in the physics world.

Example:

if os_is_paused()
{
physics_pause_enable(true);
instance_deactivate_all(true);
instance_create(x, y, obj_PauseMenu);
}

The code above checks to see if the OS has been paused and if it has then it pauses the physics world, deactivates everything except itself, and then creates a pause menu instance.

Back: The Physics World
Next: physics_world_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_world_create

Creates the physics system in the room specified.

Syntax:

physics_world_create(pixeltometrescale);

Argument | Description
pixeltometrescale | defines the ratio of pixels on screen to metres in the real world. A ratio of 32:1 will be specified as 1/32 (or 0.03125).

Returns: N/A

Description

Even if you have defined the physics for your objects, without a world to place them in they will default to the traditional GameMaker: Studio collision system, so you need this function to create the physics system for the specified room either in an object event, or the creation code of the room itself (it can also be defined without using code in the room editor). This function will associate a physics "world" with the room and all instances created in the room will behave using the physics that has been defined for them and the world itself.

You'll notice that we have an argument that defines a ratio between pixel size and metres. This is because the physics functions work using real-world measurements and thus we must translate pixel coordinates and pixel sizes into these real-world measurements using a "pixel to metre scale". You'll want to adjust the pixeltometrescale setting until the average pixel size of the objects you are using translates roughly into simulated physics objects of an appropriate size, and above you can see that we have set it to 32 pixels being the equivalent of 1 metre. It should be noted that the physics system will work with larger and smaller ratios, but that the best performance is when the real world measurements of your objects are no less than 0.1 metres and no more than 50 metres.

Example:

physics_world_create(1/32)

The above code will create a physics world in the current room with a scale ratio of 32 pixels being the equivalent of 1 metre.

Back: The Physics World
Next: physics_world_gravity

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_world_draw_debug

This function draws some, or all, of the physics world system for debugging depending on the flag value.

Syntax:

physics_world_draw_debug(flag)

Argument | Description
flag | The flag value for showing different debug features

Returns: N/A

Description

This function will draw a representation of the physics world system of the room to help with debugging when you are having trouble getting the physics scene to work right. Sometimes the problem can be in the rendering part of your game, for example a sprite may be drawn at the wrong position or rotation, giving the appearance of incorrect physics, or it may be that your calculations are not correct. Either way, this function will help you to find and resolve the problem by drawing what is going on in your physics system. To do this, you need tell it which part of the system to draw, and this is done by passing a value created from the bits stored in various "flag" constants:

Argument | Description
phy_debug_render_aabb | This shows the absolute bounding box of each fixture in relation to the room axis
phy_debug_render_collision_pairs | This will show any fixtures that are currently in collision
phy_debug_render_coms | This marks the center of mass of each fixture in the room
phy_debug_render_core_shapes | Shows the basic shapes that make up the fixtures in the room
phy_debug_render_joints | This will draw each of the joints of all fixtures in the room
phy_debug_render_obb | This shows the relative bounding box for the fixtures in the room
phy_debug_render_shapes | This shows the actual shapes that make up fixtures within the room

So, to draw any two of those options we would need to do a bitwise "or" (in GameMaker: Studio this is represented by | ) on the two of them and store the resulting variable for the function to use. Here is an example of how you would set a variable to use with the function that will draw only the centers of mass and the joints of all fixtures in a room:

flag = phy_debug_render_coms | phy_debug_render_shapes

Which would give you something like this:

As you can see with the above code, only the shapes and centers of mass are drawn on the screen (as well as colours representing their states - for further information please check the Box 2D documentation on-line). In the same way you can display more, or even all, of the constants that you wish to debug... Just "or" them all together! One further thing should be noted - this function should be called only in the draw event of an instance that has a depth lower than those you wish to debug or else you will not be able to see the debug information.

Example:

flag = phy_debug_render_aabb | phy_debug_render_collision_pairs | phy_debug_render_obb;
physics_world_draw_debug(flag);

The code above will draw all of the absolute bounding boxes, the relative bounding boxes as well as the fixtures in collision within the current physics system.

Back: The Physics World
Next: physics_draw_debug

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_world_gravity

Sets the direction and strength of the gravity in the physics world.

Syntax:

physics_world_gravity(xg, yg)

Argument | Description
xg | The x component of the gravity vector
yg | The y component of the gravity vector

Returns: N/A

Description

As with all the physics functions, physics_world_gravity will only work on an instance if the room has a physics world defined for it in the room editor or using physics_world_create. It will then use the 0,0 defining point of the physics world to calculate the direction and strength of gravity based on the vector calculated from the xg and yg inputs. Here are some images to illustrate...

As you can see, the xg,yg coordinates are relative to the position of 0,0 as defined for the physics world, and the gravity itself is calculated as a vector of those two components. So, the default values of 0,10 will give you a gravity direction of down (270 degrees) with an acceleration of 10 metres per second squared. Note the metres per second squared! Like all the physics functions, gravity is calculated using metres as a base measurement so the pixel to metre scale that you set in physics_world_create function is important here. Gravity is also cumulative on the object (but the exact amount depends on what you have set for the function physics_fixture_set_linear_damping), meaning that in a room with a room_speed of 60, with no damping, the instance will accelerate by 10 metres per second, every second - which, if you have a 0.1 pixel to metre scale is the same as saying it will accelerate to a speed of 100 pixels per second in 60 steps.

Example:

physics_world_gravity(-5, 0)

The above code will set gravity to be (assuming the room physics 0,0 is set to top left) to the right - 0 degrees - with an acceleration of 5 metres per second squared.

Back: The Physics World
Next: physics_world_update_iterations

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_world_update_iterations

This function controls the number of iterations per step of the physics world.

Syntax:

physics_world_update_iterations(iterations)

Argument | Description
y1 | the iterations (per step) that the physics system will perform

Returns: N/A

Description

Everything in GameMaker: Studio is based around steps and, normally, each event will only happen once per step. However, to get the necessary precision with the physics functions they are made to do several calculations each step which are called "iterations" the number of which are controlled by this function. The default number for the physics system is 10, but this can be changed to higher or lower depending how many times you want the physics to calculate each step, but it is recommended that you set this no lower than 5 and no higher than 30. You should also be aware that this function is dependant on the physics_world_update_speed function.

Example:

physics_world_update_iterations(20)

The code above sets the physics world in the current room to perform calculations 20 times a step.

Back: The Physics World
Next: physics_world_update_speed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


physics_update_speed

physics_world_update_speed

Sets the speed at which the physics system will update.

Syntax:

physics_world_update_speed(speed)

Argument | Description
speed | the number of times per second that the physics system updates

Returns: N/A

Description

GameMaker: Studio updates things based on the room speed, so that if you set it to ,say, 30, GameMaker: Studio will run 30 steps in the course of a second. However, for the physics functions that may not be enough and you may want things to be updated at a slightly faster speed to increase stability or precision. To that end we use the function physics_world_update_speed which sets the update speed for the physics system independently of the room speed. This means that you could have a room speed of 30, but set the physics to 60, effectively doubling the speed at which the physics system updates and performs its calculations compared to the speed at which the step are updated.

Note: you cannot currently set this to any less than room speed, but future updates may change this.

Example:

physics_world_update_speed(room_speed * 2);

The code above sets the physics system update speed to be twice that of the room speed.

Back: The Physics World
Next: physics_world_draw_debug

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Push Notifications

This section deals with the functions for pushing notifications to devices.

On mobile devices, normally only one application can be active in the foreground at any time, but many games and applications operate in a time-based or interconnected environment where events of interest to users can occur when the application is not in the foreground. In these cases, Local and Remote push notifications can allow these games to notify their users when events occur.

When the operating system delivers a local or remote push notification and the target application is not running in the foreground, it presents the notification to the user in the form of a banner. If there is a notification alert and the user taps on it, then the game is launched and an Asynchronous Push Event is called where you can check the callback string that you specify and resolve the push based on its value. If the application is running in the foreground when the notification is delivered, the application will still receive an Asynchronous Push Event, but the user will get no message displayed unless you create it yourself.

There are a few differences to note between supported platforms:

  • On Android, you will need to download and install the Google Play Services Extension before you can use local notifications and also have enabled push notifications in the Android Social Global Game Settings. Also note that all notifications received when the app is not running/in background, will be stored, and the data delivered by the async event the next time the app runs.

  • On iOS, data for a particular notification will only be delivered when the notification is selected (or if the app is running in foreground when the notification is received).

Local Notifications

A local push notification is local to the device that the game is installed on, and requires no backend server. You simply set the date and time for the notification and it will be displayed to the user if the game is not currently running. This type of notification is useful to set "reminders" for the user to play your game again, or to offer a daily reward for playing, etc... and when the user taps the notification it will launch the game and pass in a data string which can then be parsed by the game to give a reward or whatever.

The following functions are available for local notifications:

  1. push_local_notification
  2. push_get_first_local_notification
  3. push_get_next_local_notification
  4. push_cancel_local_notification

NOTE: This function is limited to the iOS and Android target modules. on Android you will need to have installed the Google Play Services Extension and have enabled push notifications in the Android Social Global Game Settings.

Remote Notifications

Remote notification messages are sent by a server to a service provided by the device platform App Store, and this then forwards those messages onto all the devices on which your application is installed. This is supported by GameMaker: Studio on the iOS and Android target modules.

There are no functions in GameMaker: Studio to deal with remote notifications, as they must all be generated by your server and handled by the respective App Stores. However, once set up correctly, GameMaker: Studio games will receive these notifications, which can then be dealt with in the Asynchronous Push Event, as you would a local notification.

For all available platforms, once you have done the necessary set-up, when the game is run on a device it will register that device with the platforms push notification service. This will trigger an Asynchronous Push Notification Event, and the ds_map key "type" will have the value "register" as well as a new key, "reg_id", containing the registration id (or an error message in the "error" key, if "status" is 0). You must then send this registration id to your server, and every device that your game is installed on will have a different registration id. Your server must maintain a list of ids for registered devices, as when when you send a push notification message from your server, you use the registration ids to send the message to the registered devices.

Please note that there is no guarantee that remote push notifications will be delivered, and that the allowed data payload is fairly small. This varies between platforms, but iOS is particularly limited - the apple service only delivers the most recent notification, which must be selected by the recipient for the payload data to be delivered to your async event, and these notifications have a mximum payload size of 256bytes. Typically a remote push notification would just indicate that new data is available from your server for example.

NOTE: Android requires that you add the GCM Sender ID into the Global Game Settings for the platform. This is the Project Number that is assigned when you create your Google Play API Project.

For further details on how to go about setting up a server, as well as information specific to the available platforms, please see the following pages on the YoYo Games Knowledge Base:

  • Push Notifications - Android
  • Push Notifications - iOS
NOTE: Implementing the server-side is entirely up to the end user, and YoYo Games do not provide any support for that side of things, other than basic set-up information available from their Knowledge Base.

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


push_cancel_local_notification

Populate a ds_map with the information related to the next local notification in the queue.

Syntax:

push_cancel_local_notification(ID);

Argument | Description
ID | The ID of the notification to cancel.

Returns: Real

Description

This function cancel the given push notification. You can get the ID for the notification to cancel using the functions push_get_first_local_notification() and push_get_next_local_notification() and the function will return true on success or false otherwise (for example if the notification does not exist or has already been triggered).

NOTE: This function is limited to the iOS and Android target modules.

Example :

var map = ds_map_create();
var ntf = push_get_first_local_notification(map);
while(ntf >= 0)
{
var data = ds_map_find_value(map, "data");
if data == "Daily_Reward"
{
push_cancel_local_notification(ntf);
}
ntf = push_get_next_local_notification(map);
}
ds_map_destroy(map);

The above code creates a ds_map and then requests data for the first available notification in the queue. If a notification exists, the map is populated and the code then checks the "data" key for a specific string. If the string is found, the notification is cancelled and moves on to check the next notification until all in the queue have been checked.

Back: Push Notifications
Next: push_local_notification

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


push_get_first_local_notification

Populate a ds_map with the information related to the first local notification queued.

Syntax:

push_get_first_local_notification(map);

Argument | Description
map | The ds_map ID to use.

Returns: Real

Description

This function will populate a pre-made ds_map with a series of key/value pairs for the first local push notification in the queue to be shown. It returns -1 if there are no notifications queued, or a real value otherwise representing the ID for the notification. This ID can then be used to cancel the notification using the function push_cancel_local_notification().

The ds_map will hold the following key/value pairs:

  • "title" - The title of the notification (this will only be available on the Android platform as iOS does not store the title information)
  • "message" - The message body text
  • "data" - The data package string

NOTE: This function is limited to the iOS and Android target modules.

Example :

var map = ds_map_create();
var ntf = push_get_first_local_notification(map);
while(ntf >= 0)
{
var data = ds_map_find_value(map, "data");
if data == "Daily_Reward"
{
push_cancel_local_notification(ntf);
}
ntf = push_get_next_local_notification(map);
}
ds_map_destroy(map);

The above code creates a ds_map and then requests data for the first available notification in the queue. If a notification exists, the map is populated and the code then checks the "data" key for a specific string. If the string is found, the notification is cancelled and moves on to check the next notification until all in the queue have been checked.

Back: Push Notifications
Next: push_get_next_local_notification

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


push_get_next_local_notification

Populate a ds_map with the information related to the next local notification in the queue.

Syntax:

push_get_next_local_notification(map);

Argument | Description
map | The ds_map ID to use.

Returns: Real

Description

This function will populate a pre-made ds_map with a series of key/value pairs for the next local push notification in the queue to be shown. It returns -1 if there are no further notifications queued, or a real value otherwise representing the ID for the notification. This ID can then be used to cancel the notification using the function push_cancel_local_notification(). You should call the function push_get_first_local_notification to get the first notification in the queue and then use this function to continue through it.

The ds_map will hold the following key/value pairs:

  • "title" - The title of the notification (this will only be available on the Android platform as iOS does not store the title information)
  • "message" - The message body text
  • "data" - The data package string

NOTE: This function is limited to the iOS and Android target modules.

Example :

var map = ds_map_create();
var ntf = push_get_first_local_notification(map);
while(ntf >= 0)
{
var data = ds_map_find_value(map, "data");
if data == "Daily_Reward"
{
push_cancel_local_notification(ntf);
}
ntf = push_get_next_local_notification(map);
}
ds_map_destroy(map);

The above code creates a ds_map and then requests data for the first available notification in the queue. If a notification exists, the map is populated and the code then checks the "data" key for a specific string. If the string is found, the notification is cancelled and moves on to check the next notification until all in the queue have been checked.

Back: Push Notifications
Next: push_cancel_local_notification

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


push_local_notification

Sets a local notification to be shown at a given time on a given date.

Syntax:

push_local_notification(fire_time, title, message, data);

Argument | Description
fire_time | The date/time to fire the off the notification
title | The notification title (a string)
message | The notification message text (a string)
data | The data package to send to your game (a string)

Returns: N/A

Description

This function can be used to set a local notification to be shown on a given date at a given time. The "fire_time" is the date/time that the notification should be pushed to the user device (you can use the GameMaker: Studio Date and Time Functions to get this), and you can give the notification a title and a message text as well as a payload string which will be passed to your game when the users taps the notification.

NOTE: The "title" argument is ignored on iOS and the game name is shown instead.

Tapping the notification will start the game on the device and trigger an Asynchronous Push Notification event with a ds_map which can then be parsed to check the payload string and perform whatever action is required.

NOTE: This function is limited to the iOS and Android target modules.
IMPORTANT! For Android you will need to have installed the Google Play Services Extension and have enabled push notifications in the Android Social Global Game Settings.

Extended Example

In this example we will send a local push notification using the following code:

var fireTime = date_inc_day(date_current_datetime(), 1);
var data = "daily_reward";
push_local_notification(fireTime, "Ahoy!", "Catch The Haggis Has A Present", data);

This will set a timer to "push" a notification to the device when one day has passed. When the day is up, if your game is either in the background or not running, a notification will be shown to the user with the given title and message (on iOS, the game name is shown and the title is ignored), and then an asynchronous Push Notification Event will be called. Note that if the game is in the foreground when the time for the notification comes, it will not be shown, but the asynchronous event will still trigger. In the event itself you would handle the callback something like this: Async Event in the following way:

var type = ds_map_find_value(async_load, "type");
var status = ds_map_find_value(async_load, "status");
if status == 0
{
//error of some kind
var error = ds_map_find_value(async_load, "error");
show_debug_message("error=" + string(error));
}
else
{
if type == "register"
{
global.reg_id = ds_map_find_value(async_load, "reg_id");
}
else
{
var data = ds_map_find_value(async_load, "data");
if data == "daily_reward"
{
global.Gold += 1000;
}
}
}

Back: Push Notifications
Next: push_get_first_local_notification

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Rooms

This section deals with the functions related to rooms.

Rooms in GameMaker: Studio are where everything happens in your game and you must have at least one room in any game for it to run, but in general you will need many more. This section has all the GML functions related to rooms and getting information about them or even setting certain properties within them. It should be noted that those functions related to changing room properties should never be run from within the room that you wish to change, but rather be run from an instance in another room first.

Room Information

The following functions and global variables are used for getting basic information about a room:

  1. room_exists
  2. room_first
  3. room_last
  4. room_next
  5. room_previous
  6. room
  7. room_speed
  8. room_height
  9. room_width
  10. room_persistent
  11. room_caption
  12. room_get_name

Moving Between Rooms

The following functions are used for moving between rooms:

  1. room_goto
  2. room_goto_next
  3. room_goto_previous
  4. room_restart

Creating and Changing Rooms

The following functions are used for creating rooms and changing room properties:

NOTE: These functions cannot be used with the current room otherwise errors and unpredictable behaviours can occur.

  1. room_add
  2. room_duplicate
  3. room_assign
  4. room_instance_add
  5. room_instance_clear
  6. room_tile_add
  7. room_tile_add_ext
  8. room_tile_clear
  9. room_set_background
  10. room_set_background_colour
  11. room_set_height
  12. room_set_width
  13. room_set_persistent
  14. room_set_view_enabled

Back: Game Assets

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room

The index of the current room.

Syntax:

room;

Returns: Real

Description

This variable holds the room index for the current room that your game is running. This is not a read only variable, however changing this will not change the index value for the current room, but rather change the room to match the index that you have set the variable to. Care should be taken when doing this as if the index you change the variable to is not valid the game will throw an error and close. In general it is much better practice to use room_goto to change rooms.

Example:

if room_next(room) != -1
{
room_goto(room_next);
}

The above code will check to see if the next room exists and if so, it will go to it.

Back: Rooms
Next: room_speed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_add

Creates a new room.

Syntax:

room_add();

Returns: Real

Description

This function will create a new, empty, room and add it to your game, returning its index to be stored in a variable for all further codes that deal with this room.

NOTE: New rooms are not part of usual room ordering, so they do not have a "previous" or "next" room (meaning that the functions room_next and room_previous will not work). To jump from the added room to another, you must use the index of the room itself.

Example:

global.myroom = room_add();
room_set_width(global.myroom, 640);
room_set_height(global.myroom, 480);
room_set_persistent(global.myroom, false);

This will create a new room and store its index in the variable "global.myroom". It will then set its width to 640 pixels, its height to 480 pixels, and its persistence to false.

Back: Rooms
Next: room_duplicate

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_assign

Copy one room to another.

Syntax:

room_assign(ind, room);

Argument | Description
ind | The index of the original room to be copied from.
room | The index of the room to be copied to.

Returns: N/A

Description

This function will copy one room to another, removing all instances, tiles etc... from the room that is being copied to and replacing them completely with the new room contents.

Example:

global.rm = room_add();
room_assign(rm_Base, global.rm);

The above code will add a new room to the game and then copy the contents of the room indexed as "rm_Base" into it.

Back: Rooms
Next: room_instance_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_caption

Holds the room caption as a string.

Syntax:

room_caption;

Returns: String

Description

This variable permits you to create a "caption" string for your room. If no caption is defined, or you wish to set no caption, use an empty string "".

NOTE: this variable is deprecated and may be removed in future versions of the product.

Example:

if room_caption=""
{
room_caption = room_get_name(room);
}

The above code will check to see if the room has a caption and if it does not it sets the caption to be the same as the name of the room.

Back: Rooms
Next: room_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_duplicate

This will duplicate a room.

Syntax:

room_duplicate(ind);

Argument | Description
ind | The index of the original room to be duplicated.

Returns: Real

Description

This will duplicate a given room and return the duplicates index to be used in all further calls to reference the new room.

NOTE: New rooms are not part of usual room ordering, so they do not have a "previous" or "next" room (meaning that the functions room_next and room_previous will not work). To jump from the added room to another, you must use the index of the room itself.

Example:

global.myroom = room_duplicate(rm_level);

This will duplicate the room indexed by "rm_level" and assign the room index of this new room to the variable "global.myroom".

Back: Rooms
Next: room_assign

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_exists

Returns whether a room with the given index exists or not.

Syntax:

room_exists(index);

Argument | Description
index | The index of the room to check.

Returns: Boolean

Description

With this function you can check and see whether the room you specify exists or not. This function takes the room index (a real number) and not the room name (a string). This function is most useful when you are creating rooms dynamically using the function room_add, but you can also use the read only variables room_first and room_last or the functions room_next and room_previous to get a specific room index, or provide a variable that has stored the index of any other room in your game.

Example:

if room_exists(global.rm[0])
{
room_goto(global.rm[0]);
}

The above code checks to see if the room indexed in the array "global.rm[]" exists and if it does it then goes to that room.

Back: Rooms
Next: room_first

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_first

The index of the first room in the game.

Syntax:

room_first;

Returns: Real

Description

This read only variable returns the index of the very first room in the game (this is defined by the order in which the rooms appear in the resource tree and not by the order in which they were created.

Example:

if lives < 1
{
room_goto(room_first);
}

The above code will check the "lives" variable and if it is less than 1 goto the first room in the game.

Back: Rooms
Next: room_last

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_get_name

Returns the name of the room with the given index.

Syntax:

room_get_name(index);

Argument | Description
index | The index of the room to check the name of.

Returns: String

Description

This function can be used to return the name of the specified room as a string. Please note that this is only a string and cannot be used to reference the room directly - for that you would need the room index. You can, however, use this string to get the room index using the returned string along with the function asset_get_index().

Example:

var roomname = room_get_name(room);
draw_text(32, 32, roomname);

The above code will get the name of the current room and draw it on the screen.

Back: Rooms
Next: room_goto

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_goto

This is used to go to a given room.

Syntax:

room_goto(numb);

Argument | Description
numb | The index of the room to go to.

Returns: N/A

Description

This function will end the current room and go to the room specified by the input index. The room must exist or else an error will be given, and if you use the same room as the current room it will have the same effect as room_restart. Note that the room will not change until the end of the event where the function was called, so any code after this has been called will still run.

Example:

switch (global.rm)
{
case 0: room_goto(rm_level1); break;
case 1: room_goto(rm_level2); break;
case 2: room_goto(rm_level3); break;
}

The above code will check a global variable and change room based on the value that it holds.

Back: Rooms
Next: room_goto_next

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_goto_next

This is used to jump to the next room.

Syntax:

room_goto_next();

Returns: N/A

Description

With this function you can make your game go to the next one as listed in the resource tree at the time the game was compiled. if this room does not exist, and error will be thrown and the game will be forced to close. Note that the room will not change until the end of the event where the function was called, so any code after this has been called will still run.

Example:

if room_exists(room_next(room)) room_goto_next();

The above code will check to see if there is another room after the current one and if so it will go to that room.

Back: Rooms
Next: room_goto_previous

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_goto_previous

This is used to jump to the previous room.

Syntax:

room_goto_previous();

Returns: N/A

Description

With this function you can make your game go to the previous one as listed in the resource tree at the time the game was compiled. if this room does not exist, and error will be thrown and the game will be forced to close. Note that the room will not change until the end of the event where the function was called, so any code after this has been called will still run.

Example:

if room_exists(room_previous(room)) room_goto_previous();

The above code will check to see if there is another room before the current one and if so it will go to that room.

Back: Rooms
Next: room_restart

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_height

The height of the current room in pixels.

Syntax:

room_height;

Returns: Real

Description

This variable holds the height of the current room in pixels. You can change this variable to change the height of the room at any time.

Example:

if bbox_bottom > room_height
{
y += room_height - bbox_bottom;
}

The above code checks to see if the current instance's sprite bounding box is greater than the height of the room, and if it is it moves the instance up.

Back: Rooms
Next: room_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_instance_add

Adds an object instance at a given position to a given room.

Syntax:

room_instance_add(ind, x, y, obj);

Argument | Description
ind | The index of the room to add an object instance to.
x | The x position of the new instance.
y | The y position of the new instance.
obj | The object to add an instance of.

Returns: Real

Description

With this function you can add an instance into any room other than the current one and at any position within that room. The function returns the unique id of the instance which can then be used in further function calls to set properties etc... of that instance, but only once the game has entered the specified room. If you wish to create an instance in the current room you should be using the function instance_create.

Example:

global.rm = room_add();
room_assign(rm_Base, global.rm);
room_instance_add(global.rm, 100, 100, obj_Player);

The above code will add a new room to the game and then copy the contents of the room indexed as "rm_Base" into it. It will then add an instance of the object "obj_player" at the position 100,100 of this new room.

Back: Rooms
Next: room_instance_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_instance_clear

Clears all instances in a given room.

Syntax:

room_instance_clear(ind);

Argument | Description
ind | The index of the room to clear all instances in.

Returns: N/A

Description

This function will clear a room of all instances (no destroy events shall be called for the instances that are being removed).

Example:

global.rm = room_add();
room_assign(rm_Base, global.rm);
room_instance_clear(global.rm);

The above code will add a new room to the game and then copy the contents of the room indexed as "rm_Base" into it. It will then clear all instances from this new room.

Back: Rooms
Next: room_tile_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_last

The index of the last room in the game.

Syntax:

room_last;

Returns: Real

Description

This read only variable returns the index of the very last room in the game (this is defined by the order in which the rooms appear in the resource tree and not by the order in which they were created.

Example:

if keyboard_check_pressed(ord("Q"))
{
room_goto(room_last);
}

The above code checks to see if a key has been pressed and if so it goes to the last room in the game.

Back: Rooms
Next: room_next

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_next

This will return the index of the room after the given room id.

Syntax:

room_next(numb);

Argument | Description
numb | The index of the base room to check from.

Returns: Real

Description

With this function you can retrieve the index of the room after the room input into the function. For example you can use the read only variable room to get the index of the current room and then use this function to find the room that follows it in the resource tree. If there is no room after the one you input then -1 is returned.

Example:

if room_next(room) != -1
{
room_goto_next());
}

The above code will check to see if the next room exists and if so, it will go to it.

Back: Rooms
Next: room_previous

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_persistent

Holds the state of the persistent flag of the room.

Syntax:

room_persistent;

Returns: Boolean

Description

This variable can be used to get and to set the persistent flag for the current room. If set to true the room is considered persistent, in which case each time you leave the room and come back again the state of the instances within that room will have been maintains. However if it is flagged as false, each time you return to the room it will be reset to its initial state. You should note that a persistent room uses considerably more memory than a normal room and it is not recommended to have too many of them in your game.

Example:

if lives < 1
{
room_persistent = false;
room_goto(rm_start);
}

The above code checks the variable "lives" and if it is less than 1, it will set the room persistence to false and then change rooms.

Back: Rooms
Next: room_caption

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_previous

This will return the index of the room before the given room id.

Syntax:

room_previous(numb);

Argument | Description
numb | The index of the base room to check from.

Returns: Real

Description

With this function you can retrieve the index of the room before the room input into the function. For example you can use the read only variable room to get the index of the current room and then use this function to find the room that comes before it in the resource tree. If there is no room before the one you input then -1 is returned.

Example:

if room_previous(room) != -1
{
room_goto_previous();
}

The above code will check to see if the previous room exists and if so, it will go to it.

Back: Rooms
Next: room

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_restart

This is used to restart the current room.

Syntax:

room_restart();

Returns: N/A

Description

With this function you can restart the current room. Note that the room will not be restarted until the end of the event where the function was called, so any code after this has been called will still run.

Example:

if lives < 1 room_restart();

The above code checks to see if the variable "lives" is less than 1 and if it is it will restart the room.

Back: Rooms
Next: room_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_set_background

Sets a background and its related attributes of a given room.

Syntax:

room_set_background(ind, bind, vis, fore, back, x, y, htiled, vtiled, hspeed, vspeed, alpha);

Argument | Description
ind | The index of the room to set the background of.
bind | The index of the background 'slot' to set (between 0 and 7).
vis | Whether the new background is visible (true) or not (false).
fore | Whether the background is actually a foreground (true) or a background (false).
back | The index of the new background.
x | The x position of the background (if htiled is true, the x of one of the backgrounds).
y | The y position of the background (if vtiled is true, the y of one of the backgrounds).
htiled | Whether the background is tiled horizontally (true) or not (false).
vtiled | Whether the background is tiled vertically (true) or not (false).
hspeed | The horizontal speed of the background in pixels per step.
vspeed | The vertical speed of the background in pixels per step.
alpha | The alpha (transparency) of the background. 1=opaque, 0=invisible, 0.5=translucent etc

Returns: N/A

Description

With this function you can set a background for a room (except the current one), with all the same property options that you can find in the room editor like horizontal speed and horizontal or vertical tiling.

Example:

global.rm = room_add();
room_set_background(global.rm, 0, 1, 0, bck_Space, 32, 32, 1, 1, 4, 0, 0.8);

The above code will add a new room to the game and then set the background of that room to the background indexed as "bck_Space" and set the properties for that background.

Back: Rooms
Next: room_set_background_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_set_background_colour

Sets the background colour of a given room.

Syntax:

room_set_background_colour(ind, col, show);

Argument | Description
ind | The index of the room to set the background colour of.
col | The new background colour.
show | Whether to show background colour (true) or not (false).

Returns: N/A

Description

With this function you can set the background colour for a room (except the current one) and choose whether it should be drawn (true) or not (false).

Example:

global.rm = room_add();
room_set_background_colour(global.rm, c_maroon, 1);

The above code will add a new room to the game and then set the background colour for that room to maroon and make the colour visible too.

Back: Rooms
Next: room_set_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_set_height

Sets the height, in pixels, of a given room.

Syntax:

room_set_height( ind, h );

Argument | Description
ind | The index of the room to set the height of.
h | The new height of the room in pixels.

Returns: N/A

Description

With this function you can change (or set) the height of any room in your game except the current one.

Example:

global.myroom = room_add();
room_set_width(global.myroom, 640);
room_set_height(global.myroom, 480);
room_set_persistent(global.myroom, false);

This will create a new room and store its index in the variable "global.myroom". It will then set its width to 640 pixels, its height to 480 pixels, its caption to 'Game Room' and its persistence to 'false'.

Back: Rooms
Next: room_set_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_set_persistent

Sets whether a given room is persistent or not.

Syntax:

room_set_persistent( ind, val );

Argument | Description
ind | The index of the room to set the persistence of.
val | Whether the room shall be persistent (true) or not (false).

Returns: N/A

Description

With this function you can change (or set) the persistence of any room in your game except the current one. A room with persistence flagged as true it will maintain the state of all instances within that room if the player leaves and then returns, whereas if persistence is flagged as false it will be reset to the initial state every time. You should note that a persistent room uses considerably more memory than a normal room and it is not recommended to have too many of them in your game.

NOTE: This function will NOT work to switch off persistence if the room has already been visited! A persistent room, once visited, is held in memory and to switch off persistence you should go to that room and set the room_persistent variable to false and then exit the room again.

Example:

global.myroom = room_add();
room_set_width(global.myroom, 640);
room_set_height(global.myroom, 480);
room_set_persistent(global.myroom, true);

This will create a new room and store its index in the variable "global.myroom". It will then set its width to 640 pixels, its height to 480 pixels, its caption to 'Game Room' and its persistence to 'true'.

Back: Rooms
Next: room_set_view_enabled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_set_view_enabled

Sets whether views are enabled or not in a given room.

Syntax:

room_set_view_enabled( ind, val );

Argument | Description
ind | The index of the room to set.
val | Whether to enable (true) or disable (false) views in the given room.

Returns: N/A

Description

With this function you can enable (true) or disable (false) the view of any room within your game except the current one.

Example:

global.myroom = room_add();
room_set_view_enabled(global.myroom, true);

This will enable views in the room indexed in "global.myroom".

Back: Rooms
Next: room_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_set_width

Sets the width, in pixels, of a given room.

Syntax:

room_set_width( ind, w );

Argument | Description
ind | The index of the room to set the width of.
w | The new width of the room in pixels.

Returns: N/A

Description

With this function you can change (or set) the width of any room in your game except the current one.

Example:

global.myroom = room_add();
room_set_width(global.myroom, 640);
room_set_height(global.myroom, 480);
room_set_persistent(global.myroom, false);

This will create a new room and store its index in the variable "global.myroom". It will then set its width to 640 pixels, its height to 480 pixels, its caption to 'Game Room' and its persistence to 'false'.

Back: Rooms
Next: room_set_persistent

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_speed

The speed of the current room in steps.

Syntax:

room_speed;

Returns: Real

Description

This variable holds the running speed of the current room. Note that this is NOT the FPS (frames per second) but rather the number of game steps that GameMaker: Studio will try to maintain each second.

Example:

alarm[0] = room_speed * 10;

The above code uses room_speed to set an alarm to run for 10 seconds. Using the variable in this way will ensure that the alarm runs for 10 seconds, no matter what speed is set for the room.

Back: Rooms
Next: room_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_tile_add

Add a new tile to a room and return its index.

Syntax:

room_tile_add(ind, back, left, top, width, height, x, y, depth);

Argument | Description
ind | The index of the room to add the tile to.
back | The background from which the tile is taken.
left | The x coordinate of the left side of the tile relative to the background.
top | The y coordinate of the top side of the tile relative to the background.
width | The width of the tile.
height | The height of the tile.
x | The x coordinate of where to place the tile.
y | The y coordinate of where to place the tile.
depth | The depth of the tile in the room.

Returns: Real

Description

With this function you can add a tile to any room from any background. You specify the position within the background to get the tile from and the position within the room as well as the depth that the tile should have. The function returns a unique id number for that tile that you can use for further tile functions.

Example:

global.rm = room_add();
room_assign(rm_Base, global.rm);
room_tile_add(global.rm, tl_grass, 0, 0, 256, 32, 0, 400, 10000);

The above code will add a new room to the game and then copy the contents of the room indexed as "rm_Base" into it. It will then add a tile into the room taken from the background indexed as "tl_grass".

Back: Rooms
Next: room_tile_add_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_tile_add_ext

Adds a new tile to a given room and sets its properties.

Syntax:

room_tile_add_ext(ind, back, left, top, width, height, x, y, depth, xscale, yscale, alpha);

Argument | Description
ind | The index of the room to add the tile to.
back | The background from which the tile is taken.
left | The x coordinate of the left side of the tile relative to the background.
top | The y coordinate of the top side of the tile relative to the background.
width | The width of the tile.
height | The height of the tile.
x | The x coordinate of where to place the tile.
y | The y coordinate of where to place the tile.
depth | The depth of the tile in the room.
xscale | The horizontal scale of the tile. 1=normal size, 0.5=half, 2=double, etc.
yscale | The vertical scale of the tile. 1=normal size, 0.5=half, 2=double, etc.
alpha | The alpha (transparency) of the tile. 0=invisible, 1=opaque, 0.5=translucent etc.

Returns: Real

Description

With this function you can add a tile to any room from any background. You specify the position within the background to get the tile from and the position within the room as well as the depth that the tile should have and the alpha and scale of the new tile. The function returns a unique id number for that tile that you can use for further tile functions.

Example:

global.rm = room_add();
room_assign(rm_Base, global.rm);
room_tile_add_ext(global.rm, tl_grass, 0, 0, 256, 32, 0, 400, 10000, 2, 2, 0.2 );

The above code will add a new room to the game and then copy the contents of the room indexed as "rm_Base" into it. It will then add a tile into the room taken from the background indexed as "tl_grass", setting its alpha to a value of 0.2 and scaling it by 2 on the x and y axis.

Back: Rooms
Next: room_tile_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_tile_clear

Clears all tiles from a given room.

Syntax:

room_tile_clear(ind);

Argument | Description
ind | The index of the room to clear all tiles from.

Returns: N/A

Description

With this function you can remove all the tiles from a room.

Example:

global.rm = room_add();
room_assign(rm_Base, global.rm);
room_tile_clear(global.rm);

The above code will add a new room to the game and then copy the contents of the room indexed as "rm_Base" into it. It will then clear all tiles from this new room.

Back: Rooms
Next: room_set_background

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


room_width

The width of the current room in pixels.

Syntax:

room_width;

Returns: Real

Description

This variable holds the width of the current room in pixels. You can change this variable to change the width of the room at any time.

Example:

if bbox_right > room_width
{
x += room_width - bbox_right;
}

The above code checks to see if the current instance's sprite bounding box is greater than the width of the room, and if it is it moves the instance up.

Back: Rooms
Next: room_persistent

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Shaders

This section explains the functions and constants used to create shaders in GameMaker: Studio.

Shaders are an incredibly powerful tool for manipulating what and how things are rendered to the screen by the graphics card. Since these tiny programs are actually run on the card itself, this means that they are extremely fast to process, freeing up valuable CPU cycles for more game logic.

To create a shader you will need to have written both a Vertex Shader and a Fragment Shader (also know as a Pixel Shader) using the Shader Editor, and even if (for example) you only wish to change the vertex positions for an instance being drawn, or if you only want to change the colour values for the pixels, you will still need both programs for a complete shader to work.

NOTE: Shaders do not permit you to change the value of any variables that you pass into them, and so these will be called shader constants in all the documentation that refers to them.

For a complete overview of the available GLSL ES functions and variables that you can use to program the shaders themselves, please refer to the OpenGL ES Shading Language (GLSL ES) Reference Pages.

Using Shaders

Once you have your shader created, using it is very simple and only requires a couple of lines of code to get the most basic of use from it:

shader_set(myShader);
draw_self();
shader_reset();

As you can see, they are used in a similar manner to blend modes and surfaces, where you first select (set) the shader, draw what you want using it, then reset the draw target again afterwards. If you wish to render the full screen through a shader, and not just a single sprite or background, you will need to set up a surface to catch the current view, and then pass that through to the shader (see Surfaces for more information).

If the shader you are using has input values, these are set using the uniform functions. You would first get the uniform handle (which is essentially an ID value for the uniform to be set) using the function shader_get_uniform() in the Create Event of the instance using the shader, and then store these handles in variables, something like this:

colour_to_find = shader_get_uniform(sShaderDemo5, "f_Colour1");
colour_to_set = shader_get_uniform(sShaderDemo5, "f_Colour2");

Once you have the uniform handles, they can then be set in the shader code for the Draw Event like this:

shader_set(sShaderDemo5);
shader_set_uniform_f(colour_to_find, 1,1,1 );
shader_set_uniform_f(colour_to_set, 1,0,0 );
draw_sprite(sprite_index,image_index,x+24, y);
shader_reset();

One final thing to note is that although shaders are accepted across all platforms, they are still device specific and if the hardware or software of the device cannot use shaders then you will get an error. Therefore you are recommended to check that the shader has been compiled before setting uniforms or using the shader itself, like this:

if (shader_is_compiled(myShader))
{
shader_set(myShader);
draw_self();
shader_reset();
}
else show_debug_message("Shader failed");

As an extra check you can also call the function shaders_are_supported to see if the hardware even supports shaders. In general you'd do these checks on game start and store the results as a global variable to then check later.

It is important to note that GameMaker: Studio 1.4 also supports some conditional compile Macros which can be used within GLSL ES shaders so they can perform alternative code on specific supported platforms. The macros and the platforms they will be generated on are shown in the table below:

Shader Macro | Value | Target Platform
_YY_GLSLES_ | 1 | All target platforms
_YY_GLSL_ | 1 | Mac and Ubuntu (Linux)
_YY_HLSL9_ | 1 | Windows 32
_YY_HLSL11_ | 1 | UWP, XboxOne
_YY_PSSL_ | 1 | PlayStation 4
_YY_CG_PS3_ | 1 | PlayStation 3
_YY_CG_PSVITA_ | 1 | PS Vita

When you compile your GameMaker Studio 2 project on any one of the listed platforms using a GLSL ES format shader, one of the above macros will be generated which can then be used checked in the shader code like this:

#ifdef _YY_HLSL11_
// HLSL shader code here
#else
// GLSL shader code here
#endif

NOTE: Shaders, like anything related to drawing, can only be used in the draw event. It is also worth noting that if you are trying to use a colour value in a shader and the object has no texture, the results will turn out black.

The following functions are available for drawing shaders:

  1. shader_set
  2. shader_get_uniform
  3. shader_get_sampler_index
  4. shader_set_uniform_f
  5. shader_set_uniform_f_array
  6. shader_set_uniform_i
  7. shader_set_uniform_i_array
  8. shader_set_uniform_matrix
  9. shader_set_uniform_matrix_array
  10. shader_reset
  11. shader_is_compiled
  12. shaders_are_supported
  13. shader_current

We also have a special function which defines a global state for all shaders:

  1. shader_enable_corner_id

Textures

When working with texture samplers in shaders you will need information about the texture being used, in which case you can use the following functions:

  1. background_get_texture
  2. background_get_uvs
  3. sprite_get_texture
  4. sprite_get_uvs
  5. font_get_texture
  6. font_get_uvs
  7. texture_get_width
  8. texture_get_height
  9. texture_get_texel_width
  10. texture_get_texel_height
  11. texture_set_stage
  12. texture_set_interpolation_ext
  13. texture_set_repeat_ext

GameMaker: Studio Shader Constants

While this manual will not cover any of the Open GL shader functions and variables, it does contain a list of the ones that are unique to GameMaker: Studio. These constants are not part of the Open GL specification for shaders and are supplied to simplify the integration of shaders within your projects.

  1. Shader Constants

Vertex Formats and Custom Primitives

Finally, GameMaker: Studio permits you to define your own Vertex Formats from which you can create your own custom primitives. This can greatly speed up shader operations or can be used to extend their capabilities and create surprising effects. You can find information on this in the following sections:

  1. Vertex Formats
  2. Primitive Building

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_current

Returns the ID of the shader currently being used for rendering.

Syntax:

shader_current();

Returns: Real (ID value of the shader, or -1 if no shader)

Description

This function will return the index ID value of the shader currently being used for rendering, or it will return -1 if no shader is being used.

Example:

if shader_current() == -1
{
shader_set(sh_warp)
}

The above code will check to see what the current shader is and if it returns -1 (no shader being used) then a shader is set.

Back: Shaders
Next: shader_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_enable_corner_id

Permit all shaders to use colour bytes to determine the corner id of the vertex.

Syntax:

shader_enable_corner_id(enable);

Argument | Description
enable | Enable (true) or disable (false) this function.

Returns: N/A

Description

With this function you can set a global state for all shaders being used where, when enabled, the shader "steals" 2 bits from the input colour values. The first is from the lower bit of the red colour value, and the second is from the lower bit of the blue colour value. These values can get then be recovered in the shader to work out which vertex your dealing with (ie: which corner).

Example:

shader_enable_corner_id(true);

The above code will enable the use of colour bits for the corner id for all shaders.

Back: Shaders

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_get_sampler_index

Get the handle of a given shader sampler.

Syntax:

shader_get_sampler_index(shader, uniform);

Argument | Description
shader | The index of the shader to use.
shader | The shader sampler to get the handle of (a string).

Returns: Real

Description

Since you cannot change the value of a shader sampler within the shader itself, you have to set it before calling the shader using one of the available uniform set functions. However, to be able to do that you must first call this function to get the "handle" of the shader sampler that you will want to set.

NOTE: Although a shader is made up of two discreet programs (vertex and fragment) this function will not differentiate between the two and will return the handle of the shader sample from either of them.

Example:

shader_sample = shader_get_sampler_index(shader_glass, "s_NoiseSampler");

The above code will get the handle of the shader sample "s_NoiseSampler".

Back: Shaders
Next: shader_set_uniform_f

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_get_uniform

Get the handle of a given shader constant.

Syntax:

shader_get_uniform(shader, uniform);

Argument | Description
shader | The index of the shader to use.
shader | The shader constant to get the handle of (a string).

Returns: Real

Description

Since you cannot change the value of a shader constant within the shader itself, you have to set it before calling the shader using one of the available uniform set functions. However, to be able to do that you must first call this function to get the "handle" of the shader constant that you will want to change.

NOTE: Although a shader is made up of two discreet programs (vertex and fragment) this function will not differentiate between the two and will return the handle of the shader constant from either of them.

Example:

shader_params = shader_get_uniform(shader_glass, "u_vRefractColour");

The above code will get the handle of the shader constant "u_vRefractColour".

Back: Shaders
Next: shader_get_sampler_index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_is_compiled

Checks a shader to make sure that it has compiled okay.

Syntax:

shader_is_compiled(shader);

Argument | Description
shader | The shader to check.

Returns: N/A

Description

This function will check a shader at run-time to make sure that it has been successfully compiled. If it has then the function returns true otherwise it returns false. This function should be used at the start of the game to make sure that the platform running your game has successfully compiled any shaders used (particularly on Windows where some computers may be using DX9 with Shader Level 2.0 and not a later version using shader level 3.0).

If your shader has NOT been compiled and you call shader_set the game will crash, so it is worth while having some sort of check whenever you are using anything other than simple GLSL ES shaders.

Example:

global.GFX = false;
if shader_is_compiled(sh_glass) && shader_is_compiled(sh_warp)
{
global.GFX = true;
}

The above code will set a global variable to false, and then if both the shaders being checked have compiled correctly, it will be set to true.

Back: Shaders
Next: shaders_are_supported

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_reset

Reset the draw target from a shader to standard drawing.

Syntax:

shader_reset();

Returns: N/A

Description

This function resets the draw target and should be called when you no longer wish to use the current shader (set using shader_set).

Example:

shader_set(shader_Glass);
draw_self();
shader_reset();

The above code will set a shader top be used for drawing, then draw the current sprite used for the instance using it.

Back: Shaders
Next: shader_is_compiled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_set

Set a shader to be used for all further drawing.

Syntax:

shader_set(shader);

Argument | Description
shader | The index of the shader to use.

Returns: N/A

Description

With this function you can set the drawing target to the given shader and all further drawing will be done using that. You can end shader use with function shader_reset.

NOTE: You can only call a shader in the Draw Event of an instance.

Example:

shader_set(shader_Glass);
draw_self();
shader_reset();

The above code will set a shader top be used for drawing, then draw the current sprite used for the instance using it.

Back: Shaders
Next: shader_get_uniform

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_set_uniform_f

Set a shader constant to a new floating point value (or values).

Syntax:

shader_set_uniform_f(handle, value1 [, value2, value3, value4]);

Argument | Description
handle | The handle of the shader constant to set.
value1 ... value4 | The floating point value (or values) to set the shader constant to.

Returns: N/A

Description

With this function you can set the value (or values) of a shader constant. You must previously have gotten the "handle" of the constant using the function shader_get_uniform, and you will have to know what type of constant it is to pass the correct number of floating point values through to it, ie: if you have a vec2 you will need to pass two values to the function.

An exception to the above rule is when dealing with 32bit colour values. You can pass into the shader up to eight 32bit colour values and they will automatically be converted for you into vec4 values of 0 - 1. However for this you must use the shader constant name in_Colour, for a single colour, or in_Colour0, in_Colour1, etc... up to in_Colour7 for multiple input values. The following to examples show how this would look in the shader itself:

//Single colour
attribute vec2 in_Position;
attribute vec4 in_Colour;
attribute vec2 in_TextureCoord;

//Multiple colours
attribute vec2 in_Position;
attribute vec4 in_Colour0;
attribute vec4 in_Colour1;
attribute vec2 in_TextureCoord;

Note too that if you want to do compressed normals etc... using a 4 byte colour format, then you will also have to use the same "in_Colour" format as shown above too.

NOTE: All uniforms must be set after calling the function shader_set(), and before calling shader_reset.

Example:

shader_set(shader_Glass);
shader_params = shader_get_uniform(shader_glass, "u_vParams");
shader_set_uniform_f(shader_params, 0.1, 0.8, 0.25);
draw_self();
shader_reset();

The above code will get the handle of the shader constant "u_vParams" ( a vec3), then set that constant to the given values.

Back: Shaders
Next: shader_set_uniform_f_array

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_set_uniform_f_array

Set a shader constant to an array of floating point values.

Syntax:

shader_set_uniform_f_array(handle, array);

Argument | Description
handle | The handle of the shader constant to set.
array | A previously initialised array of floating point values.

Returns: N/A

Description

With this function you can set a shader constant to hold an array of values. You must previously have gotten the "handle" of the constant using the function shader_get_uniform, and you will have to have previously initialised the array.

NOTE: All uniforms must be set after calling the function shader_set(), and before calling shader_reset.

Example:

shader_set(shader_Glass);
tex_array[0] = 0.5;
tex_array[1] = 0.1;
tex_array[2] = 0.25;
shader_params = shader_get_uniform(shader_glass, "u_vParams");
shader_set_uniform_f_array(shader_params, tex_array);
draw_self();
shader_reset();

The above code will get the handle of the shader constant "u_vParams" then set that constant to the given array.

Back: Shaders
Next: shader_set_uniform_i

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_set_uniform_i

Set a shader constant to a new integer value (or values).

Syntax:

shader_set_uniform_i(handle, value1 [, value2, value3, value4]);

Argument | Description
handle | The handle of the shader constant to set.
value1 ... value4 | The integer value (or values) to set the shader constant to.

Returns: N/A

Description

With this function you can set the value (or values) of a shader constant. You must previously have gotten the "handle" of the constant using the function shader_get_uniform, and you will have to know what type of constant it is to pass the correct number of integer values through to it, ie: if you have a vec2 you will need to pass two values to the function.

NOTE: All uniforms must be set after calling the function shader_set(), and before calling shader_reset.

Example:

shader_set(shader_Glass);
shader_params = shader_get_uniform(shader_glass, "u_vParams");
shader_set_uniform_i(shader_params, 0, 65, 255);
draw_self();
shader_reset();

The above code will get the handle of the shader constant "u_vParams" ( a vec3), then set that constant to the given integer values.

Back: Shaders
Next: shader_set_uniform_i_array

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_set_uniform_i_array

Set a shader constant to an array of integer values.

Syntax:

shader_set_uniform_i_array(handle, array);

Argument | Description
handle | The handle of the shader constant to set.
array | A previously initialised array of integer values.

Returns: N/A

Description

With this function you can set a shader constant to hold an array of values. You must previously have gotten the "handle" of the constant using the function shader_get_uniform, and you will have to have previously initialised the array.

NOTE: All uniforms must be set after calling the function shader_set(), and before calling shader_reset.

Example:

shader_set(shader_Glass);
col_array[0] = 255;
col_array[2] = 255;
col_array[3] = 64;
col_array[4] = 128;
shader_params = shader_get_uniform(shader_tint, "cColourArray");
shader_set_uniform_i_array(shader_params, col_array);
draw_self();
shader_reset();

The above code will get the handle of the shader constant "cColourArray" then set that constant to the given array.

Back: Shaders
Next: shader_set_uniform_matrix

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_set_uniform_matrix

Set a shader constant to the current transform matrix.

Syntax:

shader_set_uniform_matrix(handle);

Argument | Description
handle | The handle of the shader constant to set.

Returns: N/A

Description

With this function you can set the value (or values) of a shader constant to the current transform matrix (as set using the D3D Transform Functions). You must previously have gotten the "handle" of the constant using the function shader_get_uniform.

NOTE: All uniforms must be set after calling the function shader_set(), and before calling shader_reset.

Example:

shader_set(shader_Glass);
shader_matrix = shader_get_uniform(shader_glass, "u_vMatrix");
shader_set_uniform_matrix(shader_matrix);
draw_self();
shader_reset();

The above code will get the handle of the shader constant "u_vMatrix" then set that constant to the current transform matrix.

Back: Shaders
Next: shader_set_uniform_matrix_array

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shader_set_uniform_matrix_array

Set a shader constant to matrix array.

Syntax:

shader_set_uniform_matrix_array(handle, array);

Argument | Description
handle | The handle of the shader constant to set.
array | A previously initialised array of floating point values.

Returns: N/A

Description

With this function you can set a shader constant to hold an array of matrix values. You must previously have gotten the "handle" of the constant using the function shader_get_uniform, and you will have to have previously initialised the array as an array of floating point values, where each successive group of 16 floats is a 4x4 matrix.

NOTE: All uniforms must be set after calling the function shader_set(), and before calling shader_reset.

Example:

shader_set(shader_Glass);
shader_params = shader_get_uniform(shader_tint, "cMatrixArray");
shader_set_uniform_matrix_array(shader_params, matrix_array);
draw_self();
shader_reset();

The above code will get the handle of the shader constant "cMatrixArray" then set that constant to the given array.

Back: Shaders
Next: shader_reset

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shaders_are_supported

Checks to see if the target platform supports shaders.

Syntax:

shaders_are_supported();

Returns: Boolean

Description

This function will do a check to see if the chosen target platform supports shaders, returning true if they do, and false if they do not.

Example:

global.GFX = false;
if shaders_are_supported()
{
if shader_is_compiled(sh_glass) && shader_is_compiled(sh_warp)
{
global.GFX = true;
}
}

The above code will set a global variable to false, and then if the platform supports shaders and both the shaders being checked have compiled correctly, it will be set to true.

Back: Shaders
Next: shader_current

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Primitive Building

This section explains the functions used to create custom primitives.

GameMaker: Studio permits you to define your own custom primitives following the specifications of the vertex format that you have chosen (see Vertex Formats). These can then be used within any shaders that you have created.

The Vertex Buffer

Any primitives that you build are held in a vertex buffer. This must be created beforehand and then referenced by the functions that are used to build your primitive. The vertex buffer can be re-used as many times as necessary to create different primitives, or it can be "frozen" to maintain a specific primitive type for the duration of your game or level (which is the fastest approach, so if you know that a primitive you build will not change then you should always use this option).

The following functions are available for the vertex buffer:

  1. vertex_create_buffer
  2. vertex_create_buffer_ext
  3. vertex_create_buffer_from_buffer
  4. vertex_create_buffer_from_buffer_ext
  5. vertex_get_buffer_size
  6. vertex_get_number
  7. vertex_delete_buffer

Building A Primitive

The primitives that you build should follow the format that you have set using the Vertex Formats functions, so if you have defined a vertex format with only positional data, there is no point building your primitive with colour data. You should note that the order in which you add properties to the primitive you are building is defined by the order in which you added these properties when creating the vertex format, so if you have defined the vector format with the order position, colour and texture coordinate, you must add these properties to the primitive being built in the same order otherwise you will get errors.

An example of a single triangle primitive being built is shown in the following code:

v_buff = vertex_create_buffer();
vertex_begin(v_buff, global.my_format);
vertex_position(v_buff, 10, 10);
vertex_colour(v_buff, c_white, 1);
vertex_texcoord(v_buff, 0, 0);
vertex_position(v_buff, 110, 10);
vertex_colour(v_buff, c_white, 1);
vertex_texcoord(v_buff, 1, 0);
vertex_position(v_buff, 110, 110);
vertex_colour(v_buff, c_white, 1);
vertex_texcoord(v_buff, 1, 1);
vertex_end(v_buff);
var tex = background_get_texture(background1);
shader_set(shader_prim);
vertex_submit(v_buff, pr_trianglelist, tex);
shader_reset();

Primitives can be points, line lists or strips, or triangle lists or strips, but you are not permitted triangle fans since most mobile hardware will not accept that primitive type. The constants used to define these different primitive types can be found here.

NOTE: You can build the primitive and store it in the vertex buffer in any step of your game, however to draw it, you must submit it during the Draw Event.

The following functions are available for building primitives:

  1. vertex_begin
  2. vertex_colour
  3. vertex_normal
  4. vertex_position
  5. vertex_position_3d
  6. vertex_argb
  7. vertex_texcoord
  8. vertex_float1
  9. vertex_float2
  10. vertex_float3
  11. vertex_float4
  12. vertex_ubyte4
  13. vertex_end
  14. vertex_freeze
  15. vertex_submit

Back: Shaders
Next: Vertex Formats

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_argb

Set the ARGB values for the vertex.

Syntax:

vertex_argb(buffer, argb);

Argument | Description
buffer | The buffer to write the information to.
a | The alpha value for the colour (0 - 255).
r | The red component part of a colour (0 - 255).
g | The green component part of a colour (0 - 255).
b | The blue component part of a colour (0 - 255).

Returns: N/A

Description

This function will set the ARGB values for the vertex currently being defined for the custom primitive. You supply the buffer to write the data into as well as the red, green, blue and alpha values that you wish to use as a single 32-bit unsigned integer - alpha sample in the highest 8 bits, followed by the red sample, green sample and finally the blue sample in the lowest 8 bits. You can use hex notation ($AARRGGBB) a real number or use any of the make_colour_*() functions to define the colour value.

Example:

vertex_argb(buff, $FFFFFFFF);

The above code will set the ARGB values of the vertex being defined to white.

Back: Building Primitives
Next: vertex_texcoord

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_begin

Begin the definition of a custom primitive.

Syntax:

vertex_begin(buffer, format);

Argument | Description
buffer | The buffer to be written to.
format | The vertex format to use.

Returns: N/A

Description

With this function you begin the definition of a custom primitive. You assign a buffer to write the primitive to, and the vertex format to use (previously defined using the vertex format functions). You would then define the necessary points for each vertex of the primitive before calling vertex_end to finalise the primitive creation.

Example:

vertex_format_begin();
vertex_format_add_position();
vertex_format_add_colour();
vertex_format_add_textcoord();
v_format = vertex_format_end();
v_buff = vertex_create_buffer();
vertex_begin(v_buff, v_format);

The above code will define a new vertex format, create a new buffer and start the definition process of a new primitive.

Back: Building Primitives
Next: vertex_get_number

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_colour

Set the colour and alpha for the vertex.

Syntax:

vertex_colour(buffer, colour, alpha);

Argument | Description
buffer | The buffer to write the information to.
colour | The colour for this vertex (can be a constant or a hex value).
alpha | The alpha value for the vertex (from 0 to 1).

Returns: N/A

Description

If your defined vertex format takes a colour value you can use this function to add that data to the vertex being defined for the current primitive. The function needs a buffer to store the data in and will take either a colour constant, or a hex value (using the standard GameMaker: Studio format of BGR, eg: $FF0000 for blue) as well as an alpha value from 0 (transparent) to 1 (fully opaque).

Example:

vertex_colour(b, c_white, 1);

The above code will set the vertex being defined to be white with an alpha value of 1.

Back: Building Primitives
Next: vertex_normal

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_create_buffer

Create a new vertex buffer.

Syntax:

vertex_create_buffer();

Returns: Pointer

Description

With this function you can create a new vertex buffer. This is a special grow buffer created by GameMaker: Studio which is pre-formatted for use when building primitives (for use with shaders, for example). The function will return a "Pointer" (index) for the buffer which should then be used in all further calls to it.

When using a vertex buffer created with this function you simply call vertex_begin to start assigning vertex data to it to start to define your custom primitive, which will then be held in the buffer ready for submission to the shader. The buffer can be re-used when necessary (unless you have used the vertex_freeze function), with each call of vertex_begin wiping the previous buffer data ready to accept the new data.

Example:

v_buff = vertex_create_buffer();

The above code will create a new a new vertex buffer and store its handle in the variable "v_buff".

Back: Primitive Building
Next: vertex_create_buffer_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_create_buffer_ext

Create a vertex buffer of a given size.

Syntax:

vertex_create_buffer_ext(size);

Argument | Description
size | The initial size of the buffer (in bytes).

Returns: Pointer

Description

As with the function vertex_create_buffer, this function will create a new vertex buffer. This is a special grow buffer created by GameMaker: Studio which is pre-formatted for use when building primitives for use with shaders. You can specify an initial starting size for the buffer (in bytes) and it will return a "handle" (index) for the buffer which should then be used in all further calls to the buffer.

Example:

v_buff = vertex_create_buffer_ext(1024 * 1024);

The above code will create a new vertex buffer, initially 1MB in size, and store its handle in the variable "v_buff".

Back: Vertex Formats
Next: vertex_create_buffer_from_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_create_buffer_from_buffer

Create a vertex buffer from a regular buffer.

Syntax:

vertex_create_buffer_from_buffer(buffer, format);

Argument | Description
buffer | The buffer to create the vertex buffer from.
format | The primitive vertex format to use.

Returns: Pointer

Description

As with the function vertex_create_buffer, this function will create a new vertex buffer, only now the vertex data it stores is copied from the regular buffer that is specified as the source. The buffer created is a special grow buffer which is pre-formatted with the vertex format for building primitives for use with (for example) shaders. This function requires that you supply the pointer to a previously created regular buffer, and a vertex format that should be applied to the copied data.

Example:

vertex_format_begin();
vertex_format_add_position_3d();
vertex_format_add_colour();
vertex_format_add_textcoord();
var my_format = vertex_format_end();
v_buff = vertex_create_buffer_from_buffer(global.modelBuff, myFormat);

The above code will create a new vertex format then create a new vertex buffer from a previously created regular buffer, applying the custom vertex format to it.

Back: Vertex Formats
Next: vertex_delete_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_create_buffer_from_buffer_ext

Create a vertex buffer of a given size.

Syntax:

vertex_create_buffer_from_buffer_ext(buffer, format, src_offset, vert_num);

Argument | Description
buffer | The buffer to create the vertex buffer from.
format | The primitive vertex format to use.
src_offset | The offset within the the source buffer to copy from.
vert_num | The number of vertices the buffer should have.

Returns: Pointer

Description

As with the function vertex_create_buffer, this function will create a new vertex buffer, only now the vertex data it stores is copied from the regular buffer that is specified as the source. The buffer is pre-formatted with the vertex format for building primitives for use with (for example) shaders, and you can also supply an offset within the source buffer to copy from and the number of vertices that the final buffer should have. Note that if the number of vertices does not match those being copied you may get corrupted vertex data.

Example:

vertex_format_begin();
vertex_format_add_position_3d();
vertex_format_add_colour();
vertex_format_add_textcoord();
var my_format = vertex_format_end();
v_buff = vertex_create_buffer_from_buffer(global.modelBuff, myFormat, 0, 512);

The above code will create a new vertex format then create a new vertex buffer from a previously created regular buffer, applying the custom vertex format to it with 0 offset. The function tells the new vertex buffer that it should expect 512 vertices.

Back: Vertex Formats
Next: vertex_get_buffer_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_delete_buffer

Delete a vertex buffer from memory.

Syntax:

vertex_delete_buffer(buffer);

Argument | Description
buffer | The buffer to be removed.

Returns: N/A

Description

This function can be used to remove a previously created vertex buffer (see vertex_create_buffer) from system memory. This will also remove all vertex data for any custom primitives that it contained.

Example:

vertex_delete_buffer(v_buff);

The above code will delete from memory the buffer indexed in the variable "v_buff".

Back: Vertex Formats
Next: vertex_begin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_end

Finish building the primitive.

Syntax:

vertex_end(buffer);

Argument | Description
buffer | The buffer to end writing to.

Returns: N/A

Description

With this function you end the building of the custom primitive. Once you call this command the primitive can be used in the vertex_submit function for use in a shader or you can freeze the buffer (making the vertex buffer used read-only and much faster) using vertex_freeze.

Example:

vertex_end(buff);

The above code will end the defining of a custom primitive.

Back: Building Primitives
Next: vertex_freeze

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_float1

Add a floating point value to a vertex.

Syntax:

vertex_float1(buffer, float);

Argument | Description
buffer | The buffer to write the information to.
float | The input value.

Returns: N/A

Description

This function will add a floating point value to the vertex data. The vertex must have been formatted correctly to accept this using the vertex_format_add_custom function.

Example:

vertex_float1(buff, 0.05);

The above code will add a floating point value to the vertex data being defined.

Back: Building Primitives
Next: vertex_float2

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_float2

Add floating point values to a vertex.

Syntax:

vertex_float2(buffer, float, float);

Argument | Description
buffer | The buffer to write the information to.
float | The first input value.
float | The second input value.

Returns: N/A

Description

This function will add two floating point values to the vertex data. The vertex must have been formatted correctly to accept this using the vertex_format_add_custom function.

Example:

vertex_float2(buff, 0.05, 0.01);

The above code will add two floating point values to the vertex data being defined.

Back: Building Primitives
Next: vertex_float3

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_float3

Add floating point values to a vertex.

Syntax:

vertex_float3(buffer, float, float, float);

Argument | Description
buffer | The buffer to write the information to.
float | The first input value.
float | The second input value.
float | The third input value.

Returns: N/A

Description

This function will add three floating point values to the vertex data. The vertex must have been formatted correctly to accept this using the vertex_format_add_custom function.

Example:

vertex_float3(buff, 0.05, 0.01, room_width / x);

The above code will add three floating point values to the vertex data being defined.

Back: Building Primitives
Next: vertex_float4

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_float4

Add floating point values to a vertex.

Syntax:

vertex_float4(buffer, float, float, float, float);

Argument | Description
buffer | The buffer to write the information to.
float | The first input value.
float | The second input value.
float | The third input value.
float | The fourth input value.

Returns: N/A

Description

This function will add four floating point values to the vertex data. The vertex must have been formatted correctly to accept this using the vertex_format_add_custom function.

Example:

vertex_float4(buff, 0.05, 0.01, room_width / x, room_height / y);

The above code will add four floating point values to the vertex data being defined.

Back: Building Primitives
Next: vertex_ubyte4

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_freeze

Freeze the given vertex buffer.

Syntax:

vertex_freeze(buffer);

Argument | Description
buffer | The buffer to freeze.

Returns: N/A

Description

This function can be used to "freeze" a vertex buffer. this buffer becomes read-only, meaning that should you need to change it, you would have to delete the whole buffer and re-create it. A frozen buffer can be submitted to the shader faster than a normal, dynamic buffer and is recommended for those effects that require an unchanging custom primitive for the duration of a level or the game.

Example:

vertex_freeze(buff);

The above code will freeze the given vertex buffer.

Back: Building Primitives
Next: vertex_submit

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_get_buffer_size

Get the size - in bytes - of a given vertex buffer.

Syntax:

vertex_get_buffer_size(buffer);

Argument | Description
buffer | The buffer to get the size of.

Returns: Real

Description

With this function you can get the size of the given vertex buffer in bytes.

Example:

bufferBytes = vertex_get_buffer_size(buff);

The above code will get the number of bytes used by the vertex buffer given and store the value in the variable "bufferBytes".

Back: Vertex Formats
Next: vertex_get_number

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_get_number

Get the number of vertices in the given vertex buffer

Syntax:

vertex_get_number(buffer);

Argument | Description
buffer | The vertex buffer to check.

Returns: Real

Description

With this function you can find out the number of individual vertices defined in any given vertex buffer.

Example:

v_num = vertex_get_number(v_buffer);

The above code will store the number of vertices stored in the given vertex buffer to a variable.

Back: Building Primitives
Next: vertex_delete_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_normal

Set the surface normal for the vertex.

Syntax:

vertex_normal(buffer, nx, ny, nz);

Argument | Description
buffer | The buffer to write the information to.
nx | The x component of the surface normal.
ny | The y component of the surface normal.
nz | The z component of the surface normal.

Returns: N/A

Description

This function will add surface normal data to the vertex currently being defined for the custom primitive. You supply the buffer to write the data into as well as the x, y and z component parts of the normal.

Example:

vertex_normal(buff, 0, 1, 1);

The above code will set the surface normal of the vertex being defined.

Back: Building Primitives
Next: vertex_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_position

Set the 2D position for the vertex.

Syntax:

vertex_position(buffer, x, y);

Argument | Description
buffer | The buffer to write the information to.
x | The x position.
y | The y position.

Returns: N/A

Description

This function will add 2D position data to the vertex currently being defined for the custom primitive. You supply the buffer to write the data into as well as the x and y position for drawing.

Example:

vertex_position(buff, x - 100, y - 125);

The above code will set the position of the vertex being defined.

Back: Building Primitives
Next: vertex_position_3d

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_position_3d

Set the 3D position for the vertex.

Syntax:

vertex_position_3d(buffer, x, y, z);

Argument | Description
buffer | The buffer to write the information to.
x | The x position.
y | The y position.
z | The z position.

Returns: N/A

Description

This function will add 3D position data to the vertex currently being defined for the custom primitive. You supply the buffer to write the data into as well as the x, y and z position for drawing.

Example:

vertex_position_3d(buff, x - 100, y - 125, 0);

The above code will set the position of the vertex being defined.

Back: Building Primitives
Next: vertex_argb

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_submit

Freeze the given vertex buffer.

Syntax:

vertex_submit(buffer, primitive, texture);

Argument | Description
buffer | The buffer to use.
primitive | The primitive base type.
texture | The texture to use (or -1 for no texture).

Returns: N/A

Description

You can use this function to submit the contents of a vertex buffer to the graphics pipeline for use with a shader. You supply the buffer index to use, the base primitive type to use (see the constants below) and the texture that is to be used. The base primitive type is only used for assigning the order in which the vertexes that you stored in the buffer are drawn and connected, but the actual data used for each of the vertexes will be that which you defined when creating the vertex buffer.

For a visual example of the different base primitives available, please see the function draw_primitive_begin

NOTE: this function can only be used in the Draw Event.

Constant | Description
pr_pointlist | A primitive consisting of a list of points.
pr_linelist | A primitive made up of a individual lines in a list.
pr_linestrip | A primitive made up of a consecutive strip of lines.
pr_trianglelist | A primitive made up of individual triangles in a list.
pr_triangle_strip | A primitive made up of a consecutive strip of triangles.

Example:

shader_set(shader_prim);
vertex_submit(buff, pr_trianglelist, sprite_get_texture(sprite_index));
shader_reset();

The above code will submit the vertex buffer indexed in the variable "buff" for drawing with the shader "shader_prim", using a triangle list as the base primitive and the texture of the sprite for the instance running the code.

Back: Building Primitives
Next: vertex_create_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_texcoord

Set UV coordinates for the texture being used for the vertex.

Syntax:

vertex_texcoord(buffer, u, v);

Argument | Description
buffer | The buffer to write the information to.
u | The first texture coordinate to use (0 - 1).
v | The second texture coordinate to use (0 - 1).

Returns: N/A

Description

This function will set the texture coordinates to use for the vertex currently being defined for the custom primitive. You supply the buffer to write the data into as well as the UV position within the texture to use.

Example:

vertex_texcoord(buff, 0, 0);

The above code will set the UV values of the vertex being defined.

Back: Building Primitives
Next: vertex_float1

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_ubyte4

Add four unsigned byte values to a vertex.

Syntax:

vertex_ubyte4(buffer, byte, byte, byte, byte);

Argument | Description
buffer | The buffer to write the information to.
byte | The first input value.
byte | The second input value.
byte | The third input value.
byte | The fourth input value.

Returns: N/A

Description

This function will add four unsigned byte values (0 - 255) to the vertex data. The vertex must have been formatted correctly to accept this using the vertex_format_add_custom function.

Example:

vertex_ubyte4(buff, irandom(255), irandom(255), irandom(255), 127);

The above code will add four values to the vertex data being defined.

Back: Building Primitives
Next: vertex_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Shader Constants

This section lists the GameMaker: Studio specific constants used for creating shaders.

Apart from the shader functions and constants defined in the OpenGL ES Shading Language (GLSL ES) Reference Pages, there are also a number of shader constants available to you that are unique to GameMaker: Studio.

Matrices

The following display matrix constants can be used as array indices when using the shader array constant gm_Matrices:

Constant | Description
MATRIX_VIEW | This array index constant holds the index to the current view matrix. The index returned would be used as an array value when calling the gm_Matrices constant within the shader code.
MATRIX_PROJECTION | This array index constant holds the index to the current projection matrix. The index returned would be used as an array value when calling the gm_Matrices constant within the shader code.
MATRIX_WORLD | This array index constant holds the index to the current world matrix. This can be used for things like lighting if you have light information in world-space. The index returned would be used as an array value when calling the gm_Matrices constant within the shader code.
MATRIX_WORLD_VIEW | This array index constant holds the index to the result of the world and view matrices multiplied together. This is often used for things like fog. The index returned would be used as an array value when calling the gm_Matrices constant within the shader code.
MATRIX_WORLD_VIEW_PROJECTION | This array index constant holds the index to the result of the world, view and projection matrices multiplied together. This is the normal transformation matrix used for vertex positions. The index returned would be used as an array value when calling the gm_Matrices constant within the shader code.
MATRIX_MAX | This is not an array index, but rather returns the size of the matrix array in the vertex shader.
MAX_VS_LIGHTS | This is not an array index, but rather returns the number of the lights in the vertex shader.

Other Constants

The following pre-defined matrix uniforms and constants can be used in your shader to access GameMaker: Studio specific values:

Constant | Description
gm_Matrices[matrix] | This array constant returns a transform matrix and is one of the available pre-defined uniforms that GameMaker: Studio creates for you to use within the shader code editor. The array index is chosen from one of the above listed constants.
gm_BaseTexture | This is a 2D sampler constant that returns the texture of the current object, as set by GameMaker: Studio. So it would be the current sprite, surface or texture that would normally be used when drawing without the shader being called.
gm_LightingEnabled | This can be used to get or set the GameMaker: Studio lighting when using 3D.
gm_FogStart | This can be used to get the distance where polygons start to be blended with the fog colour.
gm_RcpFogRange | This can be used to get the distance at which fog is maximal and nothing can be seen anymore.
gm_PS_FogEnabled | This will return true or false if the GPU has pixel fog enabled or not.
gm_FogColour | This can be used to get the fog colour used by GameMaker: Studio.
gm_VS_FogEnabled | This will return true or false if the GPU has vertex fog enabled or not.
gm_AlphaTestEnabled | This can be used to get alpha testing in the shader. See draw_set_alpha_test for more information on alpha testing.
gm_AlphaRefValue | This can be used to get the current alpha testing reference value. See draw_set_alpha_test_ref_value for more information on the alpha test reference.

Back: Shaders

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Vertex Formats

This section explains how to define and build your own vertex formats.

In general when you start working with shaders you need not worry too much about the vertex format being used, since GameMaker: Studio will automatically set up and pass through the vertex data for you.

However, sometimes it is necessary to create your own vertex data and format it to suit, especially when you need to boost speed, or wish to pass in extra information. For example the standard vertex format includes an x, y, z 3D position, colour (with alpha), and UV texture coordinates, which, if you were creating it yourself, would look something like:

vertex_format_begin();
vertex_format_add_position_3d();
vertex_format_add_colour();
vertex_format_add_textcoord();
my_format = vertex_format_end();

However, if you are only using (for example) the shader to manipulate the position of the vertex, then there would be no need to pass through colour or texture data. In this case you would create your own format as so:

vertex_format_begin();
vertex_format_add_position_3d();
my_format = vertex_format_end();

You should note that once you have created your vertex format, the order in which you have defined the vertex properties must be honoured when building your primitives. So, if you have defined a vertex format as position, colour, texture coordinate, then you must add these properties to the primitive in the same order otherwise you will get an error. Also note that like any other dynamic resource, a vector format requires memory and therefore should be removed when not needed using the function vector_format_delete().

The following functions are available for drawing shaders:

  1. vertex_format_begin
  2. vertex_format_add_colour
  3. vertex_format_add_position
  4. vertex_format_add_position_3d
  5. vertex_format_add_textcoord
  6. vertex_format_add_normal
  7. vertex_format_add_custom
  8. vertex_format_end
  9. vertex_format_delete

One final important point to note when using your own vertex buffers in this way is how it affects the vertex batches that are sent to the GPU. When you create a vertex buffer you are creating the lowest level of graphics data, so when you draw all that happens is we send your buffer directly to the graphics card. Because of this, if you want better batching, you must work it out yourself and store things you want batch inside the same buffer. So you can't put in 3 sprites then draw many of them and expect vertex buffers to be merged - you're in charge of vertex buffer data at this point. If you want auto-batching then you have to give the engine higher level primitives - like a sprite - at which point GameMaker: Studio can work out what your doing, and fill buffers properly.

Building Your Primitives

Once you have defined your new vertex format, you can then go ahead and build your primitives that will use it. The functions available for this can be found in the following section:

  1. Primitive Building

Back: Shaders
Next: Primitive Building

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_format_add_colour

Add colour data to the vertex format.

Syntax:

vertex_format_add_colour();

Returns: N/A

Description

Tell GameMaker: Studio to accept colour data as part of the new vertex format being created.

Example:

vertex_format_begin();
vertex_format_add_colour();
vertex_format_add_position();
my_format = vertex_format_end();

The above code will create a new vertex format with just colour and position values and then store the format id in the variable "my_format".

Back: Vertex Formats
Next: vertex_format_add_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_format_add_custom

Add custom values to the vertex format.

Syntax:

vertex_format_add_custom(type, usage);

Argument | Description
type | The data type that this custom vertex data will hold (see the type constants listed below).
usage | The use that the data will get(see the usage constants listed below).

Returns: N/A

Description

Tell GameMaker: Studio to accept a custom value (or values) as part of the new vertex format being created. The available values to use are defined by the data type constant that you choose, listed below:

Constant | Description
vertex_type_float1 | A single floating point value
vertex_type_float2 | Two floating point values
vertex_type_float3 | Three floating point values
vertex_type_float4 | Four floating point values
vertex_type_colour | Four component values (r, g, b, a)
vertex_type_ubyte4 | Four component unsigned byte values (from 0 to 255)

The use that these constants will be put too also needs to be defined so that the values can be "bound" properly within the shader being created. This is necessary due to the fact that DX and OpenGL have different requirements so if you don't bind them properly, they won't come through right in the shader. The available usage constants that you can choose are listed below and those you use will depend on the specifics of the shader being created:

Constant | Description
vertex_usage_position | position values (x, y, z)
vertex_usage_colour | colour values (r, g, b, a)
vertex_usage_normal | vertex normal values (nx, ny, nz)
vertex_usage_textcoord | UV coordinates (u, v)
vertex_usage_blendweight | the blendweight of the input matrix (for skeletal animation, for example)
vertex_usage_blendindices | the indices of the matrices to use (for skeletal animation, for example)
vertex_usage_depth | vertex depth buffer value
vertex_usage_tangent | tangent values
vertex_usage_binormal | binormal values
vertex_usage_fog | fog values
vertex_usage_sample | sampler index

Example:

vertex_format_begin();
vertex_format_add_textcoord();
vertex_format_add_custom(vertex_type_float3, vertex_usage_position);
my_format = vertex_format_end();

The above code will create a new vertex format with just texture and 3 custom floating point values for position. It is then stores the format id in the variable "my_format".

Back: Vertex Formats
Next: vertex_format_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_format_add_textcoord

vertex_format_add_normal

Add surface normal data to the vertex format.

Syntax:

vertex_format_add_normal();

Returns: N/A

Description

Tell GameMaker: Studio to accept surface normal data (nx, ny and nz) as part of the new vertex format being created.

Example:

vertex_format_begin();
vertex_format_add_textcoord();
vertex_format_add_normal();
my_format = vertex_format_end();

The above code will create a new vertex format with just texture and surface normal values and then store the format id in the variable "my_format".

Back: Vertex Formats
Next: vertex_format_add_custom

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_format_add_position

Add 2D position data to the vertex format.

Syntax:

vertex_format_add_position();

Returns: N/A

Description

Tell GameMaker: Studio to accept 2D positional data (x and y) as part of the new vertex format being created.

Example:

vertex_format_begin();
vertex_format_add_colour();
vertex_format_add_position();
my_format = vertex_format_end();

The above code will create a new vertex format with just colour and position values and then store the format id in the variable "my_format".

Back: Vertex Formats
Next: vertex_format_add_position_3d

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_format_add_position_3d

Add 3D position data to the vertex format.

Syntax:

vertex_format_add_position_3d();

Returns: N/A

Description

Tell GameMaker: Studio to accept 3D positional data (x, y and z) as part of the new vertex format being created.

Example:

vertex_format_begin();
vertex_format_add_colour();
vertex_format_add_position_3d();
my_format = vertex_format_end();

The above code will create a new vertex format with just colour and position values and then store the format id in the variable "my_format".

Back: Vertex Formats
Next: vertex_format_add_textcoord

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_format_add_textcoord

Add texture position data to the vertex format.

Syntax:

vertex_format_add_textcoord();

Returns: N/A

Description

Tell GameMaker: Studio to accept texture position data (u and v) as part of the new vertex format being created.

Example:

vertex_format_begin();
vertex_format_add_textcoord();
vertex_format_add_position_3d();
my_format = vertex_format_end();

The above code will create a new vertex format with just texture and position values and then store the format id in the variable "my_format".

Back: Vertex Formats
Next: vertex_format_add_normal

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_format_begin

Begin the definition of a custom vertex format.

Syntax:

vertex_format_begin();

Returns: N/A

Description

Before you can define your new vertex format you must tel GameMaker: Studio that your doing so using this function. You must call this first, then define the format values using the appropriate functions, and finally call vertex_format_end to finish the definition and return the new format "handle".

Example:

vertex_format_begin();
vertex_format_add_colour();
vertex_format_add_position();
my_format = vertex_format_end();

The above code will create a new vertex format with just colour and position values and then store the format id in the variable "my_format".

Back: Vertex Formats
Next: vertex_format_add_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_format_delete

Remove a custom vertex format from memory.

Syntax:

vertex_format_delete(formatID);

Returns: N/A

Description

This function must be called whenever you are finished using any created vector formats. You provide the format ID value (as returned by the function vector_format_end()), and this function will free the memory associated with it. Note that if you try to use this format again after calling this function, you will get an error.

Example:

vertex_format_delete(myFormat);

The above code will remove the vertex format created in the variable "myFormat" from memory.

Back: Vertex Formats
Next: vertex_format_begin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


vertex_format_end

Add custom values to the vertex format.

Syntax:

vertex_format_end();

Returns: Real

Description

This function must be called after defining any new vertex format. It returns the new format "handle" (index) which must be used in all further vertex functions that refer to this new format.

Example:

vertex_format_begin();
vertex_format_add_colour();
vertex_format_add_position();
my_format = vertex_format_end();

The above code will create a new vertex format with just colour and position values and then store the format id in the variable "my_format".

Back: Vertex Formats
Next: vertex_format_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Social gaming

This section deals with those platform specific functions for integrating social networks with GameMaker: Studio.

As the mobile platforms grow and take up more of the gaming market share, so to does the demand for social interaction and feedback from these games. To meet these demands GameMaker: Studio has a number of APIs integrated into it to permit you to communicate with different networks depending on the device you are targeting for your game.

The following sections contain information on the available social media integration:

  1. Facebook
  2. Achievements and Leaderboards

There is also an asynchronous function that will open a dialogue and permit you to request that a user of your game leaves a comment or rating on a specific web page:

  1. shop_leave_rating

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


shop_leave_rating

With this you can ask the user to add a rating.

Syntax:

shop_leave_rating(text, yes_string, no_string, url)

Argument | Description
text | Text that appears on the dialogue.
yes_string | Text that appears on the "yes" button.
no_string | Text that appears on the "no" button.
url | The full URL where the comment has to be sent.

Returns: N/A

Description

This function opens up an OS dependant dialogue where you can ask the user to post a rating or comment to a particular page. You can define the text that is to appear in the dialogue, as well as the text you wish to appear on the two buttons and the URL where the comment has to be posted.

NOTE: This function is only for Android and iOS targets.

IMPORTANT! On iOS, when using TestFlight, in development the prompt will be displayed but you won't be able to actually do anything. Once your app is in the App Store, this button becomes active and the user is given the option to write a review or leave a rating. Note that if you distribute the game through TestFlight, this window may not even be shown.

Example:

if timer <= 0
{
shop_leave_rating("Thanks for playing the game! Why not leave a comment?", "Okay!", "Not Today!", "http://MacSweeney/comments");
timer = 10000000;
}
else
{
timer -= 1;
}

The above code will ask the user to leave a comment if the variable "timer" has counted down to 0.

Back: Social Gaming

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Achievements and Leaderboards

Here you can find the functions for integrating your game with the available leaderboard and achievements APIs

Games that are made to target devices that run iOS or Android can also connect to one of two leaderboard and achievement API's. For iOS you have the iTunes Game Center, and for Android you can use the Amazon Game Circle or Google Play, with all of them using the using the functions found on this page. These functions permit your game to send information on scores and achievements to the leaderboards that you have set up in the Developers Account for the game you are making and is an excellent way to get players involved in the social side of gaming as they can then see what other people who have played your game have achieved and try to better them.

When using these functions, you should note that they do not track achievements and scores automatically for you. They only show the data that you send them from your game, so you must code your own achievements and hi-score system to keep track of the individuals status in game, then use these functions to add the data to the chosen network (however you can request progress information for achievements using the achievement_load_progress function).

Some of these functions will trigger a callback Social Asynchronous Event, which will contain a ds_map of data relating to the function that triggered it. Those functions that trigger the event also detail the map key/value pairs that are returned by the callback, however a callback Social Event can also be triggered by your game receiving external notifications about challenges etc... The exact details of the ds_map returned for these events are explained in the Social Asynchronous Event section.

NOTE: For these functions to work with iOS you must have a valid Game Center account and an iOS app id for your game.

NOTE: For these functions to work with Android you must submit your game to the Amazon App store, or to Google Play, and have set up the necessary sections as well as have the API activated in the Global Game Settings for your game.

The functions listed below are the basic ones used for integrating your game with the chosen target social gaming platform:

  1. achievement_login_status
  2. achievement_login
  3. achievement_logout
  4. achievement_available
  5. achievement_post
  6. achievement_post_score
  7. achievement_increment
  8. achievement_show_achievements
  9. achievement_show_leaderboards
  10. achievement_show_challenge_notifications
  11. achievement_get_challenges
  12. achievement_get_pic
  13. achievement_load_friends
  14. achievement_load_leaderboard
  15. achievement_load_progress
  16. achievement_send_challenge
  17. achievement_reset

Local High Scores

Apart from these functions for devices, GameMaker: Studio also integrates a basic highscore storage system that is local to your game and compatible with all platforms. This system can store up to ten places (with names and scores) locally, which you can then draw on-screen as you wish. For more information see:

  1. Local High Scores

Back: Social Gaming

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_available

Check to see if the chosen leaderboard is available.

Syntax:

achievement_available()

Returns: Boolean

Description

This function will return true if the user is currently connected to the internet and the chosen leaderboard and achievement system is available, otherwise it will return false.

Example:

if achievement_available() achievement_post("ach_Level1", 100);

The above code will check that the leaderboard service is available and if so, post to it.

Back: Achievements and Leaderboards
Next: achievement_post

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_get_challenges

Requests information on current challenges.

Syntax:

achievement_get_challenges()

Returns: N/A

Description

This function will send a request to the server for information on all current challenges and will trigger a callback Social Asynchronous Event which contains the async_load map populated with the relevant key/value pairs. The id key of this ds_map is used to identify the correct callback (there can be more than one trigger function for any given asynchronous event), and will be paired with the constant achievement_challenge_list_received as well as a number of other key/value pairs for each challenge. The exact contents of the map are shown below:

  1. "id" - For this function it should be achievement_challenge_list_received

  2. "numchallenges" - The number of challenges (local and remote) currently available.

  3. "ChallengeNplayerid" - The player id for the challenge, where "N" is an integer, EG: "Challenge5playerid" is the player id for the fifth challenge in the list.

  4. "ChallengeNissuerid" - The id of the person that issued the challenge, where "N" is an integer, EG: "Challenge2issuerid" is the issuer id for the second challenge in the list.

  5. "ChallengeNstate" - The state of the challenge "N", which will have a value of 0 - 3 (as a string) for invalid, pending, completed or declined.

  6. "ChallengeNmessage" - The text message for challenge "N".

  7. "ChallengeNissueddate" - The issue date for challenge "N".

  8. "ChallengeNcompleteddate" - The completion date for challenge "N".

  9. "ChallengeNtype" - The type of challenge given. Can be one of two constants:
    • achievement_type_score_challenge - A challenge based on the score value.
    • achievement_type_achievement_challenge - A challenge based on an achievement.
  10. "ChallengeNidentifier" - The identifying string for the challenge.

  11. "ChallengeNscore" - The score tied in with the challenge.

NOTE: This function is for iOS only.

Extended Example:

The following code would probably be called after the player has logged into their game account using achievement_login:

achievement_get_challenges();

This will send off a request for the current challenge information and generate an asynchronous callback with the special async_load ds_map containing the following data:

var ident = ds_map_find_value(async_load, "id");
if ident == achievement_challenge_list_received
{
var numentries = ds_map_find_value(async_load,"numchallenges");
for(var i = 0; i < numentries; i++;)
{
player_id[i] = ds_map_find_value(async_load, "Challenge" + string(i)+"playerid");
issuer_id[i] = ds_map_find_value(async_load, "Challenge" + string(i) +"issuerid");
state[i] = ds_map_find_value(async_load, "Challenge" + string(i)+"state");
message[i] = ds_map_find_value(async_load, "Challenge" + string(i)+"message");
date_completed[i] = ds_map_find_value(async_load, "Challenge" + string(i)+"completeddate");
date_issued[i] = ds_map_find_value(async_load, "Challenge" + string(i)+"issueddate");
ach_type[i] = ds_map_find_value(async_load, "Challenge" + string(i)+"type");
ach_ident[i] = ds_map_find_value(async_load, "Challenge" + string(i)+"identifier");
ach_score[i] = ds_map_find_value(async_load, "Challenge" + string(i)+"score");
}

The above code checks the returned ds_map in the Social Asynchronous Event and if its "id" matches the constant being checked, it then loops through the map storing all the different values in a number of arrays. This information can then be used, for example, to create your own, personalised, challenge pages in game.

Back: Achievements and Leaderboards
Next: achievement_get_pic

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_get_pic

Requests an image of a player or a friend for display.

Syntax:

achievement_get_pic(char)

Argument | Description
char | The id of the person to get the image of (either from a friends list or a leaderboard)

Returns: N/A

Description

This function will send a request to the server for the image of a player or a friend and will trigger a callback Social Asynchronous Event which contains the async_load map populated with the relevant key/value pairs. The id key of this ds_map is used to identify the correct callback (there can be more than one trigger function for any given asynchronous event), and will be paired with the constant achievement_pic_loaded as well as a number of other key/value pairs. The exact contents of the map are shown below:

  1. "id" - For this function it should be achievement_pic_loaded

  2. "playerid" - The id of the player or friend that we are receiving the image of.

  3. "spriteid" - The sprite id for the image that can then be used to draw it on-screen using any of the draw sprite functions

NOTE: This function is for iOS only.

WARNING: This function creates sprites and as such, their ids should be stored in variables and then removed from memory using the sprite_delete function otherwise repeated use will give you a memory leak that will eventually slow down or crash your game.

Extended Example:

The following code would be called after you have gotten a friends list or a leaderboards list using achievement_load_friends or achievement_load_leaderboard. Those functions will return unique "id" values for each person, which are then used in the function to retrieve the profile picture for them:

achievement_get_pic(global.player_id[0]);

This will send off a request for the image associated with the player id stored in the global array and generate an asynchronous callback with the special async_load ds_map containing the following data:

var ident = ds_map_find_value(async_load, "id");
if ident == achievement_pic_loaded
{
var picid = ds_map_find_value(async_load, "playerid");
var spriteid = ds_map_find_value(async_load, "spriteid");
if global.playerid[0] == picid)
{
global.playerpic[0] = spriteid;
}
}

The above code checks the returned ds_map in the Social Asynchronous Event and if its "id" matches the constant being checked, it then checks that the id associated with the image is the same as that being requested and if it is, it sets another global array to hold the unique id for the image (which can be used to draw the image as a sprite).

Back: Achievements and Leaderboards
Next: achievement_load_friends

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_increment

Increment an achievement by a given value (Google Play only).

Syntax:

achievement_increment(ach_name, value)

Argument | Description
name | The name of the achievement.
value | The value to be sent.

Returns: N/A

Description

Google Play permit Android games to have achievements with no completion value and you can use this function to increment those achievement by a given amount.

Example:

achievement_increment("ach_TotalScore", score);

The above code adds the current player score to the achievement "ach_TotalScore".

Back: Achievements and Leaderboards
Next: achievement_show_achievements

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_load_friends

Get information about the users friends.

Syntax:

achievement_load_friends()

Returns: N/A

Description

This function will send a request to the server for information on all the logged in users friends and will trigger a callback Social Asynchronous Event which contains the async_load map populated with the relevant key/value pairs. The id key of this ds_map is used to identify the correct callback (there can be more than one trigger function for any given asynchronous event), and will be paired with the constant achievement_friends_info as well as a number of other key/value pairs for each friend. The exact contents of the map are shown below:

  1. "id" - For this function it should be achievement_friends_info

  2. "FriendN" - The name of the friend, where "N" is an integer value corresponding to their position within the friends list.

  3. "FriendidN" - The unique user id of the friend, "N".

NOTE: This function is for iOS only.

Extended Example:

The following code would probably be called after the player has logged into their game account using achievement_login to get a list of all that users friends:

achievement_friends_info();

This will send off a request for the information on the users friends and generate an asynchronous callback with the special async_load ds_map containing the following data:

var ident = ds_map_find_value(async_load, "id");
if ident == achievement_friends_info
{
var numfriends = ds_map_find_value(async_load, "numfriends");
global.numfriends = numfriends;
for(var i=0; i < numfriends; i++;)
{
global.friendname[i] = ds_map_find_value(async_load, "Friend" + string(i));
global.friendid[i] = ds_map_find_value(async_load, "Friendid" + string(i));
achievement_get_pic(global.friendid[i]);
}
}

The above code checks the returned ds_map in the Social Asynchronous Event and if its "id" matches the constant being checked, it then loops through the map storing all the different values in a number of arrays and requests an image for each of the entries in the map (see achievement_get_pic).

Back: Achievements and Leaderboards
Next: achievement_load_leaderboard

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_load_leaderboard

Get leaderboard data, either for all players or only friends.

Syntax:

achievement_load_leaderboard(ident, minindex, maxindex, filter)

Argument | Description
ident | The unique ID of the leaderboard as shown on the developer dashboard.
minindex | The starting index value to get the leaderboard data from.
maxindex | The maximum index value to get the leaderboard data from.
filter | Whether to filter the results to those that are on your friends list or to all players (see the Description below)

Returns: N/A

Description

This function will send a request to the server for information on the given leaderboard. The leaderboard must have been created previously on the developer dashboard for your game and the ID given is that which you must supply as the first argument of the function. It will trigger a callback Social Asynchronous Event which contains the async_load map populated with the relevant key/value pairs. The id key of this ds_map is used to identify the correct callback (there can be more than one trigger function for any given asynchronous event), and will be paired with the constant achievement_leaderboard_info as well as a number of other key/value pairs for each player. The exact contents of the map are shown below:

  1. "id" - For this function it should be achievement_leaderboard_info

  2. "leaderboardid" - The unique ID for the leaderboard as defined on the provider dashboard.

  3. "numentries" - The number of entries in the leaderboard that you have received.

  4. "PlayerN" - The name of the player, where "N" is an integer value corresponding to their position within the leaderboard entries list.

  5. "PlayeridN" - The unique user id of the player, "N".
  6. "RankN" - The rank of the player "N" within the leaderboard.

  7. "ScoreN" - The score of the player "N".

You can specify the exact portion of the leaderboard to show by giving a minimum and maximum index value, as well as request that the results be filtered to retrieve only those scores by your friends or those posted by all players using the following filter constants:

  • achievement_filter_friends_only - Get only the scores of the players friends.

  • achievement_filter_all_players - Get all scores for all players.

NOTE: this function does not work on the Android platform.

Extended Example:

The following code would probably be called after the player has logged into their game account using achievement_login to get a list of all friends leaderboard positions for the game, on either Android or iOS:

if os_type == os_android
{
achievement_load_leaderboard("CgkIs9_51u0PEAIQBw", 1, 100, achievement_filter_friends_only);
}
else
{
achievement_load_leaderboard("leaderboard1id", 1, 100, achievement_filter_friends_only);
}

This will send off a request for the information on the given leaderboard and generate an asynchronous callback with the special async_load ds_map containing the following data:

var ident = ds_map_find_value(async_load, "id");
if ident == achievement_leaderboard_info
{
var lbid = ds_map_find_value(async_load,"leaderboardid");
if lbid == "CgkIs9_51u0PEAIQBw" || lbid == "leaderboard1id"
{
global.numentries = ds_map_find_value(async_load,"numentries");
for(var i = 0; i < numentries; i++;)
{
global.playername[i] = ds_map_find_value(async_load, "Player" + string(i));
global.playerid[i] = ds_map_find_value(async_load, "Playerid" + string(i));
global.playerrank[i] = ds_map_find_value(async_load, "Rank" + string(i));
global.playerscore[i] = ds_map_find_value(async_load, "Score" + string(i));
achievement_get_pic(global.playerid[i]);
}
}
}

The above code checks the returned ds_map in the Social Asynchronous Event and if its "id" matches the constant being checked, it then checks to make sure that the leaderboard being sent matches the original function call before looping through the map and storing all the different values in a number of arrays. It also requests an image for each of the entries in the map (see achievement_get_pic).

Back: Achievements and Leaderboards
Next: achievement_load_progress

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_load_progress

Get achievement data from the service provider.

Syntax:

achievement_load_progress()

Returns: N/A

Description

This function will send a request to the server for information on all available achievements. It will trigger a callback Social Asynchronous Event which contains the async_load map populated with the relevant key/value pairs. The id key of this ds_map is used to identify the correct callback (there can be more than one trigger function for any given asynchronous event), and will be paired with the constant achievement_achievement_info as well as a number of other key/value pairs for each player. The exact contents of the map are shown below:

  1. "id" - For this function it should be achievement_achievement_info.

  2. "numentries" - The number of achievements in the list.

  3. "AchN" - The name of the achievement, where "N" is an integer value corresponding to its place in the entries list.

  4. "AchCompN" - How complete the achievement "N" is as a percentage value from 0 to 100 (a string).

NOTE: This function is for iOS only.

Extended Example:

The following code would request achievement progress when the user is on an iOS device:

if os_type == os_ios
{
achievement_load_progress();
}

This will send off a request for the information on achievements and generate an asynchronous callback with the special async_load ds_map containing the following data:

var ident = ds_map_find_value(async_load, "id");
if ident == achievement_achievement_info
{
var numentries = ds_map_find_value(async_load, "numentries");
for(var i = 0; i < numentries; i++;)
{
ach_id[i] = ds_map_find_value(async_load, "Ach" + string(i));
comp[i] = ds_map_find_value(async_load, "AchComp" + string(i));
}
}

The above code checks the returned ds_map in the Social Asynchronous Event and if its "id" matches the constant being checked, it then loops through the entries in the map for each of the achievements and stores their name and completion percentage.

Back: Achievements and Leaderboards
Next: achievement_send_challenge

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_login

Log the user into the leaderboards page for the chosen platform.

Syntax:

achievement_login()

Returns: N/A

Description

This function logs the user into appropriate leaderboard and achievement service. If the service is not available, the user is logged into a "pretend" game centre and all achievements and scores are stored on the device so that when the actual service is available, these details can be uploaded. The function will trigger a callback Social Asynchronous Event which contains the async_load map populated with the relevant key/value pairs. The id key of this ds_map is used to identify the correct callback (there can be more than one trigger function for any given asynchronous event), and will be paired with the constant achievement_our_info as well as a number of other key/value pairs for each challenge. The exact contents of the map are shown below:

  1. "id" - For this function it should be achievement_our_info

  2. "name" - The name of the user that is currently logged in.

  3. "playerid" - The unique player id for the user that is currently logged in.

Extended Example:

The following code would probably be called right at the startof your game, or from a special button object that you have placed in a room, and will request that the player logs into their Google Game Services or Apple Game center account:

achievement_login();

This will send off a request for the current player information and generate an asynchronous callback with the special async_load ds_map containing the following data:

var ident = ds_map_find_value(async_load, "id");
if ident == achievement_our_info
{
var name = ds_map_find_value(async_load, "name" );
var playerid = ds_map_find_value(async_load, "playerid" );
global.OurName = name;
global.OurId = playerid;
if os_type == os_android
{
achievement_load_leaderboard("CgkIs9_51u0PEAIQBw", 1, 100, achievement_filter_friends_only);
}
else
{
achievement_load_leaderboard("leaderboard1id", 1, 100, achievement_filter_friends_only);
}
achievement_get_challenges();
achievement_load_friends();
achievement_load_progress();
}

The above code checks the returned ds_map in the Social Asynchronous Event and if its "id" matches the constant being checked, it then loops through the map storing all the different values in variables before calling the rest of the functions to prepare the leaderboards, challenges and friends lists.

Back: Achievements and Leaderboards
Next: achievement_logout

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_login_status

Check to see if the user is already logged in.

Syntax:

achievement_login_status();

Returns: Boolean

Description

This function is currently only useful for Google Play on the Android platform. It will check to see if the user is already logged into Google services, in which case it will return true, or not, returning false. If it returns true there is no need to call the achievement_login function.

Example:

if !achievement_login_status()
{
achievement_login();
}

The above code will log you into the chosen leaderboard and achievement service.

Back: Achievements and Leaderboards
Next: achievement_login

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_logout

Log the user out of the leaderboards page for the chosen platform.

Syntax:

achievement_logout()

Returns: N/A

Description

This function logs the user out of the chosen leaderboard and achievement service. This will stop all further achievements and scores from being recorded.

Example:

achievement_logout();

The above code will log you out of the chosen leaderboard and achievement service.

Back: Achievements and Leaderboards
Next: achievement_available

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_post

Sends information about an achievement to the Game Center.

Syntax:

achievement_post(achievement, percent)

Argument | Description
achievement | The name of the achievement.
percent | The percentage of the achievement completed.

Returns: N/A

Description

You can use this function to send your achievements to the chosen leaderboard and achievement service. You send the name of the achievement (this is the name you assigned to it when you set up the account for your app) and the percentage that you have completed towards getting the achievement (0 - None, 100 - Completed).

Example:

if achievement_available() achievement_post("ach_Level1", 100);

The above code checks to see if the chosen leaderboard and achievement service is available and if so it posts an achievement.

Back: Achievements and Leaderboards
Next: achievement_post_score

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_post_score

Sends a score the Game Center leaderboard for your game.

Syntax:

achievement_post_score(name, score)

Argument | Description
name | The name of the score table (or "Leaderboard").
score | The score to be sent.

Returns: N/A

Description

You can use this function to send your score to the chosen leaderboard and achievement service. You send the name of the score table (the "leaderboard" name that you assigned to your game when you set up the account) and the actual score value).

Example:

if achievement_available() achievement_post_score("Leaderboard", 1000);

The above code checks to see if the chosen leaderboard and achievement service is available and if so it posts a score to the score table called "Leaderboard".

Back: Achievements and Leaderboards
Next: achievement_increment

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_reset

Reset all achievements to initial values.

Syntax:

achievement_reset()

Returns: N/A

Description

This function will reset all achievements back to their initial values for the game. This function is provided as a debug function and it is not recommended that you permit the end-user to do this in your games.

Example:

if debug_mode
{
if keyboard_check_pressed(vk_space) achievement_reset
}

The above code checks to see the game is in debug mode, and if it is pressing "space" will reset all the achievements.

Back: Achievements and Leaderboards
Next: achievement_login_status

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_send_challenge

Send a challenge across the network to a player.

Syntax:

achievement_send_challenge(playerid, challengeid, score, type, message)

Argument | Description
playerid | The unique ID of the player to challenge.
challengeid | The unique challenge ID (as found on the provider dashboard).
score | The score to beat.
type | the type of challenge to be issued - one of two constants given below.
message | The message to attach to the challenge.

Returns: N/A

Description

This function will send a challenge across the network to the chosen player. You can get the playerid using the achievement_load_friends or the achievement_load_leaderboard functions and you must also supply the challengeid which is the unique value given the challenge when you created it on your iTunes Connect or Google Play dashboard. You must also supply a score, and a short text message as well as set the challenge type. This can be one of the following constants:

  • achievement_type_score_challenge - A challenge based on the score value.
  • achievement_type_achievement_challenge - A challenge based on an achievement.

This function will trigger a callback Social Asynchronous Event for the player that is to receive the challenge, and in this event you will have a ds_map referenced in the variable async_load. The id key of this ds_map is used to identify the correct callback (there can be more than one trigger function for any given asynchronous event), and will be paired with the constant achievement_challenge_received as well as a number of other key/value pairs for each player. The exact contents of the map are shown below:

NOTE: that the user can also receive toast notifications for challenges received, but this will depend on the values you have chosen using the function achievement_show_challenge_notifications.

  1. "id" - For this function it should be achievement_leaderboard_info

  2. "playerid" - The player ID for the challenge.

  3. "issuerid" - The issuer ID for the challenge.

  4. "state" - The state of the challenge, which will have a value of 0 - 3 (as a string) for invalid, pending, completed or declined.

  5. "message" - The text message for challenge.

  6. "completeddate" - The completion date for challenge.

  7. "issueddate" - The issue date for challenge.

  8. "type" - The type of challenge given. Can be one of two constants:
    • achievement_type_score_challenge - A challenge based on the score value.
    • achievement_type_achievement_challenge - A challenge based on an achievement.
  9. "identifier" - The identifying string for the challenge, as set on the provider dashboard

  10. "score" - The score tied in with the challenge (if applicable).

Extended Example:

To send a challenge over the network you would have this code:

achievement_send_challenge(global.playerid[0], global.challengeid[0], score, achievement_type_score_challenge, "Beat that sucker!");

This request will then trigger the Social Event in your game for the player that the challenge was directed at, and this can be dealt with in the following way:

var ident = ds_map_find_value(async_load, "id");
if ident == achievement_challenge_received
{
player_id = ds_map_find_value(async_load, "playerid");
issuer_id = ds_map_find_value(async_load, "issuerid");
state = ds_map_find_value(async_load, "state");
message = ds_map_find_value(async_load, "message");
date_completed = ds_map_find_value(async_load, "completeddate");
date_issued = ds_map_find_value(async_load, "issueddate");
ach_type = ds_map_find_value(async_load, "type");
ach_ident = ds_map_find_value(async_load, "identifier");
ach_score = ds_map_find_value(async_load, "score");
}

The above code checks the returned ds_map in the Social Asynchronous Event and if its "id" matches the constant being checked, it then extracts the relevant values for each of the keys in the map and stores them in variables for future use.

Back: Achievements and Leaderboards
Next: achievement_reset

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_show_achievements

Shows the achievements page for the chosen platform.

Syntax:

achievement_show_achievements()

Returns: N/A

Description

This function will open the achievements page for the chosen platform. Please note that this is an asynchronous function, ie: your game will continue to run in the background while the achievements page is being shown. As such, you should be careful where you use this and make sure to pause the game or only permit it to be shown in areas of your game where it will not interfere with the game-play.

Example:

if achievement_available()
{
global.Pause = true;
instance_create(0, 0, obj_Pause);
achievement_show_achievements();
}

The above code checks to see if the chosen leaderboard and achievement service is available and if so it sets a global variable and creates a controller "pause" instance before calling the function to show the achievements on screen.

Back: Achievements and Leaderboards
Next: achievement_show_leaderboards

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_show_challenge_notifications

Show or suppress challenge notifications

Syntax:

achievement_show_challenge_notifications(receive, local, remote)

Argument | Description
receive | Show challenges received pop-up (true) or not (false).
local | Show completed local challenges pop-up (true) or not (false).
remote | Show completed remote challenges pop-up (true) or not (false).

Returns: N/A

Description

With this function you can show, or suppress, the various different "toast" pop-up notifications relating to challenges. When the arguments are set to true these messages will appear, informing the player of any local or remote challenges received as well as those challenges that have been completed, while setting them to false will suppress these notifications.

Example:

achievement_show_challenge_notifications(true, false, false);

The above code will set challenge toast notifications to be shown for received challenges only.

Back: Achievements and Leaderboards
Next: achievement_get_challenges

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


achievement_show_leaderboards

Shows the leaderboards page for the chosen platform.

Syntax:

achievement_show_leaderboards()

Returns: N/A

Description

This function will open the leaderboards page for the chosen platform. Please note that this is an asynchronous function, ie: your game will continue to run in the background while the leaderboards page is being shown. As such, you should be careful where you use this and make sure to pause the game or only permit it to be shown in areas of your game where it will not interfere with the game-play.

Example:

if achievement_available()
{
global.Pause = true;
instance_create(0, 0, obj_Pause);
achievement_show_leaderboards();
}

The above code checks to see if the chosen leaderboard and achievement service is available and if so it sets a global variable and creates a controller "pause" instance before calling the function to show the leaderboards on screen.

Back: Achievements and Leaderboards
Next: achievement_show_challenge_notifications


Local High Scores

This section deals with some special functions for creating a local high score table.

To help you create and maintain highscores for your games, GameMaker: Studio creates a global high score array of 10 places which you can access, add to and change to create your own custom high score lists without too much fuss. This functionality is local to the game and works on all platforms, so you can easily store and maintain a basic high score table using these functions along with the File Handling Functions.

The following functions exist that deal with the internal high score list.

  1. highscore_add
  2. highscore_name
  3. highscore_value
  4. highscore_clear

GameMaker: Studio also includes a function for drawing the highscores out on the screen as a list, however it is very basic and it is recommended that you use this for debugging more than anything else as making your own high score table is easy and will give you far more control over how it is displayed:

  1. draw_highscore

Back: Achievements and Leaderboards

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


highscore_add

Adds a name and score to the internal high score list.

Syntax:

highscore_add(str, numb);

Argument | Description
str | The string (name) to attribute the score to
numb | The number (score) to add.

Returns: N/A

Description

With this function you can add a name and a score to the internal global high score list. There is no need to check the value to see if it is high enough to enter into the score list as GameMaker: Studio will only store those values that are greater than the tenth position stored.

Example:

if lives = 0
{
highscore_add(global.Name, score);
score = 0;
room_goto(rm_MainMenu);
}

The above code will check the lives and if they are set to 0, it will add the current score and the string held in the global variable "Name" into the high score list, before finally setting the score to 0 and sending the player to the room indexed in "rm_MainMenu".

Back: High Scores
Next: highscore_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


highscore_clear

Clears the highscore list.

Syntax:

highscore_clear();

Returns: N/A

Description

With this function you can clear the internal global high score list, resetting all names to the default value of "Unknown" and all scores to the default value of 0.

Example:

highscore_clear();

This would clear the high score list.

Back: High Scores
Next: highscore_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


highscore_name

Returns the name string stored at the given place in the highscore table.

Syntax:

highscore_name(place);

Argument | Description
place | The place on the table (1-10).

Returns: String

Description

With this function you can retrieve the name string that has been stored in the high score list at the given position. If no name has been entered, the string "Unknown" will be returned.

Example:

var i;
i = 10;
repeat(10)
{
name[i] = highscore_name(i);
i -= 1;
}

The above code will loop through the high score list and store all the names in an array.

Back: High Scores
Next: highscore_value

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


highscore_value

Returns the score value stored at the given place in the highscore table.

Syntax:

highscore_value(place);

Argument | Description
place | The place on the table (1-10).

Returns: N/A

Description

With this function you can retrieve the score value that has been stored in the high score list at the given position. If no score has been entered, the function will return 0.

Example:

var i;
i = 10;
repeat(10)
{
scr[i] = highscore_value(i);
i -= 1;
}

The above code will loop through the high score list and store all the scores in an array.

Back: High Scores
Next: highscore_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Facebook

This section explains all the Facebook API functions.

Facebook is one of the most important social media on the internet and many games and developers currently have their own pages for posting games and media. GameMaker: Studio has a number of built in functions that permit you to connect with Facebook and get user information as well as post images and text to walls and a number of other things. It is recommended that you visit the Facebook Developers page before starting to use these functions as a firm understanding of how the Facebook Graph works and the available calls and permissions is essential for you to get the most from these functions.

The current graph API supported is Graph API v2.0 on all platforms.

NOTE: If your test device has the Facebook App installed, these functions will only work when creating an executable, as just testing the game (using the green or orange "play" buttons) will not work correctly. Basically, the test runner and the FaceBook App communicate with one another so the mechanism for communication has to be correctly setup, and you only get it correctly setup via the Create Application button.

Android Apps

When you set up your Facebook page to accept an Android app, you need to give the Android package name (reverse URL format and should conform to your game bundle ID), and you can set the class name to be <package_name>.RunnerActivity. GameMaker: Studio also supports Single Sign-On for Android apps, so you can enable this to allow the game to be launched from the Android Facebook app notifications. There is no need to activate Deep Linking as it is not supported by GameMaker.

There is also a section where you are required to enter the Android Keystore Hash that is unique to the keystore that you are using for your game. As this can be quite difficult to get, GameMaker: Studio can generate it for you from the Android Preferences, and you can then simply copy and paste it into the required part of the Facebook setup page.

The image below shows how your final Facebook Android section should look:

iOS Apps

The basic setup for iOS apps with the Facebook functions is the same as for Android, however there are a few key things that need to be correctly set up on the actual Facebook Developers page for your app:

  • Bundle ID: Must match with the bundle ID of your game (usually of the form "com.{yourcompany}.{yourgame}").
  • iPhone App Store ID: This is the Apple ID associated with your game as found on iTunes Connect for the iPhone game.
  • iPad App Store ID: As above except for iPad.
  • Facebook Login: GameMaker: Studio supports Single Sign-On for iOS apps, so you can enable this to allow the game to be launched from the iOS Facebook app.
  • Deep Linking: This is not supported, so keep disabled.
  • URL Scheme Suffix: This is not supported, so leave blank.

Also note that the iOS Facebook SDK version is 3.16.1 which means that the minimum iOS target is version v5.0 and above.

HTML5 Apps

The HTML5 target works almost exactly the same as all previous target modules, however you cannot test the functions locally, meaning that you will have to compile and upload to your server to test. There is also one additional function that has been added to create offerwall compatibility for HTML5 games that is not available for other platforms:

  1. facebook_launch_offerwall

The functions listed below are for integrating your game with Facebook:

  1. facebook_init
  2. facebook_login
  3. facebook_request_publish_permissions
  4. facebook_request_read_permissions
  5. facebook_check_permission
  6. facebook_status
  7. facebook_accesstoken
  8. facebook_user_id
  9. facebook_graph_request
  10. facebook_dialog
  11. facebook_send_invite
  12. facebook_post_message
  13. facebook_logout

NOTE: You must have activated the Facebook API in the Global Game Settings for the target platform and called the facebook_init() function before any of these functions can be used correctly.

Troubleshooting

There are a few things to note when working with Facebook, and these are listed below:

  • The login function is only called once on a publish action through GameMaker: Studio, so if you login once and try to retest the button, there is no visible result.

  • If you have the Facebook app installed on your android device, the login function is not visibly called at all called from a compiled app. Your app automatically logs in to the same Facebook account that you have tied to your Facebook app.

  • If you intend to permit your game to publish in anyway using the Facebook functions, you need to request permission from Facebook themselves. To facilitate this, you should create at least one test user account that you've already tested as working so that Facebook can use it thus make getting permission simpler.

  • When requesting permission from Facebook for your app, it's a good idea to inform Facebook that your app will do this (in the permission request notes) so that they are aware of what to look for. Also, include screenshots of your command console showing a successful login, the login screen on your device and the successful wall post on your Facebook test account.

  • If you are using a test user, including screenshots from the test user's wall post and have Facebook test use the same test user.

  • All text you want posted will have to be in the bottom banner of your post. Any text that is pre-filled (even if it editable by the user) is not allowed. This means your wall posts will need to be dialog posts that allow the user to write what they want.

  • You will need your package name and class name to get your permissions approved through Facebook. Your package name is listed in your game settings, and the class name is your package name + ".RunnerActivity", for example: "com.macsweeneygames.catchthehaggis.RunnerActivity")

  • if your game has been set to "sandboxed" mode from the Facebook dashboard, all users that wish to play your game must have been added to the list of test users on Facebook.

Back: Social Gaming

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_accesstoken

This function returns the access token from Facebook.

Syntax:

facebook_accesstoken()

Returns: String

Description

An access token is a random string that provides temporary, secure access to the Facebook APIs, and this function will return the access token that Facebook gives you when you log in to verify that it's a valid log in.

Example:

token = facebook_accesstoken();

The above code gets the access token that Facebook generates for the user and stores it as a string in the variable "token".

Back: Facebook
Next: facebook_user_id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_check_permission

Check to see if the user has specific publishing or read actions from the Facebook API.

Syntax:

facebook_check_permission(permission)

Argument | Description
permission | The permission you want to check (a string).

Returns: Real

Description

With this function you can check the Facebook API to see if the user has granted a specific permission, either read or publish. The function will return true if they have the permission or false if they do not or there is an error. Note that the user must be logged in for the check to function.

Example:

var permissions = ds_list_create();
if !facebook_check_permission("user_likes")
{
ds_list_add(permissions, "user_likes");
}
if !facebook_check_permission("user_interests")
{
ds_list_add(permissions, "user_interests");
}
if !ds_list_empty(permissions))
{
request_ID = facebook_request_read_permissions(permissions);
}
ds_list_destroy(permissions);

The above code checks some of the Facebook read permissions, and if the game has not requested them, a request is sent.

Back: Facebook
Next: facebook_status

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_dialog

With this function you can open a Facebook dialog for the user to interact with.

Syntax:

facebook_dialog(graph_path, ds_map_parameters, ds_map_return)

Argument | Description
graph_path | The part of the social graph to interact with
ds_map_parameters | The ds_map with the information to send.
ds_map_return | The ds_map to receive (-1 for none).

Returns: N/A

Description

A Facebook dialog is the way in which Facebook asks the user to give comments and information and they not need any additional permissions because they require user interaction. For example, it can be used to send friend request or to post a comment to a wall. The "graph_path" argument is where you define the part of the graph you wish to access, and the exact path can be defined using the terms outlined in the Facebook Dialogues Overview.

The next argument is slightly more complex as it requires you to have created and filled a ds_map with the correct information which GameMaker: Studio will then convert into json automatically when sent to the Facebook Api. The information that you put in this map will depend very much on which path you choose to use and a complete list of all possible values can be found here. An example of how this map is structured can be seen in the code example supplied below.

Finally, we have an argument for storing any information that Facebook has sent back from the graph request. This information comes in the form of json which GameMaker: Studio converts into a ds_map. For this to work correctly, you must have created a ds_map previously, and if that map has been used elsewhere and already contains some key/value pairs it will be cleared by this function before the Facebook data is added. It is very important that you read the Facebook documentation on possible return values so that you know exactly what to expect. Thankfully Facebook have a Graph Api Test Page where you can check different graph paths and see exactly what information they will return.

NOTE: The user does not need to be logged in to use this function as the log in dialogue will be shown as part of the dialogue request.

Example:

var interactiveMap;
interactiveMap = ds_map_create();
ds_map_add(interactiveMap, "picture", "http://MacSweeneygames.com/Clown.jpg");
ds_map_add(interactiveMap, "link", "http://MacSweeneygames.com/");
ds_map_add(interactiveMap, "name", "Catch The Clown");
ds_map_add(interactiveMap, "caption", "MacSweeneygames.com");
ds_map_add(interactiveMap, "description", "Play Catch the clown now on MacSweeney Games!");
facebook_dialog("feed", interactiveMap, -1);
ds_map_destroy(interactiveMap);

The above code will create a ds_map and store its index in the local variable "interactiveMap". This map is then filled with the necessary key/value pairs to generate an interactive wall post. Next the facebook_dialog will open a window asking the user to add a message to be sent along with the rest of the information and this will all be published to the users wall. Finally the ds_map is deleted to free memory.

Back: Facebook
Next: facebook_send_invite

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_graph_request

This function is used to interact with the Facebook social graph.

Syntax:

facebook_graph_request(graph_path, httpMethod, ds_map_parameters, ds_map_return)

Argument | Description
graph_path | The part of the social graph to interact with
httpMethod | The http method to use (POST, GET, DELETE).
ds_map_parameters | The ds_map with the information to send.
ds_map_return | The ds_map to receive (-1 for none).

Returns: N/A

Description

With this function you can get the user to interact with the Facebook Social Graph. The "graph_path" argument is where you define the part of the graph you wish to access, like the current user friends list, or another apps comments or even an event. The exact path can be defined using the terms outlined in the Publishing section of the Facebook Graph Api pages. You then define the http method to use which is usually POST or GET but Facebook also accepts the DELETE method.

The next argument is slightly more complex as it requires you to have created and filled a ds_map with the correct information which GameMaker: Studio will then convert into json automatically when sent to the Facebook Api. The information that you put in this map will depend very much on which path you choose to use and a complete list of all possible values can be found here. An example of how this map is structured can be seen in the code example supplied below.

Finally, we have an argument for storing any information that Facebook has sent back from the graph request. This information comes in the form of json which GameMaker: Studio converts into a ds_map. For this to work correctly, you must have created a ds_map previously, and if that map has been used elsewhere and already contains some key/value pairs it will be cleared by this function before the Facebook data is added. It is very important that you read the Facebook documentation on possible return values so that you know exactly what to expect. Thankfully Facebook have a Graph Api Test Page where you can check different graph paths and see exactly what information they will return.

NOTE: The user must be logged in for the graph request to function.

Example:

var wallPostMap;
wallPostMap = ds_map_create();
ds_map_add(wallPostMap, "message", "I just got a hi-score playing Catch The Clown!");
ds_map_add(wallPostMap, "picture", "http://MacSweeneygames.com/Clown.jpg");
ds_map_add(wallPostMap, "link", "http://MacSweeneygames.com/");
ds_map_add(wallPostMap, "name", "Catch The Clown");
ds_map_add(wallPostMap, "caption", "MacSweeneygames.com");
ds_map_add(wallPostMap, "description", "Play Catch the clown now on MacSweeney Games!");
facebook_graph_request("me/feed", "POST", wallPostMap, -1);
ds_map_destroy(wallPostMap);

The above code will create a ds_map and store its index in the local variable "wallPostMap". It then fills the ds_map with the relevant key/value pairs that are needed to post an image and text to the currently logged in users wall. Finally it sends the graph request and deletes the ds_map from memory.

Back: Facebook
Next: facebook_dialog

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_init

This code initialises Facebook.

Syntax:

facebook_init(appKey)

Returns: N/A

Description

Before using any of the Facebook functions you must call this function to initialize the Facebook API and tell GameMaker: Studio that you are going to be using the Facebook specific functions. This should be done only once in the game and can be done at any time, but it is recommended that you call this function right at the start before anything else. Note too, that even if you use facebook_logout at some point in your game you will not need to use this function again to log in.

Example:

facebook_init();
var permissions = ds_list_create();
ds_list_add(permissions,"public_profile", "user_friends");
facebook_login(permissions);
ds_list_destroy(permissions);

The above code initialises Facebook, then creates a ds_list to hold the specific permissions that you wish to request, and finally logs in using these permissions.

Back: Facebook
Next: facebook_login

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_launch_offerwall

This function returns the status of the facebook connection.

Syntax:

facebook_launch_offerwall(url)

Argument | Description
url | The URL of your facebook currency definition.

Returns: String

Description

This implementation enables your app to open a Facebook dialog containing an interactive list of advertiser offers. For further information see FaceBook Developers - Offers With Payments.

NOTE: this function will only work with the HTML5 target module.

Example:

if mouse_check_button_pressed(mb_left)
{
facebook_launch_offerwall("http://facebook.com/game/payments");
}

The above code checks for a mouse press and if one is detected it takes the user to the FaceBook offerwall page.

Back: Facebook
Next: facebook_init

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_login

Logs the user into their Facebook account.

Syntax:

facebook_login(permissions, ios_login_type)

Argument | Description
permissions | The permissions you want to have from the user logging in.
ios_login_type | The iOS only log in type (see the list of constants below).

Returns: N/A

Description

With this function GameMaker: Studio will connect to Facebook and ask the user to log into their account. You may also supply additional permission requests in the form of a ds_list that this function then converts into a json array to communicate them to Facebook. There are a wide variety of permissions you may request and they are documented on the Facebook developers pages found here. If you do not wish to ask for any special or extended permissions then you will still need to send a ds_list, but this time it will be empty.

This function is also considered as being asynchronous as while the Facebook login window is open on the screen, the game will continue to run in the background and even once the user has completed the login process, none of the other Facebook functions will work until the facebook_status() returns "AUTHORISED" . Due to the need for an internet connection and the different rates of data transfer, this means that it could be several seconds before this authorisation is received, and all the while the game will still be running.

NOTE: You can now only in read permissions to this function. If you require write permissions, you need to call facebook_request_publish_permissions() after logging in. Also note that if your game requests for more than than the public_profile, email and user_friends it will require review by Facebook before it can be used by people other than the game's developers.

There is an extra parameter required for iOS login (other platforms can simply use fb_login_default for the argument). This should be one of the constants listed below:

Constant | Description
fb_login_default | Use the default iOS login behaviour (see here for further details).
fb_login_fallback_to_webview | Attempt Facebook login, asking user for credentials if necessary.
fb_login_no_fallback_to_webview | Attempt Facebook login, but no direct request for credentials will be made.
fb_login_forcing_webview | Only attempt WebView login, asking user for credentials
fb_login_use_system_account | Attempt Facebook login, preferring the system account and falling back to a fast app switch if necessary.
fb_login_forcing_safari | Attempt only to login with Safari.

The above listed constants change the login behaviour on iOS, permitting you to select which fallback methods to use (if any) should login fail from through the normal process. For further information please see this Facebook Developer page.

Example:

facebook_init();
var permissions = ds_list_create();
ds_list_add(permissions,"public_profile", "user_friends");
facebook_login(permissions, fb_login_default);
ds_list_destroy(permissions);

The above code will initialize Facebook and then log the current user in, asking for the extended read permissions given.

Back: Facebook
Next: facebook_request_publish_permissions


facebook_logout

This function logs the user out of Facebook.

Syntax:

facebook_logout()

Returns: N/A

Description

With this function you can log the user out of Facebook. Note, this does not mean that Facebook is disconnected from the game and there is no need to call facebook_init again if you wish the user to log back in again. It is also worth noting that certain graph and dialogue functions may work, only that they will prompt the user to log in again beforehand.

Example:

facebook_logout();

The above code simply logs the current user out of Facebook.

Back: Facebook
Next: facebook_launch_offerwall

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_post_message

Posts a message to the player's Facebook feed.

Syntax:

facebook_post_message(title, caption, message, picture_url, redirect_url, actionname, action_url)

Argument | Description
title | The "name" of the link.
caption | The caption of the link (appears beneath the link name).
message | The message to include with the post.
picture_url | A link to the picture included with this post.
redirect_url | The link attached to this post.
actionname | An action to be applied for this post.
action_url | The link to use for the above action.

Returns: N/A

Description

This function will posts a message direct to the user feed (ie, a “/me/feed” post to the facebook graph API ) . You give the name and the caption as well as a message and image to include, then the url to link to. The last two arguments, "actionname" and "actionurl" are optional and can either be left as empty strings ("") or they can be set to one of the permitted Facebook actions, like commenting or liking, in which case you should also supply an appropriate URL (for more information see Facebook Developers Api Post).

NOTE: There is no Facebook dialogue displayed for this function as the post is sent “silently” without user interaction. For this reason, you must have requested the correct permissions on login ("publish_actions").
NOTE: The user must be logged in for the message post to function.

Example:

if mouse_check_button_pressed(mb_left)
{
facebook_post_message("Catch The Haggis", "MacSweeneygames.com", "I just got a hi-score playing Catch The Haggis!", "http://MacSweeneygames.com/Clown.jpg", "http://MacSweeneygames.com/CatchTheHaggis.html", "", "");
}

The above code will silently post a message to the users wall feed.

Back: Facebook
Next: facebook_logout

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_request_publish_permissions

Request specific publishing actions from the Facebook API.

Syntax:

facebook_request_publish_permissions(permissions)

Argument | Description
permissions | The permissions you want to have from the user.

Returns: Real

Description

With this function you can request additional publishing permissions for Facebook. These permissions are added (as strings) to a previously created ds_list which is then used in the function to send the request. The user must be successfully logged in (ie. they have called facebook_login) and the facebook_status should be "AUTHORISED" before you call this function. the functon returns a unique ID value for the request call or -1 if the request was not sent (for example, the user is not logged in).

This function will trigger an Asynchronous Social Event, which contains the ds_map async_load. This ds_map will be populated with various key/value pairs to report the success or failure of the request.

Example:

var request = "publish_actions";
if !facebook_check_permission(request)
{
var permissions = ds_list_create();
ds_list_add(permissions, request);
request_ID = facebook_request_publish_permissions(permissions);
ds_list_destroy(permissions);
}

The above code checks the current Facebook permissions, and if the game has not requested the "publish_actions" permission, then a request is sent.

Back: Facebook
Next: facebook_request_read_permissions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_request_read_permissions

Request specific read actions from the Facebook API.

Syntax:

facebook_request_read_permissions(permissions)

Argument | Description
permissions | The permissions you want to have from the user.

Returns: Real

Description

With this function you can request additional read permissions for Facebook. These permissions are added (as strings) to a previously created ds_list which is then used in the function to send the request. The user must be successfully logged in (ie. they have called facebook_login) and the facebook_status should be "AUTHORISED" before you call this function. the functon returns a unique ID value for the request call or -1 if the request was not sent (for example, the user is not logged in).

This function will trigger an Asynchronous Social Event, which contains the ds_map async_load. This ds_map will be populated with various key/value pairs to report the success or failure of the request.

Example:

var permissions = ds_list_create();
if !facebook_check_permission("user_likes")
{
ds_list_add(permissions, "user_likes");
}
if !facebook_check_permission("user_interests")
{
ds_list_add(permissions, "user_interests");
}
if !ds_list_empty(permissions))
{
request_ID = facebook_request_read_permissions(permissions);
}
ds_list_destroy(permissions);

The above code checks som eof the Facebook read permissions, and if the game has not requested them, a request is sent.

Back: Facebook
Next: facebook_check_permission

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_send_invite

Send an invite message to friends.

Syntax:

facebook_send_invite(titlestring, msg, picture_url, redirect_url, ds_map_response);

Argument | Description
titlestring | The title of the dialog (a string)
msg | The message which appears in the dialog (a string).
picture_url | the url of the image to include in the dialog.
redirect_url | The “SiteURL” of your app on the Facebook Developers app settings page.
ds_map_response | A pre-created ds_map that is used to store the response details.

Returns: N/A

Description

With this function you can get your game to display a facebook “apprequests” dialog, which will allow your player to select friends from a list and send them a game invite message. The function requires that you supply a previously created ds_map which will then be populated with the relevant user details. This map should be polled every step after calling this function as the response could come through at any time, and when it does the map will should have a key "to" which will return a ds_list containing all the Facebook user IDs of those people invited (se extended example below for further details).

NOTE: The "SiteURL" is ignored on the iOS and Android modules and is only required on the HTML5 module if you are not hosting the application on the "SiteURL" (ie: you are testing locally).
NOTE: The user does not need to be logged in to use this function as the log in dialogue will be shown as part of the invite request.

Extended Example:

You can send a friends invite in the following way:

if mouse_check_button_pressed(mb_left)
{
map = ds_map_create();
facebook_send_invite("Catch The Haggis!", "Come and play Catch The Haggis with me...", "http://MacSweeneygames.com/Clown.jpg", "", map);
}

The above code will display an "apprequest" dialogue where you can select friends to invite to play the game, and it also creates a ds_map to hold the Facebook IDs of the users that are invited. This then needs to be polled in the Step event of an instance to receive the results, like this:

if ds_map_exists(map, "to")
{
var list = ds_map_find_value(map, "to");
var size = ds_list_size(list);
for(var i = 0; i < size; i++;)
{
fb_uid[i] = ds_list_find_value(list, i);
}
ds_map_clear(map);
}

This code checks the ds_map for the key "to" and when it's added, it then accesses the ds-list that "to" contains and loops through it, setting the "fb_uid" array to hold the user IDs that have been returned.

Back: Facebook
Next: facebook_post_message

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_status

This function returns the status of the facebook connection.

Syntax:

facebook_status()

Returns: String

Description

With this function you can poll Facebook for the current status of the connection. One of the following strings is returned (note that they are always returned in capital letters):

  • AUTHORISED: This means that the user has logged in correctly, but not all permissions may have been granted.
  • PROCESSING: This is returned when the login process is currently un-resolved.
  • IDLE: This is returned when the connection has been initialised but no further action has been taken.
  • FAILED: This means that the user has not logged in correctly, usually due to a connection error.

Example:

switch (facebook_status())
{
case "AUTHORISED": global.Auth = true; instance_destroy(); break;
case "FAILED": facebook_login(permissions); alarm[0] = 30; break;
default: alarm[0] = 30;
}

The above code would be run in an alarm and checks the status of Facebook to see if the user has logged in correctly. If the return string is "AUTHORISED", a global variable is set to true and the game continues, if the return string is "FAILED" the game will request that the user logs in again and then repeat the alarm to check the status once more.

Back: Facebook
Next: facebook_accesstoken

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


facebook_user_id

This function returns the unique Facebook user id.

Syntax:

facebook_user_id()

Returns: String

Description

With this function you can poll Facebook for the user id of the currently logged in user. This will be returned as a string, with a format similar to "07778915123" which can then be used with the other Facebook functions.

NOTE: The user must be logged in to get the ID.

Example:

fb_id = facebook_user_id();

The above code gets the user ID of the currently logged in user and stores it as a string in the variable "fb_id".

Back: Facebook
Next: facebook_graph_request

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Steam API

This section shows the functions associated with the Steam API.

This section is for those users that have been given access to the Steam API for publishing your game to that platform. To be able to use these functions you must have been accepted onto Steam previously, either through a publisher or through the Greenlight system, and have set up the Steam Preferences and the Steam Global Game Settings correctly.

Checking Steam Client/Server

The following set of functions are all for checking the availability of certain aspects of the Steam client or server API, and as such return either true or false depending on factors like the server being busy or the user being logged on etc... This means that these functions should be used before any other function call to ensure that the client/server setup is correct and communicating with your game:

  1. steam_initialised
  2. steam_stats_ready
  3. steam_is_overlay_enabled
  4. steam_get_persona_name
  5. steam_get_user_persona_name
  6. steam_get_user_steam_id
  7. steam_is_user_logged_on

General API Functions

The following functions can be used to get the app (game) ID and the account ID for the current user, which can then be used in other functions relating to Steam and the Steam Workshop:

  1. steam_get_app_id
  2. steam_get_user_account_id
  3. steam_current_game_language
  4. steam_available_languages

The Steam Overlay

The Steam Overlay is the visual display that can be brought up to display the Steam interface to the user. This is normally done by the user themselves using a combination of keys, but you also have the possibility of doing it from within your game, so that you can map a button or an event to show the overlay, using the following functions:

  1. steam_activate_overlay
  2. steam_activate_overlay_browser
  3. steam_activate_overlay_store
  4. steam_activate_overlay_user
  5. steam_is_overlay_activated

Leaderboards

The Steam API supports persistent leaderboards with automatically ordered entries. These leaderboards can be used to display global and friend leaderboards in your game and on the community web page for your game. Each game can have up to 10,000 leaderboards, and each leaderboard can be retrieved immediately after a player's score has been inserted into it, but note that for each leaderboard, a player can have only one entry, although there is no limit on the number of players per leaderboard.

Each leaderboard entry contains a name, a score and a rank for the leaderboard, and this data will be replaced when a new leaderboard entry is created for the user, and the following functions can be used to add and retrieve this data form the leaderboards for your game:

  1. steam_create_leaderboard
  2. steam_upload_score
  3. steam_upload_score_buffer
  4. steam_download_scores
  5. steam_download_scores_around_user
  6. steam_download_friends_scores

Achievements and Statistics

The Steam Stats and Achievements API provides an easy way for your game to provide persistent, roaming achievement and statistics tracking for your users. The user's data is associated with their Steam account, and each user's achievements and statistics can be formatted and displayed in their Steam Community Profile.

In addition to providing highly-valued rewards to players of your games, achievements are useful for encouraging and rewarding teamwork and player interaction, providing extra dimensionality to the game objectives, and rewarding users for spending more of their time in-game, and as such it is recommended that your game has a few. They are easily set up from the Steam Dashboard, but will require that you create special Icons for them.

Statistics track fine-grained pieces of information, such as play time, number of power-ups used, etc. You may choose to use them simply for tracking internal game data - so that, for instance, you can grant an achievement based on multi-session game-play statistics collected from the user across multiple computers. Or, you can track interesting game data for display on the user's Steam Community page, where users can compare their own stats against their friends.

Statistics come in three types, integers, floats and averages, and GameMaker: Studio permits you to modify each of these from your game, but they should have been initialised previously from the Steamworks control panel for your game.

NOTE: You must wait until steam_stats_ready has returned true, before attempting to read or write stats and achievements.

Further details and instructions on how to use statistics and achievements can be found in the following pages describing the functions:

  1. steam_set_achievement
  2. steam_get_achievement
  3. steam_clear_achievement
  4. steam_set_stat_int
  5. steam_set_stat_float
  6. steam_set_stat_avg_rate
  7. steam_get_stat_int
  8. steam_get_stat_float
  9. steam_get_stat_avg_rate
  10. steam_reset_all_stats
  11. steam_reset_all_stats_achievements

If the user in Offline Mode, Steam keeps a local cache of the stats and achievement data so that the APIs can be use as normal. Any stats unable to be committed are saved for the next time the user is online. In the event that there have been modifications on more than one machine, Steam will automatically merge achievements and choose the set of stats that has had more progress. Because Steam keeps a local cache of stats data it is not necessary for the game to also keep a local cache of the data on disk, especially as such caches often come in conflict and when they do it looks to a users as if their progress has been reverted, which is a frustrating experience.

Cloud Functions

The Steam Cloud provides an easy and transparent remote file storage system for your game. All files written to disk using the GameMaker: Studio cloud functions (listed below) will be replicated to the Steam servers after the game exits. If the user then changes computers, the files will then be downloaded to the new computer before the game launches, meaning that the game can then access the files by reading them using the appropriate Steam functions. The Steam Client does the work of ensuring that the files are kept synchronized across all computers the user may be accessing.

NOTE: By default, the Cloud is not enabled for a game on Steamworks. it must be enabled previously from the 'Cloud' tab of the Steamworks game admin, where you should set the byte and file quota. The next time you publish your games Steamworks configuration, the Cloud storage will be ready to use.

The following functions can be used to access the Steam Cloud from within GameMaker: Studio

  1. steam_is_cloud_enabled_for_app
  2. steam_is_cloud_enabled_for_account
  3. steam_get_quota_total
  4. steam_get_quota_free
  5. steam_file_exists
  6. steam_file_size
  7. steam_file_persisted
  8. steam_file_write
  9. steam_file_write_file
  10. steam_file_read
  11. steam_file_share
  12. steam_file_delete

User Generated Content

The Steam API integration in GameMaker: Studio permits the sharing of certain user-generated content. You can use them to share files to the Steam Workshop for your game, as well as post screen shots to the user profile.

  1. steam_is_screenshot_requested
  2. steam_send_screenshot

Apart from these basic screenshot functions, you also have available a great number if UGC functions for working with Workshop files and other user content features, which you can find listed in the following section of the manual:

  1. User Generated Content

Finally there is a legacy function, which is now deprecated and should not be used, but it is still supported for those games that used it originally (although you should change and update to the new UGC functions as soon as possible):

  1. steam_publish_workshop_file

DLC

Steam supports both free and paid downloadable content (DLC), and in the Steam client, a game with downloadable content appears as a single application in the user's game list with the downloadable content viewable through the games properties dialog. Once owned, downloadable content is treated as an integral part of the game and Steam will automatically update the content when a patch is available and installs the content when the user installs the game.

Since this is all handled by the Steam servers and the configuration of any DLC is done through the Steamworks control panel, there are only a few functions necessary in GameMaker: Studio to check for this extra content:

  1. steam_user_owns_dlc
  2. steam_user_installed_dlc

Back: Contents

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_activate_overlay

Activate the Steam user interface overlay for your game.

Syntax:

steam_activate_overlay(overlayindex);

Argument | Description
overlayindex | The page index of the Steam API UI to show (see constants listed below).

Returns: N/A

Description

The Steam overlay is a piece of the Steam user interface that can be activated over the top of almost any game launched through Steam. It lets the user access their friends list, web browser, chat, and in-game DLC purchasing. The default key for a user to access the overlay while in a game is SHIFT+TAB, but you can also bring up any page of the overlay using this function. It takes one of six constants that are listed below:

Constant | Description
ov_friends | The friends page for the current user
ov_community | The community page for your game
ov_players | The page showing others that are playing the same game or that you have recently played with
ov_settings | The Steam client overlay settings
ov_gamegroup | Opens the Steam Community web browser to the official game group for this game
ov_achievements | The achievements page for your game

Example:

var key = keyboard_lastkey;
switch (key)
{
case vk_f1: steam_activate_overlay(ov_friends); break;
case vk_f2: steam_activate_overlay(ov_community); break;
case vk_f3: steam_activate_overlay(ov_players); break;
case vk_f4: steam_activate_overlay(ov_settings); break;
case vk_f5: steam_activate_overlay(ov_gamegroup); break;
case vk_f6: steam_activate_overlay(ov_achievements); break;
}

The above code polls the last keyboard key pressed and if it is any of the function keys from 1 to 6 it will open the corresponding page of the Steam overlay.

Back: Steam API
Next: steam_activate_overlay_browser

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_activate_overlay_browser

Activate the Steam user interface overlay as a browser.

Syntax:

steam_activate_overlay(url);

Argument | Description
url | The (full) URL for the overlay to open.

Returns: N/A

Description

with this function you can open the Steam game overlay to its web browser and then have it load the specified URL. you need to use the full URL as a string for this to resolve correctly, for example: "http://www.steamgames.com/".

Example:

if keyboard_check_pressed(vk_f1)
{
steam_activate_overlay_browser("http://www.steamgames.com/");
}

The above code polls the keyboard for the F1 key and if it is then Steam overlay will be opened and resolve to the given URL.

Back: Steam API
Next: steam_activate_overlay_store

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_activate_overlay_store

Activate the Steam user interface overlay for your game to buy DLC.

Syntax:

steam_activate_overlay_store(app_id);

Argument | Description
app_id | The unique App ID for your game.

Returns: N/A

Description

With this function you can open the Steam overlay on the store page for a game so that users can buy or download DLC (for example). You need to supply the unique App ID for the game or DLC which you would get from the Steam dashboard when you set it up.

Example:

if keyboard_check_pressed(vk_f1)
{
steam_activate_overlay_store(global.DLC_id);
}

The above code polls the keyboard for the F1 key and if it is then Steam overlay will be opened on the page for the game content using the app ID stored in the global variable.

Back: Steam API
Next: steam_activate_overlay_user

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_activate_overlay_user

Activate the Steam user interface overlay with a specific user or group ID.

Syntax:

steam_activate_overlay_user(dialog_name, steamid);

Argument | Description
dialog_name | The dialogue to open the overlay on (see below).
steamid | The Steam user ID or group ID to use.

Returns: N/A

Description

This function will open the Steam overlay to one of the chosen dialogues relating to the user ID given. The possible dialogue strings available are:

  • "steamid" - opens the Steam Community web browser to the page of the user or group
  • "chat" - opens a chat window to the specified user

Example:

var key = keyboard_lastkey;
switch (key)
{
case vk_f1: steam_activate_overlay_user("steamid", global.GameGroupID); break;
case vk_f2: steam_activate_overlay_user("chat", global.FriendID); break;
}

The above code polls the last keyboard key pressed and if it is function key 1 or function key 2, it will open the Steam overlay to either see the Steam group stored in the global variable "GamegroupID", or it will open the chat window to chat with the user stored in the global "FriendID" variable.

Back: Steam API
Next: steam_is_overlay_activated

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_available_languages

Returns the available languages for Steam.

Syntax:

steam_available_languages();

Returns: String

Description

This function can be used to retrieve a list of all available languages for Steam. The returned value is simply a a comma separated list of languages.

Example:

language = steam_available_languages();

The above gets the available languages for Steam as a string and stores it in a variable.

Back: Steam API
Next: steam_activate_overlay

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_clear_achievement

Clear a given achievement so it can be awarded again.

Syntax:

steam_clear_achievement(ach_name);

Argument | Description
ach_name | The name of the achievement to clear (string).

Returns: N/A

Description

With this function you can tell the Steam API to clear (reset) a specific achievement. The achievement should have been previously defined on the Steamworks control panel accounts page for your game and the string that is passed to the function should match that used as the API Name on the control panel.

Example:

if mouse_check_button_pressed(mb_left)
{
steam_clear_achievement("Ach_Game_Win");
steam_clear_achievement("Ach_Died_10_Times");
steam_clear_achievement("Ach_Killed_100_Enemies");
steam_clear_achievement("Ach_Beat_Boss_Level_1");
}

The above code will reset the achievements of the game when the user clicks the left mouse button.

Back: Steam API
Next: steam_set_stat_int

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_create_leaderboard

Create a new leaderboard for your game.

Syntax:

steam_create_leaderboard(lb_name, sort_method, display_type);

Argument | Description
lb_name | The name of the leaderboard that you are creating (a string).
sort_method | The method for sorting the leaderboard entries (see constants listed below).
display_type | The way to display the leaderboard to the user (see constants listed below).

Returns: Real

Description

With this function you can create a new leaderboard for your game. The first argument is a string which defines the name of your leaderboard, and this name should be used in any further function calls relating to the leaderboard being created. You can then define the sort method (see the constants listed below) as well as the way in which the information is displayed (again, one of the constants listed below). The function will return a value of -1 if it fails to create the leaderboard or a value greater than -1 if it has succeeded.

NOTE: If you have previously created a leaderboard with the same name (either through code or through your Steam page for the game) this function will be ignored!

Sort Constant | Description
lb_sort_none | No sorting. The information will be displayed "as is".
lb_sort_ascending | Sort the leaderboard in ascending order.
lb_sort_descending | Sort the leaderboard in descending order.

Display Constant | Description
lb_disp_none | Show the leaderboard "as is".
lb_disp_numeric | Show the leaderboard as a numeric display.
lb_disp_time_sec | Show the leaderboard values as times, with the base value being seconds.
lb_disp_time_ms | Show the leaderboard values as times, with the base value being milli-seconds.

Example:

steam_create_leaderboard("Game Times", lb_sort_ascending, lb_disp_time_sec);

The above code will create a leaderboard called "Game Times", and set it to display the results in ascending order and with a display in seconds.

Back: Steam API
Next: steam_upload_score

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_current_game_language

Returns the language string for the game.

Syntax:

steam_current_game_language();

Returns: String

Description

This function is used retrieve the current language that Steam is using (as a string), for example "english".

Example:

language = steam_current_game_language();

The above code gets the language used for the current game.

Back: Steam API
Next: steam_available_languages

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_download_friends_scores

Download only those scores that have been posted by friends from the given leaderboard.

Syntax:

steam_download_friends_scores(lb_name);

Argument | Description
lb_name | The name of the leaderboard that you are downloading the scores from (a string).

Returns: Real

Description

With this function you can retrieve only the scores on the leaderboard that belong to those people that are marked as "friends" in the Steam client. So, if your leaderboard has 200 entries, and 50 of them are your friends, this function will retrieve only those 50 results. The leaderboard name is a string that was defined when you created the leaderboard using the function steam_create_leaderboard, and the function will return a value which can then be used to identify the call-back in the Steam Async Event, or it will return -1 if it has failed.

Example:

score_get = steam_download_friends_scores("Game Scores");

This will send off a request to the Steam Server for the users friends scores from the given leaderboard and will store the async id of the request in the variable "score_get". This will then be handled in the Steam Async Event, as shown in the Extended Example for steam_download_scores.

Back: Steam API
Next: steam_set_achievement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_download_scores

Download all, or part, of a leaderboard.

Syntax:

steam_download_scores(lb_name, start_idx, end_idx);

Argument | Description
lb_name | The name of the leaderboard that you are downloading the scores from (a string).
start_idx | The start position within the leaderboard.
end_idx | The end position within the leaderboard.

Returns: Real

Description

This function is used retrieve a sequential range of leaderboard entries by leaderboard ranking. The start_idx and end_idx parameters control the requested range of ranks, for example, you can display the top 10 on a leaderboard for your game by setting the start value to 1 and the end value to 10. The leaderboard name is a string that was defined when you created the leaderboard using the function steam_create_leaderboard, and the function will return a value which can then be used to identify the call-back in the Steam Async Event, or it will return -1 if it has failed.

Extended Example:

In this extended example we will request the top ten ranking for the given leaderboard and parse its results in the Steam Async Event. to start with we need to request the scores with the following code:

score_get = steam_download_scores("Game Scores", 1, 10);

This will send off a request to the Steam Server for the scores from the leaderboard "Game Scores", storing the async id of the request in the variable "score_get". this will then be handled in the Steam Async Event in the following way:

var async_id = ds_map_find_value(async_load, "id");
if async_id == score_get
{
var entries = ds_map_find_value(async_load, "entries");
var map = json_decode(entries);
if ds_map_exists(map, "default")
{
ds_map_destroy(map);
exit;
}
else
{
var list = ds_map_find_value(map, "entries");
var len = ds_list_size(list);
var entry;
for(var i = 0; i < len; i++;)
{
entry = ds_list_find_value(list, i );
steam_name[i] = ds_map_find_value(entry, "name");
steam_score[i] = ds_map_find_value(entry, "score");
steam_rank[i] = ds_map_find_value(entry, "rank");
ds_map_destroy(entry);
}
ds_list_destroy(list)
}
ds_map_destroy(map)
}

What we do here is first check the "id" key of the special async_load ds_map. If this value is the same as the value of the original call-back function (stored in the "score_get" variable) we then continue to process the data. The first thing we do is parse the async_load ds_map for the key "entries" which will contain a JSON object containing the leaderboard data. This JSON object is then decoded (see json_decode) as another ds_map, and this new map id is stored in the variable "map".

This map is checked for the key "default" and if that is found then the map is destroyed and the event is exited. If no "default" key is found, the code will then parse the map to extract the necessary information about the leaderboard, by first extracting a ds_list from the "entries" key of the ds_map, and then looping through each entry of the list to get another ds_map with the name, score and rank of each entry. These values are then stored to arrays and the map destroyed.

Once the loop has finished, the entries list is destroyed as is the map that it was taken from. There is no need to destroy the async_load ds_map as this is handled for you by GameMaker: Studio.

Back: Steam API
Next: steam_download_scores_around_user

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_download_scores_around_user

Download a range of scores from a leaderboard, centered around the user position.

Syntax:

steam_download_scores_around_user(lb_name, range_start, range_end);

Argument | Description
lb_name | The name of the leaderboard that you are downloading the scores from (a string).
range_start | The start position within the leaderboard.
range_end | The end position within the leaderboard.

Returns: Real

Description

This function is used to retrieve leaderboard entries relative the current users entry. The range_start parameter is the number of entries to retrieve before the current users entry, and the range_end parameter is the number of entries after the current user's entry, and the current user's entry is always included in the results. For example, if the current user is number 5 on a given leaderboard, then setting the start range to -2 and the end range to 2 will return 5 entries: 3 through 7. If there are not enough entries in the leaderboard before or after the user's entry, Steam will adjust the range to try to return the number of entries requested. For example, if the user is #1 on the leaderboard, start is set to -2, and end is set to 2, Steam will return the first 5 entries in the leaderboard.

Example:

score_get = steam_download_scores_around_user("Game Scores", -4, 5);

This will send off a request to the Steam Server for a range of 10 scores from the leaderboard "Game Scores", centered on the player and will store the async id of the request in the variable "score_get". This will then be handled in the Steam Async Event, as shown in the Extended Example for steam_download_scores.

Back: Steam API
Next: steam_download_friends_scores

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_file_delete

Remove a file from the Steam Cloud.

Syntax:

steam_file_delete(filename);

Argument | Description
filename | The name of the file delete.

Returns: Real

Description

This function will delete the given file from the Steam Cloud. The function will return a value of 0 if it fails for whatever reason and a value greater than 0 if it succeeds.

Example:

if steam_file_exists("Save.txt")
{
steam_file_delete("Save.txt");
}

The above code will check to see if a file exists, and if it does, it deletes the file from the Steam Cloud.

Back: Steam API
Next: steam_is_screenshot_requested

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_file_exists

Find out if the given file exists on the Steam Cloud.

Syntax:

steam_file_exists(filename);

Argument | Description
filename | The name of the file to check for.

Returns: Boolean

Description

With this function you can check to see if a file from the Steam Cloud exists or not, with a return value of true if it exists, or false otherwise.

Example:

if steam_file_exists("Save.txt")
{
save_str = steam_file_read("Save.txt");
}

The above code checks to see if a file exists on the Steam Cloud and if it does, it opens it and reads its contents into the variable "save_str".

Back: Steam API
Next: steam_file_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_file_persisted

Find out if the given file is synchronised with the Steam Cloud.

Syntax:

steam_file_persisted(filename);

Argument | Description
filename | The name of the file to check.

Returns: Boolean

Description

With this function you can check the given file to see if it has been synchronised with the Steam Cloud. A return value of true means that it is, while false means it is not.

Example:

if !steam_file_persisted("Save.txt")
{
steam_file_share("Save.txt");
}

The above code will check to see if a file has been stored to the Steam Cloud, and if it has not it will then synchronise it.

Back: Steam API
Next: steam_file_write

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_file_read

Reads the contents of a Steam Cloud file.

Syntax:

steam_file_read(filename);

Argument | Description
filename | The name of the file to read from.

Returns: String

Description

This function will read the contents of the given file into a string which can later be parsed in your game.

Example:

if steam_file_exists("Save.txt")
{
save_str = steam_file_read("Save.txt");
}

The above code checks to see if a file exists on the Steam Cloud and if it does, it opens it and reads its contents into the variable "save_str".

Back: Steam API
Next: steam_file_share

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_file_share

Force the Steam API to synchronise the given file with the Steam Cloud.

Syntax:

steam_file_share(filename);

Argument | Description
filename | The name of the file synchronise.

Returns: Real

Description

With this function you can force your game to synchronise the given file with the Steam Cloud. This is not normally necessary due to the fact that the game will synchronise automatically at the end of the player's session, nor is it recommended by Steam, but it can be useful to ensure sensitive information is synchronised immediately. The function will return a value of 0 if it fails for whatever reason and a value greater than 0 if it succeeds.

Example:

if !steam_file_persisted("Save.txt")
{
steam_file_share("Save.txt");
}

The above code will check to see if a file has been stored to the Steam Cloud, and if it has not it will then synchronise it.

Back: Steam API
Next: steam_file_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_file_size

Find the size of the given file from the Steam Cloud.

Syntax:

steam_file_size(filename);

Argument | Description
filename | The name of the file to check the size of.

Returns: Real

Description

With this function you can check the size of a file stored on the Steam Cloud. The returned real number is the size, in bytes, of the file.

Example:

file_bytes = steam_file_size("Save.txt");

The above code stores the size of a file from the Steam Cloud in the variable "file_bytes".

Back: Steam API
Next: steam_file_persisted

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_file_write

Write a data string to a file for storage on the Steam Cloud.

Syntax:

steam_file_write(filename, data, size);

Argument | Description
filename | The name of the file to write to.
data | The data to write (a string).
size | the size of the data to be written.

Returns: Real

Description

You can use this function to write data to a file, which will then be synchronised with the Steam Cloud when the user exits the game. if the file does not exist, this function will create it for you, and if it does already exists, it will overwrite any data that is already stored within the file with the new data string. The function will return a value of 0 if it fails for whatever reason and a value greater than 0 if it succeeds.

Example:

var fname="SaveData.txt";
var data = string(global.Level) + "|" + string(global.Points) + "|" + string(global.HP);
var len = string_length(data);
steam_file_write_file(fname, data, len);

The above code will prepare a number of local variables and then use them to write to (or create) a file which will then be synchronised with the Steam Cloud.

Back: Steam API
Next: steam_file_write_file

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_file_write_file

Writes contents of a local file to a Steam Cloud file.

Syntax:

steam_file_write_file(steam_filename, local_filename);

Argument | Description
steam_filename | The Steam Cloud file to copy over.
local_filename | The local file to use to copy from.

Returns: real

Description

With this function you can copy the contents of a locally saved file to a file that is synchronised with the Steam Cloud. The local file must exist before using this function, and it will return a value of 0 if it fails for whatever reason and a value greater than 0 if it succeeds.

Example:

steam_file_write_file("rm_koala.png", "Koala2.png");

The above code will copy the contents of the file "Koala2.png" to the Steam Cloud file "rm_koala.png".

Back: Steam API
Next: steam_file_read

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_achievement

Check to see if an achievement has been awarded.

Syntax:

steam_get_achievement(ach_name);

Argument | Description
ach_name | The name of the achievement to get (string).

Returns: Boolean

Description

With this function you can check the Steam API to see if a specific achievement has been awarded. The achievement should have been previously defined on the Steamworks control panel accounts page for your game and the string that is passed to the function should match that used as the API Name on the control panel.

Example:

if hp <= 0
{
global.Deaths += 1;
if global.Deaths == 10
{
if !steam_get_achievement("ach_Player_Dies_Ten_Times") steam_set_achievement("ach_Player_Dies_Ten_Times");
}
}

The above code will reward the player an achievement if the global variable "Deaths" is equal to 10 and if the achievement has not already been awarded.

Back: Steam API
Next: steam_clear_achievement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_app_id

Returns the Steam App ID for your game.

Syntax:

steam_get_app_id();

Returns: Real

Description

This function is used retrieve the unique app ID that Steam assigns for your game, which is required for using some of the User Generated Content functions.

Example:

global.app_id = steam_get_app_id();

The above code gets the unique app ID for your game on Steam and stores it in a global variable.

Back: Steam API
Next: steam_get_user_account_id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_persona_name

Get the name of the user currently logged into the Steam client.

Syntax:

steam_get_persona_name();

Returns: String

Description

You can use this function to return the user name of the user currently logged into the Steam client. This is the visible screen name and not the unique user id (this can be found using the function steam_get_user_steam_id).

Example:

if steam_initialised()
{
global.p_name = steam_get_persona_name();
}

The above code will set a global variable to current users screen name if the Steam client API is correctly initialised.

Back: Steam API
Next: steam_get_user_persona_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_quota_free

Find how much free available storage is left of the quota for the game on the Steam Cloud.

Syntax:

steam_get_quota_free();

Returns: Real

Description

With this function you can find out how much free space is left for the user of the Steam Cloud quota. The value returned is in bytes.

Example:

if steam_is_cloud_enabled_for_app()
{
quota = steam_get_quota_free();
}

The above code checks to see if the steam cloud is enabled for the game and if so it gets the size of the free storage space and stores it in a variable.

Back: Steam API
Next: steam_file_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_quota_total

Find the total available storage quota for game on the Steam Cloud.

Syntax:

steam_get_quota_total();

Returns: Real

Description

When using the Steam Cloud to store and synchronise files, you must set up the quota of space that your game will need. This quota is enforced on each Cloud-enabled game, on a per-user-per-game basis, so, for example, if the quota for Game X is 1 megabyte, then each Steam account that owns Game X may store, at most, 1 megabyte of data associated with that game in the Cloud. Any other Cloud-enabled games that the user owns (say, Game Y) will not be affected by the data stored by Game X. The default quota for new Steamworks games is one gigabyte, but you can change this from the Steamworks control panel for your game.

NOTE: Once the quota is exhausted file writes will fail. If you think it may be possible for the quota to be exhausted for the user of your game, you should create code to handle it, as by doing nothing you leave users in a situation where they are unable to fix things and that will lead to a poor experience of your game.

Example:

if steam_is_cloud_enabled_for_app()
{
quota = steam_get_quota_total();
}

The above code checks to see if the steam cloud is enabled for the game and if so it gets the size of the storage quota and stores it in a variable.

Back: Steam API
Next: steam_get_quota_free

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_stat_avg_rate

Get the value of an average statistic.

Syntax:

steam_get_stat_avg_rate(stat_name);

Argument | Description
stat_name | The name of the statistic to get (a string).

Returns: Real

Description

With this function you can get the value of a specific average statistic. The statistic should have been previously defined on the Steamworks control panel accounts page for your game and the string that is passed to the function should match that used as the API Name on the control panel.

Example:

var avg = steam_get_stat_avg_rate("PointsPerHour");
draw_text(8, 8, "PPH = " + string(avg);

The above code gets the current value for the average statistic "PointsPerHour" and draws it on the screen.

Back: Steam API
Next: steam_reset_all_stats

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_stat_float

Get the value of a floating point statistic.

Syntax:

steam_get_stat_float(stat_name);

Argument | Description
stat_name | The name of the statistic to get (a string).

Returns: Real

Description

With this function you can get the value of a specific floating point statistic. The statistic should have been previously defined on the Steamworks control panel accounts page for your game and the string that is passed to the function should match that used as the API Name on the control panel.

Example:

var dist_pc = (dist / dist_max) * 100;
if steam_get_stat_float("Travelled") < dist_pc
{
steam_set_stat_int("Travelled", dist_pc);
}

The above code calculates a percentage based on the distance travelled variable "dist" and the maximum distance you can travel "dist_max". It then polls the current value for the statistic "Travelled" and if it is less than the calculated value, it sets the stat again.

Back: Steam API
Next: steam_get_stat_avg_rate

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_stat_int

Get the value of a signed integer statistic.

Syntax:

steam_get_stat_int(stat_name);

Argument | Description
stat_name | The name of the statistic to get (a string).

Returns: Real

Description

With this function you can get the value of a specific signed integer statistic. The statistic should have been previously defined on the Steamworks control panel accounts page for your game and the string that is passed to the function should match that used as the API Name on the control panel.

Example:

xp += 100;
steam_set_stat_int("Total_XP", steam_get_stat_int("Total_XP") + 100);
if steam_get_stat_int("Total_XP") > 1000
{
if !steam_get_achievement("Ach_1000XP") steam_set_achievement("Ach_1000XP");
}

The above code sets a statistic and then checks the final value for it to decide whether to award an achievement or not.

Back: Steam API
Next: steam_get_stat_float

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_user_account_id

Returns the Steam User ID for the owner of your game.

Syntax:

steam_get_user_account_id();

Returns: Real

Description

This function is used retrieve the unique User ID that Steam assigns to each user, which is required for using some of the User Generated Content functions.

Example:

global.user_id = steam_get_user_account_id();

The above code gets the unique user ID for the person who owns the game and stores it in a global variable.

Back: Steam API
Next: steam_current_game_language

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_user_persona_name

Get the Steam user name for any given user ID.

Syntax:

steam_get_user_persona_name(steamID);

Argument | Description
steamID | The unique Steam ID for a user.

Returns: Real

Description

This function can be used to retrieve the user name (screen name) for any specific user ID. You give the user ID then the function returns a unique async ID value which can be used to check the details correctly in the Steam Async event. This event will have the async_load DS map which will be populated with the following key/value pairs:

  1. "id" - The async ID returned by the function that triggered the event

  2. "event_type" - The string "user_persona_name"

  3. "steamid"" - The Steam ID value used to get the user name.

  4. "persona_name" - The user name for the given Steam ID

Example:

request = steam_get_user_persona_name(global.UGC_UserID);

The above code will request the user name of the user ID stored in the global variable "UGC_UserID", storing the returned value in a variable for parsing in the Async Event.

Back: Steam API
Next: steam_get_user_steam_id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_get_user_steam_id

Get the user id of the user currently logged into the Steam client.

Syntax:

steam_get_user_steam_id();

Returns: real

Description

You can use this function to return the unique Steam user id of the user currently logged into the Steam client. This is a unique 64 bit value that can be used to identify individual users and not their on screen user name (this can be found using the function steam_get_persona_name).

Example:

if steam_initialised()
{
global.u_id = steam_get_user_steam_id();
}

The above code will set a global variable to the current users unique Steam ID if the Steam client API is correctly initialised.

Back: Steam API
Next: steam_is_user_logged_on

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_initialised

Check the Steam client API to see if it's been started.

Syntax:

steam_initialised();

Returns: Boolean

Description

When using the Steam API, this function can be called to check that the Steam client API has been initialised correctly before any doing any further calls to Steam specific functions in your game.

Example:

global.steam_api = false;
if steam_initialised()
{
if steam_stats_ready() && steam_is_overlay_enabled()
{
global.steam_api = true;
}
}

The above code will set a global variable to true if the Steam client API is correctly initialised, along with the Steam statistics and overlay functionality, or it will set the variable to false otherwise.

Back: Steam API
Next: steam_stats_ready

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_is_cloud_enabled_for_account

Check to see if Steam Cloud storage is enabled for the current user.

Syntax:

steam_is_cloud_enabled_for_account();

Returns: Boolean

Description

With this function you can check to make sure that the Steam Cloud service is enabled by the user in their Steam Client settings. It will return true if it is and false otherwise. Note that this does not automatically mean that you can store data to the Cloud, as it will also have to have been enabled for your game (you can check this using the function steam_is_cloud_enabled_for_app). If the Steam Cloud is enabled for your game, but the user has it switched off locally, you can still use the Cloud functions to store and retrieve data from a local copy of all files, it will just not upload them to the cloud on the game end, nor synchronise on the game start.

Example:

if steam_is_cloud_enabled_for_account
{
steam_file_share("Save.txt");
}

The above code checks to see if the user has the Steam Cloud enabled and if it returns true, it will then synchronise the given file.

Back: Steam API
Next: steam_get_quota_total

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_is_cloud_enabled_for_app

Check to see if Steam Cloud storage is enabled for your game.

Syntax:

steam_is_cloud_enabled_for_app();

Returns: Boolean

Description

With this function you can check to make sure that the Steam Cloud service is enabled for your game. It will return true if it is and false otherwise. Note that this does not automatically mean that you can use the Cloud functions as the user can switch off Cloud synchronisation from their Steam Client. You can check this using the function steam_is_cloud_enabled_for_account, but, even if it is disabled for the user (and enabled for the game), the functions will still work to store and retrieve data from a local copy of all files, it will just not upload them to the cloud on the game end, nor synchronise on the game start.

Example:

if steam_is_cloud_enabled_for_app()
{
quota = steam_get_quota_total();
}

The above code checks to see if the steam cloud is enabled for the game and if so it gets the size of the storage quota and stores it in a variable.

Back: Steam API
Next: steam_is_cloud_enabled_for_account

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_is_overlay_activated

Check to see if the overlay is currently active.

Syntax:

steam_is_overlay_activated();

Returns: Boolean

Description

This function can be used to find out if the user has the Steam Overlay active or not. If the overlay is active and visible to the user the function will return true, and if it is not, then it will return false. An example of what this function can be used for would be for polling the Steam API for the overlay so that you can pause your game while the overlay is being shown.

Example:

if steam_is_overlay_activated()
{
global.Pause = true;
}

The above code will check to see if the Steam overlay is active and if it is it will set the global variable "Pause" to true.

Back: Steam API
Next: steam_create_leaderboard

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_is_overlay_enabled

Check the Steam client API to see if the overlay functionality is enabled.

Syntax:

steam_is_overlay_enabled();

Returns: Boolean

Description

When using the Steam API, this function can be called to check that the Steam client API has the overlay functionality enabled.

Example:

global.steam_api = false;
if steam_initialised()
{
if steam_stats_ready() && steam_is_overlay_enabled()
{
global.steamapi = true;
}
}

The above code will set a global variable to true if the Steam client API is correctly initialised, along with the Steam statistics and overlay functionality, or it will set the variable to false otherwise.

Back: Steam API
Next: steam_is_overlay_activated

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_is_screenshot_requested

Poll the Steam API to check for a screenshot being taken.

Syntax:

steam_is_screenshot_requested();

Returns: Boolean

Description

This function will poll the Steam API to see if the key for taking a screenshot of the game has been pressed. The function will only return true for one step (game tick) if the key has been pressed, and will return false at all other times.

NOTE: this does not take a screenshot for you. This only signals that the key has been pressed and you must use the GameMaker: Studio functions screen_save or screen_save_part to save a local copy of the file to be uploaded.

Example:

if steam_is_screenshot_requested()
{
var file = "Catch_The_Haggis_" + string(global.scrn_num) + ".png");
screen_save(file)
steam_send_screenshot(file, window_get_width(), window_get_height());
global.scrn_num += 1;
}

The above code will poll the Steam API for a screenshot request and if it has been, a unique name for the image file will be generated, a screenshot will be taken, and the file will be sent to the Steam Community page for the user.

Back: Steam API
Next: steam_send_screenshot

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_is_user_logged_on

Check to see if the user is logged onto the Steam Workshop.

Syntax:

steam_is_user_logged_on();

Returns: String

Description

This function will return true if the Steam client currently has a live connection to the Steam servers. If it returns false, it means there is no active connection due to either a networking issue on the local machine, or the Steam server being down or busy.

Example:

if steam_is_user_logged_on()
{
steam_publish_workshop_file("SaveData.txt", "", "Save Text", "Workshop saved text file");
}

The above code will check to see if the user is logged onto the Steam server and if so it will publish a file to the Workshop.

Back: Steam API
Next: steam_get_app_id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_publish_workshop_file

steam_publish_workshop_file (Deprecated)

Upload a previously synchronised file to the Steam Workshop.

Syntax:

steam_publish_workshop_file(filename, preview_image, title, description);

Argument | Description
filename | The name of the Steam Cloud synchronised file to upload (a string).
previewImage | The name of the Steam Cloud synchronised image file to upload (a string).
title | The title of the file to be shown on the Workshop (a string).
description | A description of the file to be shown on the Workshop page (a string). Maximum 8000 characters.

Returns: Real

Description

This function will add the given file to the Steam Workshop section for your game. The file to be shared must have been synchronised to the Steam Cloud previously, using the steam_file_write function for example, as must the image to be shared, and if you do not wish to supply an image for the file, you can use an empty string "". Since this function will automatically share the file when it is called, you do not need to share it yourself nor wait for the Cloud synchronisation on game end. The function will return a value of 0 if it fails for whatever reason and a value greater than 0 if it succeeds.

NOTE: Publishing files requires that the title be unique for all users and will return an error if any user has a file that was shared with the same title.

WARNING! This function has since been deprecated in favour of the newer UGC functions, so you should not use this any more and is covered here to support legacy games only.

Example:

var file = steam_get_persona_name() + "_CatchTheHaggisLevelMap.txt";
steam_file_write_file(file, "CatchTheHaggisLevelMap.txt");
steam_publish_workshop_file(file, "", "Catch The Haggis level Map", "This map was made by " + steam_get_persona_name() + " for Catch The Haggis by MacSweeney Games");

The above code will copy a file to the steam cloud and then synchronise the file to the Steam Workshop.

Back: Steam API
Next: steam_user_owns_dlc

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_reset_all_stats

Reset all statistics.

Syntax:

steam_reset_all_stats();

Returns: N/A

Description

With this function you can reset all the statistics for you game to their default values (as defined in the Steamworks control panel for your game). It is recommended that you only use this function as a debug tool when developing your game.

Example:

ini_open("Save.ini");
if global.Version != ini_read_real("Data", "Version", 0)
{
ini_write_real("Data", "Version", global.Version);
steam_reset_all_stats();
}
ini_close();

The above code checks a stored value in an ini file against that of a global variable and if they are different, it resets the statistics for the game.

Back: Steam API
Next: steam_reset_all_stats_achievements

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_reset_all_stats_achievements

Reset all statistics and achievements.

Syntax:

steam_reset_all_stats_achievements();

Returns: N/A

Description

With this function you can reset all the statistics and achievements for you game to their default values (as defined in the Steamworks control panel for your game). It is recommended that you only use this function as a debug tool when developing your game.

Example:

ini_open("Save.ini");
if global.Version != ini_read_real("Data", "Version", 0)
{
ini_write_real("Data", "Version", global.Version);
steam_reset_all_stats_achievements();
}
ini_close();

The above code checks a stored value in an ini file against that of a global variable and if they are different, it resets the statistics and achievements for the game.

Back: Steam API
Next: steam_is_cloud_enabled_for_app

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_send_screenshot

Upload a screenshot to the users Steam Community profile.

Syntax:

steam_send_screenshot(filename, width, height);

Argument | Description
filename | The name of the image file to upload (a string).
width | The width of the image (an integer).
height | The height of the image (an integer).

Returns: Real

Description

With this function you can upload a screenshot to the Steam Community profile page of the currently logged in user. The filename you supply is the name of the local file that was created when you took the screenshot using the GameMaker: Studio functions screen_save or screen_save_part. The width and height define the image size, and the function will return a value of 0 if it fails for whatever reason and a value greater than 0 if it succeeds.

Example:

if steam_is_screenshot_requested()
{
var file = "Catch_The_Haggis_" + string(global.scrn_num) + ".png");
screen_save(file)
steam_send_screenshot(file, window_get_width(), window_get_height());
global.scrn_num += 1;
}

The above code will poll the Steam API for a screenshot request and if it has been, a unique name for the image file will be generated, a screenshot will be taken, and the file will be sent to the Steam Community page for the user.

Back: Steam API
Next: steam_user_owns_dlc

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_set_achievement

Award an achievement to the player.

Syntax:

steam_set_achievement(ach_name);

Argument | Description
ach_name | The name of the achievement to set (string).

Returns: N/A

Description

With this function you can tell the Steam API to award ("set") an achievement for the player. These achievements should have been defined on the Steamworks control panel accounts page for your game and the string that is passed to the function should match that used as the API Name on the control panel. The Steam Game Overlay will display a notification panel to the user informing them of the achievement that they have received, unless the achievement has already been awarded, in which case nothing will happen.

Example:

if hp <= 0
{
global.Deaths += 1;
if global.Deaths == 10
{
if !steam_get_achievement("ach_Player_Dies_Ten_Times") steam_set_achievement("ach_Player_Dies_Ten_Times");
}
}

The above code will reward the player an achievement if the global variable "Deaths" is equal to 10 and if the achievement has not already been awarded.

Back: Steam API
Next: steam_get_achievement

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_set_stat_avg_rate

Set an average statistic value.

Syntax:

steam_set_stat_avg_rate(stat_name, session_count, session_length);

Argument | Description
stat_name | The name of the statistic to set (a string).
session_count | The value to get the average of (a real number)
session_length | The time that has been taken since the last time the stat was set (a real number).

Returns: N/A

Description

This function permits you to set an average statistic type with a "sliding window" effect on the average. The "session_count" value is the current value that you wish to average out, while the "session_length" is the amount of game time since the last call to the function. Please see the extended Example below for further details on how this can be used.

Extended Example:

Since the average stat function can be complex to understand, we will illustrate its use with the following example. Consider the case where you'd like to track an average statistic, such as "Points earned per hour". One approach would be to have two stats: an integer stat, "TotalPoints", and a float stat "TotalPlayTimeHours", and then divide the total points by the total time to get the "Points per Hour" value.

However, once the player has accumulated a significant amount of playtime, the calculated average will change extremely slowly, and the more the user plays the game, the less responsive that average will be. If the user has spent 100 hours playing the game, the calculated average will "lag" by about 50 hours of that, and if they increase their skill, they will not see the increase in "Points Per Hour" that they expect. To get around that we can use a "sliding window" to only calculate the "Points per hour" for the last 10 hours played.

So, to use this function, we would need to create a Steam stat (in the control panel for the game on the Workshop) called "AvgPointsPerHour" and set its Window property to 10. Now in your game you would have to add some global variables into an instance at the start:

global.Points = 0;
global.Time = 0;

You would then have some controller object to count up the global "Time" variable in an alarm (for example) every second, while your game-play would affect the global "Points" variable. At regular intervals while playing (again, in a controller object, perhaps in an Alarm, or at intervals from polling the "Time" value) you would set the stat like this:

steam_set_stat_avg_rate("AvgPointsPerHour", global.Points, (global.Time / 3600));
global.Points = 0;
global.Time = 0;

Note that we divide time by 3600 since we want the time in hours and not in seconds, and afterward we reset the global "Points" variable and the global "Time" variable to 0 so that the next time the function is called, we get a new average for the statistic. Now, what Steam will do is take this value that you have sent and create an average value over the time that was set for our "window".

Back: Steam API
Next: steam_get_stat_int

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_set_stat_float

Set a floating point statistic.

Syntax:

steam_set_stat_float(stat_name, value);

Argument | Description
stat_name | The name of the statistic to set (a string).
value | The value (a 32bit float) to set the stat to.

Returns: N/A

Description

With this function you can set a specific statistic to a new, floating point, value. The statistic should have been previously defined on the Steamworks control panel accounts page for your game and the string that is passed to the function should match that used as the API Name on the control panel. Examples of when you could use this are for tracking how far your player has travelled, or what percentage of the game is complete.

Example:

var dist_pc = (dist / dist_max) * 100;
steam_set_stat_float("Travelled", dist_pc);

The above code calculates a percentage based on the distance travelled variable "dist" and the maximum distance you can travel "dist_max" and then sets the stat "Travelled" to the new value.

Back: Steam API
Next: steam_set_stat_avg_rate

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_set_stat_int

Set a signed integer statistic.

Syntax:

steam_set_stat_int(stat_name, value);

Argument | Description
stat_name | The name of the statistic to set (a string).
value | The value (a 32bit integer) to set the stat to.

Returns: N/A

Description

With this function you can set a specific statistic to a new, signed integer, value. The statistic should have been previously defined on the Steamworks control panel accounts page for your game and the string that is passed to the function should match that used as the API Name on the control panel. Examples of when you could use this are for tracking how many times the player dies or for tracking progress towards an achievement.

Example:

xp += 100;
steam_set_stat_int("Total_XP", steam_get_stat_int("Total_XP") + 100);
if steam_get_stat_int("Total_XP") > 1000
{
if !steam_get_achievement("Ach_1000XP") steam_set_achievement("Ach_1000XP");
}

The above code sets a statistic and then checks the final value for it to decide whether to award an achievement or not.

Back: Steam API
Next: steam_set_stat_float

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_stats_ready

Check the Steam client API to see if statistics have been set up correctly.

Syntax:

steam_stats_ready();

Returns: Boolean

Description

When using the Steam API, this function can be called to check that the Steam client API has correctly initialised the statistics for your game.

Example:

global.steam_api = false;
if steam_initialised()
{
if steam_stats_ready() && steam_is_overlay_enabled()
{
global.steamapi = true;
}
}

The above code will set a global variable to true if the Steam client API is correctly initialised, along with the Steam statistics and overlay functionality, or it will set the variable to false otherwise.

Back: Steam API
Next: steam_is_overlay_enabled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_upload_score

Upload a score to the Steam server.

Syntax:

steam_upload_score(lb_name, score);

Argument | Description
lb_name | The name of the leaderboard that you are uploading the scores to (a string).
score | The score to upload (a real number).

Returns: Real

Description

This function will send a score to the given leaderboard. The score to be uploaded is a real number, and the leaderboard name is a string that was defined when you created the leaderboard using the function steam_create_leaderboard. If the function fails, it will return a value of -1, while a successful post will return a unique ID for the upload and trigger an asynchronous Steam Event. This event will create a ds_map in the built in variable async_load with the following key/value pairs:

  • "event_type" - This key will hold the value "leaderboard_upload" when triggered by this function

  • "lb_name" - This key holds the name of the leaderboard which was posted to

  • "success" - Will be 1 if the post succeeded, 0 failed

  • "updated" - Will be 1 if the leaderboard score was actually updated (ie: the new score was better) or 0 otherwise

  • "post_id" - This key should match the ID value returned by the upload call

  • "score" - This key holds the score which was posted

Extended Example:

In this example, we first upload a score and then parse the async_load map returned if successful. The code below shows a typical example for uploading:

if (hp <= 0)
{
upload_ID = steam_upload_score("Game Scores", score);
if (!upload_ID)
{
alarm[0] = room_speed;
}
}

Note that we have set an alarm if the call fails. This would be used to try the upload again at a later time and you can add extra code there to retry the upload or to save the score to a text file should it continue to fail, etc... We now add the following into the Steam async event for the instance controlling the scores:

var type = ds_map_find_value(async_load, "event_type");
if (type == "leaderboard_upload")
{
var lb_ID = ds_map_find_value(async_load, "post_id");
if lb_ID == upload_ID
{
var lb_name = ds_map_find_value(async_load, "lb_name");
var lb_done = ds_map_find_value(async_load, "success");
var lb_score = ds_map_find_value(async_load, "score");
var lb_updated = ds_map_find_value(async_load, "updated");
show_debug_message("leaderboard post id:" + string(lb_ID) + " to lb:" + string(lb_name) + " with score:" + string(lb_score) + " updated=" + string(lb_updated));
if (lb_done)
{
show_debug_message("- Succeeded");
}
else
{
show_debug_message("- Failed");
}
}
}

in the example we are simply outputting the return values to the compiler window as debug messages, but you can use this event to deal with the information in any way you choose.

Back: Steam API
Next: steam_upload_score_buffer

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_upload_score_buffer

Upload a score to the Steam server along with a small packet of additional data.

Syntax:

steam_upload_score_buffer(lb_name, score, buffer);

Argument | Description
lb_name | The name of the leaderboard that you are uploading the scores to (a string).
score | The score to upload (a real number).
buffer | The ID of the buffer to attach.

Returns: Real

Description

This function will send a score to the given leaderboard along with a data package created from a buffer. The buffer should be no more than 256 bytes in size - anything beyond that will be chopped off - and can contain any data you require. The score to be uploaded should be a real number, and the leaderboard name is a string that was defined when you created the leaderboard using the function steam_create_leaderboard.

If the function fails, it will return a value of -1, while a successful post will return a unique ID for the upload and trigger an asynchronous Steam Event. This event will create a ds_map in the built in variable async_load with the following key/value pairs:

  • "event_type" - This key will hold the value "leaderboard_upload" when triggered by this function

  • "lb_name" - This key holds the name of the leaderboard which was posted to

  • "success" - Will be 1 if the post succeeded, 0 failed

  • "updated" - Will be 1 if the leaderboard score was actually updated (ie: the new score was better) or 0 otherwise. Note that if the score is updated, the uploaded buffer data will not be added either.

  • "post_id" - This key should match the ID value returned by the upload call

  • "score" - This key holds the score which was posted

Note that if the function when downloading the leaderboard, the "entries" key of the async_load map will now have a "data" key so you can retrieve the uploaded data buffer (see the Steam Event extended code example for further details).

Extended Example:

In this example, we first upload a score and then parse the async_load map returned if successful. The code below shows a typical example for uploading, with a buffer being created to hold a string telling us which level the score was uploaded from:

if (hp <= 0)
{
var buff = buffer_create(256, buffer_fixed, 1 );
buffer_write(buff, buffer_string, "Uploaded on level " + string(global.Level));
upload_ID = steam_upload_score("Game Scores", score, buff);
if (!upload_ID)
{
alarm[0] = room_speed;
}
buffer_delete(buff);
}

Note that we have set an alarm if the call fails. This would be used to try the upload again at a later time and you can add extra code there to retry the upload or to save the score to a text file should it continue to fail, etc... Also note that we immediately delete the buffer, since it is no longer required for the function. We now add the following into the Steam async event for the instance controlling the scores:

var type = ds_map_find_value(async_load, "event_type");
if (type == "leaderboard_upload")
{
var lb_ID = ds_map_find_value(async_load, "post_id");
if lb_ID == upload_ID
{
var lb_name = ds_map_find_value(async_load, "lb_name");
var lb_done = ds_map_find_value(async_load, "success");
var lb_score = ds_map_find_value(async_load, "score");
var lb_updated = ds_map_find_value(async_load, "updated");
show_debug_message("leaderboard post id:" + string(lb_ID) + " to lb:" + string(lb_name) + " with score:" + string(lb_score) + " updated=" + string(lb_updated));
if (lb_done)
{
show_debug_message("- Succeeded");
}
else
{
show_debug_message("- Failed");
}
}
}

In the example we are simply outputting the return values to the compiler window as debug messages, but you can use this event to deal with the information in any way you choose.

Back: Steam API
Next: steam_download_scores

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_user_installed_dlc

Check to see if the user has installed the specified DLC (Downloadable Content).

Syntax:

steam_user_installed_dlc(dlc_id);

Argument | Description
dlc_id | The unique identifier for the DLC to be checked (an integer).

Returns: Boolean

Description

If your game has DLC created for it, you can use this function to check and see whether the user has installed it before accessing any files associated with it. The function returns true if the player has the content installed, and false if the user does not, but note that the user must also own the DLC, so you should use the additional function of steam_user_owns_dlc to check that it is owned as well before using it.

Example:

global.Level_Max = 100;
if steam_user_owns_dlc(10354)
{
if steam_user_installed_dlc(10354)
{
global.Level_max = 200;
}
}

The above code will check to see if the user has bought, and installed, the DLC with the id 10354, and if so set a global variable to a different value.

Back: Steam API
Next: steam_initialised

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_user_owns_dlc

Check to see if the user owns the specified DLC (Downloadable Content).

Syntax:

steam_user_owns_dlc(dlc_id);

Argument | Description
dlc_id | The unique identifier for the DLC to be checked (an integer).

Returns: Boolean

Description

If your game has DLC created for it, you can use this function to check and see whether the user has bought it before accessing any files associated with it. The function returns true if the player owns the content, and false if the user does not, but note that even if the user owns the DLC, they may not have it installed, so you should use the additional function of steam_user_installed_dlc to check that it is installed as well before using it.

Example:

global.Level_Max = 100;
if steam_user_owns_dlc(10354)
{
if steam_user_installed_dlc(10354)
{
global.Level_max = 200;
}
}

The above code will check to see if the user has bought, and installed, the DLC with the id 10354, and if so set a global variable to a different value.

Back: Steam API
Next: steam_user_installed_dlc

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


User Generated Content

User Generated Content (UGC)

This section shows the functions associated with the Steam API specifically for user generated content (UGC).

This section is for those users that have been given access to the Steam API for publishing your game to that platform and that want to use the possibilities that the Steam Workshop and Community gives you for adding and generating user content in your projects. Some of the functions in this page require the Steam App ID for your project as well as a User ID for the person playing the game or their user name, which can be found using the following functions:

  1. steam_get_app_id
  2. steam_get_user_account_id
  3. steam_get_user_persona_name

Before using any of the built in functions for the Steam UGC API you need to have set up your game correctly from the Steam dashboard and you should have read through the required documentation found here: Sharing User Generated Content (note that you need to have your game accepted for the Steam network and have access to the developer areas of the Steam API documentation). All subscribed UGC items will be downloaded by the Steam client automatically, and you should have code in the Steam Asynchronous Event to catch this and store the ID of the UGC that has been downloaded for use in the other UGC functions.

IMPORTANT! Steam UGC ID's can be huge numbers over 600,000,000. This means that sometimes you may need to store these as a string rather than try and store them as a real value, especially if working with buffers or trying to write the value to a text file (since this will convert it to a simplified standard format like "6.6624e+003" which will cause issues being read back).

The normal workflow for getting UGC into your game would be as follows:

  • The user would subscribe to an item (either from your game using steam_ugc_subscribe_item() or from the client/browser.

  • Your game would "listen" for new subscriptions with the appropriate code in the Steam Async Event.

  • When you get a subscription async event, you would then check if the item is installed (ie: downloaded) with steam_ugc_get_item_install_info().

  • If the item is not installed, you'll need a check using steam_ugc_get_item_update_info() to track the download progress.

Creating And Editing Content

The following functions are essentially "wrapper" functions for those supplied in the Steam API for creating and uploading content to their servers. As such, we recommend that you read over the linked Steam documentation before using them to gain a greater understanding of how they work: Creating And Uploading Content.

  1. steam_ugc_create_item
  2. steam_ugc_start_item_update
  3. steam_ugc_set_item_title
  4. steam_ugc_set_item_description
  5. steam_ugc_set_item_visibility
  6. steam_ugc_set_item_tags
  7. steam_ugc_set_item_content
  8. steam_ugc_set_item_preview
  9. steam_ugc_submit_item_update
  10. steam_ugc_get_item_update_progress

Consuming Content

Once your user content has been created and the workshop has it available for download, people can subscribe to it through the Steam App or through the Web portal. However GameMaker: Studio also includes the following functions to use the Steam API for creating and canceling subscriptions as well as for getting information about what the user is subscribed to currently:

  1. steam_ugc_subscribe_item
  2. steam_ugc_unsubscribe_item
  3. steam_ugc_num_subscribed_items
  4. steam_ugc_get_subscribed_items
  5. steam_ugc_get_item_install_info
  6. steam_ugc_get_item_update_info
  7. steam_ugc_request_item_details

Querying Content

There are also a large number of functions available to query the Steam API about the UGC items available:

  1. steam_ugc_create_query_user
  2. steam_ugc_create_query_user_ex
  3. steam_ugc_create_query_all
  4. steam_ugc_create_query_all_ex
  5. steam_ugc_query_set_cloud_filename_filter
  6. steam_ugc_query_set_match_any_tag
  7. steam_ugc_query_set_search_text
  8. steam_ugc_query_set_ranked_by_trend_days
  9. steam_ugc_query_add_required_tag
  10. steam_ugc_query_add_excluded_tag
  11. steam_ugc_query_set_return_long_description
  12. steam_ugc_query_set_return_total_only
  13. steam_ugc_query_set_allow_cached_response
  14. steam_ugc_send_query

You can get a preview image of any UGC item from the workshop by using the function steam_ugc_send_query() to get the preview file handle of the image, and then calling the following function:

  1. steam_ugc_download

Back: Contents

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_create_item

Create an item for the workshop and get its published file ID.

Syntax:

steam_ugc_create_item(consumer_app_id, file_type);

Argument | Description
consumer_app_id | The unique App ID for your game on Steam.
file_type | One of the available file type constants (listed below).

Returns: Async ID

Description

This function is used to prepare the Workshop API and generate a published file ID for the item to be added. The function must be called before doing anything else with the item to be uploaded, as you will be required to use the unique published ID value that it returns in the Steam Async Event for updating. To use this function, you need to supply the Steam App ID for your game, and the use one of the following constants for the file_type argument:

Constant | Description
ugc_filetype_community | This is used to create files that will be uploaded and made available to anyone in the community.
ugc_filetype_microtrans | This is used to describe files that are uploaded but intended only for the game to consider adding as official content.

When using this function it will return an async ID value which can then be parsed when the Steam Asynchronous event is triggerd to report the creation of the item. The event will contain the following key/map values in the async_load ds_map:

  1. "id" - The async ID returned by the calling function

  2. "result" - The result of the operation (a real value). This will either be the GML constant ugc_result_success or some other real number. So you should check for this constant to ensure that the call was successful, and if otherwise somthing has not worked correctly. The rest of the possible values returned are shown as the result of the Steam "EResult" value and you should see steamclientpublic.h in the SDK headers for all 89 possible values.

  3. "event_type" - This key will hold the value "ugc_create_item"

  4. "legal_agreement_required" - Will be true or false (see the Steam docs for more details)

  5. "published_file_id" - This key holds the unique published ID for the item

Extended Example:

In this example we first call the function and store the async ID value in a variable:

var app_id = steam_get_app_id();
new_item = steam_ugc_create_item(app_id, ugc_filetype_community);

This would then send off a request to the Steam API to create the new Worksop item, generating an async event which we would deal with as follows:

var event_id = async_load[? "id"];
if event_id == new_item
{
var type = async_load[? "event_type"];
if type == "ugc_create_item"
{
global.Publish_ID = async_load[? "published_file_id"];
}
}

The above code checks the event type and if it is "ugc_create_item" then it retrieves the published file ID and stores it in a global variable for future reference.

Back: Steam API - User Generated Content
Next: steam_ugc_start_item_update

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_create_query_all

Create a general UGC query using the app ID and certain predefined options.

Syntax:

steam_ugc_create_query_all(query_type, match_type, page);

Argument | Description
query_type | The type of query to create (see constants listed below).
match_type | The type of UGC items to query (see constants listed below).
page | The page number to query.

Returns: Query Handle

Description

This function can be used to query the UGC data base using some pre-defined query types. The function requires the following constants for the type of query to create, the type of item to query and the page number to query - note that a query will return a maximum number of 50 items.

Query Type Constant | Description
ugc_query_RankedByVote | See the Steam Documentation.
ugc_query_RankedByPublicationDate | -
ugc_query_AcceptedForGameRankedByAcceptanceDate | -
ugc_query_RankedByTrend | -
ugc_query_FavoritedByFriendsRankedByPublicationDate | -
ugc_query_CreatedByFriendsRankedByPublicationDate | -
ugc_query_RankedByNumTimesReported | -
ugc_query_CreatedByFollowedUsersRankedByPublicationDate | -
ugc_query_NotYetRated | -
ugc_query_RankedByTotalVotesAsc | -
ugc_query_RankedByVotesUp | -
ugc_query_RankedByTextSearch | -
Match Type Constant | Description
ugc_match_Items | See the Steam Documentation.
ugc_match_Items_Mtx | -
ugc_match_Items_ReadyToUse | -
ugc_match_Collections | -
ugc_match_Artwork | -
ugc_match_Videos | -
ugc_match_Screenshots | -
ugc_match_AllGuides | -
ugc_match_WebGuides | -
ugc_match_IntegratedGuides | -
ugc_match_UsableInGame | -
ugc_match_ControllerBindings | -

The function returns a unique query handle value which should be stored in a variable for use in the other query functions. Note that this function only prepares the query but does not actually send it - for that you must call the function steam_ugc_send_query - and you can use further steam_ugc_query_*() functions to refine the search request before it is actually sent.

Example:

query_handle = steam_ugc_create_query_all(ugc_query_RankedByVote, ugc_match_Items, 1);

The above code creates a general query request and stores it's handle in a variable for future use.

Back: Steam API - User Generated Content
Next: steam_ugc_create_query_all_ex

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_create_query_all_ex

Create a more general UGC query, specifying creator and consumer details.

Syntax:

steam_ugc_create_query_all_ex(query_type, match_type, page, creator_app_id, consumer_app_id);

Argument | Description
query_type | The type of data query to create (see constants listed below).
match_type | The type of UGC items to query (see constants listed below).
page | The page number to query.
creator_app_id | The item creator app ID.
consumer_app_id | The consumer app ID.

Returns: Query Handle

Description

This function can be used to query the UGC data base. The function requires the ID of the game that is going to consume the item and/or the ID of the game that created the item, and you need to use the following constants for the type of query to create, the type of item to query and the page number to quer. Note that a query will return a maximum number of 50 items.

Query Type Constant | Description
ugc_query_RankedByVote | See the Steam Documentation.
ugc_query_RankedByPublicationDate | -
ugc_query_AcceptedForGameRankedByAcceptanceDate | -
ugc_query_RankedByTrend | -
ugc_query_FavoritedByFriendsRankedByPublicationDate | -
ugc_query_CreatedByFriendsRankedByPublicationDate | -
ugc_query_RankedByNumTimesReported | -
ugc_query_CreatedByFollowedUsersRankedByPublicationDate | -
ugc_query_NotYetRated | -
ugc_query_RankedByTotalVotesAsc | -
ugc_query_RankedByVotesUp | -
ugc_query_RankedByTextSearch | -
Match Type Constant | Description
ugc_match_Items | See the Steam Documentation.
ugc_match_Items_Mtx | -
ugc_match_Items_ReadyToUse | -
ugc_match_Collections | -
ugc_match_Artwork | -
ugc_match_Videos | -
ugc_match_Screenshots | -
ugc_match_AllGuides | -
ugc_match_WebGuides | -
ugc_match_IntegratedGuides | -
ugc_match_UsableInGame | -
ugc_match_ControllerBindings | -

The function returns a unique query handle value which should be stored in a variable for use in the other query functions. Note that this function only prepares the query but does not actually send it - for that you must call the function steam_ugc_send_query - and you can use further steam_ugc_query_*() functions to refine the search request before it is actually sent.

Example:

query_handle = steam_ugc_create_query_all_ex(ugc_query_RankedByVote, page, global.AccountID, 0, global.GameID);

The above code creates a query request and stores it's handle in a variable for future use.

Back: Steam API - User Generated Content
Next: steam_ugc_query_set_cloud_filename_filter


steam_ugc_create_query_user

Create a UGC query using the current user account ID and current app ID.

Syntax:

steam_ugc_create_query_user(list_type, match_type, sort_order, page);

Argument | Description
list_type | The type of data list to create (see constants listed below).
match_type | The type of UGC items to query (see constants listed below).
sort_order | The way that the data should be ordered (see constants listed below).
page | The page number to query.

Returns: Query Handle

Description

This function can be used to query the UGC data base. The function automatically uses the default ID for the app, user and assumes that the query is being done by the consumer (rather than the creator). The function requires you to use the following constants for the type of data to query, the type of item to query and the order in which the returned items will be sorted, as well as a page number - note that a query will return a maximum number of 50 items.

List Type Constant | Description
ugc_list_Published | See the Steam Documentation.
ugc_list_VotedOn | -
ugc_list_VotedUp | -
ugc_list_VotedDown | -
ugc_list_WillVoteLater | -
ugc_list_Favorited | -
ugc_list_Subscribed | -
ugc_list_UsedOrPlayed | -
ugc_list_Followed | -
Match Type Constant | Description
ugc_match_Items | See the Steam Documentation.
ugc_match_Items_Mtx | -
ugc_match_Items_ReadyToUse | -
ugc_match_Collections | -
ugc_match_Artwork | -
ugc_match_Videos | -
ugc_match_Screenshots | -
ugc_match_AllGuides | -
ugc_match_WebGuides | -
ugc_match_IntegratedGuides | -
ugc_match_UsableInGame | -
ugc_match_ControllerBindings | -
Sort Order Constant | Description
ugc_sortorder_CreationOrderDesc | See the Steam Documentation.
ugc_sortorder_CreationOrderAsc | -
ugc_sortorder_TitleAsc | -
ugc_sortorder_LastUpdatedDesc | -
ugc_sortorder_SubscriptionDateDesc | -
ugc_sortorder_VoteScoreDesc | -
ugc_sortorder_ForModeration | -

The function returns a unique query handle value which should be stored in a variable for use in the other query functions. Note that this function only prepares the query but does not actually send it - for that you must call the function steam_ugc_send_query - and you can use further steam_ugc_query_*() functions to refine the search request before it is actually sent.

Example:

query_handle = steam_ugc_create_query_user(ugc_list_Published, ugc_match_Items, ugc_sortorder_TitleAsc, 1);

The above code creates a query request and stores it's handle in a variable for future use.

Back: Steam API - User Generated Content
Next: steam_ugc_create_query_user_ex

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_create_query_user_ex

Create a more specific UGC query using the Steam account ID and the app ID's for the item creator and the consumer.

Syntax:

steam_ugc_create_query_user_ex(list_type, match_type, sort_order, page, account_id, creator_app_id, consumer_app_id);

Argument | Description
list_type | The type of data list to create (see constants listed below).
match_type | The type of UGC items to query (see constants listed below).
sort_order | The way that the data should be ordered (see constants listed below).
page | The page number to query.
account_id | The Steam account ID.
creator_app_id | The item creator app ID.
consumer_app_id | The consumer app ID.

Returns: Query Handle

Description

This function can be used to query the UGC data base. The function requires the ID value for the user and the ID of the game that is going to consume the item and/or the ID of the game that created the item. You also need to use the following constants for the type of data to query, the type of item to query and the order in which the returned items will be sorted, as well as a page number - note that a query will return a maximum number of 50 items.

List Type Constant | Description
ugc_list_Published | See the Steam Documentation.
ugc_list_VotedOn | -
ugc_list_VotedUp | -
ugc_list_VotedDown | -
ugc_list_WillVoteLater | -
ugc_list_Favorited | -
ugc_list_Subscribed | -
ugc_list_UsedOrPlayed | -
ugc_list_Followed | -
Match Type Constant | Description
ugc_match_Items | See the Steam Documentation.
ugc_match_Items_Mtx | -
ugc_match_Items_ReadyToUse | -
ugc_match_Collections | -
ugc_match_Artwork | -
ugc_match_Videos | -
ugc_match_Screenshots | -
ugc_match_AllGuides | -
ugc_match_WebGuides | -
ugc_match_IntegratedGuides | -
ugc_match_UsableInGame | -
ugc_match_ControllerBindings | -
Sort Order Constant | Description
ugc_sortorder_CreationOrderDesc | See the Steam Documentation.
ugc_sortorder_CreationOrderAsc | -
ugc_sortorder_TitleAsc | -
ugc_sortorder_LastUpdatedDesc | -
ugc_sortorder_SubscriptionDateDesc | -
ugc_sortorder_VoteScoreDesc | -
ugc_sortorder_ForModeration | -

The function returns a unique query handle value which should be stored in a variable for use in the other query functions. Note that this function only prepares the query but does not actually send it - for that you must call the function steam_ugc_send_query - and you can use further steam_ugc_query_*() functions to refine the search request before it is actually sent.

Example:

query_handle = steam_ugc_create_query_user_ex(ugc_list_Published, ugc_match_Items, ugc_sortorder_TitleAsc, page, global.AccountID, 0, global.GameID);

The above code creates a query request and stores it's handle in a variable for future use.

Back: Steam API - User Generated Content
Next: steam_ugc_create_query_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_download

Download a preview image of a given UGC item.

Syntax:

steam_ugc_download(ugc_handle, dest_filename);

Argument | Description
ugc_handle | The unique handle for the preview to be downloaded.
dest_filename | The file name to save the preview with.

Returns: Async ID

Description

With this function you can download a preview image for any given UGC item. The ugc_handle is the unique identifying value for the image (which you can get using the function steam_ugc_send_query()), and the destination filename is the name (and local path within the Steam sandbox) that you wish to give the image file when the download is complete.

When using this function it will trigger an Steam Asynchronous event to report the details of the image file requested containing the following key/value pairs in the async_load ds_map:

  1. "id" - The async ID returned by the calling function

  2. "result" - The result of the operation (a real value). This will either be the GML constant ugc_result_success or some other real number. So you should check for this constant to ensure that the call was successful, and if otherwise somthing has not worked correctly. The rest of the possible values returned are shown as the result of the Steam "EResult" value and you should see steamclientpublic.h in the SDK headers for all 89 possible values.

  3. "event_type" - This key will hold the value "ugc_download"

  4. "original_filename" - This key holds the original name of the image file on the server (a string)

  5. "dest_filename" - This key holds the image file name you passed in (a string)

  6. "ugc_handle" - This key holds the ugc_handle value that you passed in to the calling function

Extended Example:

In this example we first call the function and store the async ID value in a variable:

steam_get = steam_ugc_download(steam_handle, "\UGC\Preview_file.png");

This would then send off a file request to the Steam API, generating an async event which we would deal with as follows:

var event_id = async_load[? "id"];
if event_id == steam_get
{
var type = async_load[? "event_type"];
if type ==  "ugc_download"
{
sprite_delete(preview_sprite);
      preview_sprite = sprite_add(async_load[? "dest_filename"], 0, false, false, 0, 0);
}
}

The above code checks the event type and then creates a sprite from the downloaded image.

Back: Steam API - User Generated Content
Next: steam_ugc_create_item

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_get_item_install_info

Retrieves information about the state of the local copy of the given item.

Syntax:

steam_ugc_get_item_install_info(published_file_id, info_map);

Argument | Description
published_file_id | The unique handle for the UGC to be updated.
info_map | A (previously created) DS map index.

Returns: Boolean

Description

This function can be used to retrieve information about any given published file item that has been subscribed to and downloaded to the Steam local storage area for your game. You give the item ID and supply the index to an empty DS map which will then be populated with the following key/value pairs if the item exists:

  1. "size_on_disk" - The file size on disk (in bytes)

  2. "legacy_item" - Will be true or false depending on whether it is a legacy file or not.

  3. "folder" - This is the full path to the installed content ( please refer to "Item Installation" in Steam SDK docs, as "legacy" items uploaded with the old method, are treated differently).

If the item exists then the function will return true and populate the map, otherwise it will return false and the map will remain empty.

Example:

var item_map = ds_map_create();
steam_ugc_get_item_install_info(global.fileID, item_map);

The above code will query the install status of the item indexed in the global variable "fileID", using a ds_map to store the information.

Back: Steam API - User Generated Content
Next: steam_ugc_get_item_update_info

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_get_item_update_info

Populates a ds_map with information about the an item update.

Syntax:

steam_ugc_get_item_update_info(published_file_id, info_map);

Argument | Description
published_file_id | The unique file ID for the UGC to be checked.
info_map | A (previously created) DS map index.

Returns: Boolean

Description

This function can be used to retrieve information about the current download state for the given file ID. You give the item ID and supply the index to an empty DS map which will then be populated with the following key/value pairs if the item exists:

  1. "needs_update" - Will return true or false depending on whether the item needs an update or not.

  2. "is_downloading" - Will return true or false depending on whether the item is currently downloading or not.

  3. "bytes_downloaded" - The number of bytes that has been downloaded.

  4. "bytes_total" - The total size (number of bytes) required for the item on disk.

If the item exists then the function will return true and populate the map, otherwise it will return false and the map will remain empty.

Example:

var info_map = ds_map_create();
var info = steam_ugc_get_item_update_info(global.fileID, info_map);
if info
{
draw_text(32, 15, "needs_update: " + string(info_map[? "needs_update"]));
draw_text(32, 30, "is_downloading: " + string(info_map[? "is_downloading"]));
draw_text(32, 45, "bytes_downloaded: " + string(info_map[? "bytes_downloaded"]));
draw_text(32, 60, "bytes_total: " + string(info_map[? "bytes_total"]));
}

The above code will query the download status of the item indexed in the global variable "fileID", using a ds_map to store the information.

Back: Steam API - User Generated Content
Next: steam_ugc_request_item_details

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_get_item_update_progress

Populates a ds_map with information about the progress of an item update.

Syntax:

steam_ugc_get_item_update_progress(ugc_update_handle, info_map);

Argument | Description
ugc_update_handle | The unique handle for the UGC to be updated.
info_map | A (previously created) DS map index.

Returns: Boolean

Description

This function can be used to track the update status for an item. You give the item handle (as returned by the function steam_ugc_start_item_update) and an empty DS map which will then be populated with the following key/value pairs:

  1. "status_code" - The Steam status code

  2. "status_string" - A string for the current status

  3. "bytes_processed" - The bytes processed so far

  4. "bytes_total" - The total number of bytes in the update

If there is an error the function will return false and the map will be empty, otherwise the function returns true.

Example:

var uploadMap = ds_map_create();
steam_ugc_get_item_update_progress(global.itemHandle, uploadMap);
var statusCode = uploadMap[? "status_code"];
var status = uploadMap[? "status_string"];
var processed = uploadMap[? "bytes_processed"];
var total = uploadMap[? "bytes_total"];
draw_text(32, 0, "Upload info for item:" + string(global.itemHandle));
draw_text(32, 15, "status code:" + string(statusCode));
draw_text(32, 30, "status:" + string(status));
draw_text(32, 45, "bytes processed:" +string(processed));
draw_text(32, 60, "bytes total:" + string( total));
ds_map_destroy(uploadMap);

The above code will query the upload status of the item indexed in the global variable "itemHandle", using a ds_map to store the information. This is then parsed and the resulting values drawn to the screen.

Back: Steam API - User Generated Content
Next: steam_ugc_subscribe_item

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_get_subscribed_items

Retrieve a list of all subscribed item IDs.

Syntax:

steam_ugc_get_subscribed_items(item_list);

Argument | Description
item_list | A (previously created) DS list index.

Returns: Boolean

Description

This function will populate a DS list with all the published file IDs for the items that the user is currently subscribed to. You must first create the list and store the index in a variable, then pass this to the function. The function will return true if everything is correct and the Steam API is initialised, or false if there is an error.

Example:

steam_list = ds_list_create();
steam_ugc_get_subscribed_items(steam_list);

The above code will create an empty DS list and then populate it with the file IDs for all subscribed items for the user.

Back: Steam API - User Generated Content
Next: steam_ugc_get_item_install_info

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_num_subscribed_items

Get the number of items that the user has subscribed to.

Syntax:

steam_ugc_num_subscribed_items();

Returns: Real

Description

This function can be used to get the number of items that the current user has subscribed to.

Example:

numSub = steam_ugc_num_subscribed_items();

The above code will store the number of subscribed items in a variable.

Back: Steam API - User Generated Content
Next: steam_ugc_get_subscribed_items

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_query_add_excluded_tag

Sets a tag that should be excluded from the UGC query.

Syntax:

steam_ugc_query_add_excluded_tag(ugc_query_handle , tag_name);

Argument | Description
ugc_query_handle | The query handle to use.
tag_name | The tag name to exclude (a string).

Returns: Boolean

Description

This function can be used to further filter any given UGC query, specifically to exclude a given UGC from the query request. The query handle is the value returned when you created the query (using, for example, steam_ugc_create_query_user()) and the second argument is a string you want to use as the tag to exclude. The function will return true if the query filter was correctly set, or false otherwise.

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByVote, ugc_match_Items, 1);
steam_ugc_query_add_excluded_tag(query_handle, "walking simulator");
steam_ugc_query_set_return_long_description(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_query_set_return_long_description


steam_ugc_query_add_required_tag

Sets a tag that the queried UGC should have.

Syntax:

steam_ugc_query_add_required_tag(ugc_query_handle , tag_name);

Argument | Description
ugc_query_handle | The query handle to use.
tag_name | The tag name to include (a string).

Returns: Boolean

Description

This function can be used to further filter any given UGC query, specifically to search only those UGC items with the given tag. The query handle is the value returned when you created the query (using, for example, steam_ugc_create_query_user()) and the second argument is a string you want to use as the tag to include. The function will return true if the query filter was correctly set, or false otherwise.

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByTrend, ugc_match_Items, 1);
steam_ugc_query_add_required_tag(query_handle, "RPG");
steam_ugc_query_set_return_long_description(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_query_add_excluded_tag

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_query_set_allow_cached_response

Sets whether to check the local cache for the query.

Syntax:

steam_ugc_query_set_allow_cached_response(ugc_query_handle , cache);

Argument | Description
ugc_query_handle | The query handle to use.
cache | Whether to have the query check the local cache or not.

Returns: Boolean

Description

This function can be used to further filter any given UGC query, specifically to request that the query check the local cache rather than online. The query handle is the value returned when you created the query (using, for example, steam_ugc_create_query_user()) and the second argument is either true or false. The function will return true if the query filter was correctly set, or false otherwise.

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByTrend, ugc_match_Items, 1);
steam_ugc_query_add_required_tag(query_handle, "RPG");
steam_ugc_query_set_return_long_description(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_send_query

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_query_set_cloud_filename_filter

Sets a filename filter for a given query.

Syntax:

steam_ugc_query_set_cloud_filename_filter(ugc_query_handle , match_cloud_filename);

Argument | Description
ugc_query_handle | The query handle to use.
match_cloud_filename | Sets whether the UGC item file name should match or not.

Returns: Boolean

Description

This function can be used to further filter any given UGC query, specifically to check and see if a Workshop item file name must match or not. The query handle is the value returned when you created the query (using, for example, steam_ugc_create_query_user()) and the second argument is either true or false depending on whether you require the file names to match. The function will return true if the query filter was correctly set, or false otherwise.

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByVote, ugc_match_Items, 1);
steam_ugc_query_set_cloud_filename_filter(query_handle, true);
steam_ugc_query_add_excluded_tag(query_handle, "nasty chips");
steam_ugc_query_set_return_long_description(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_query_set_match_any_tag

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_query_set_match_any_tag

Set whether to match tags or not for the query.

Syntax:

steam_ugc_query_set_match_any_tag(ugc_query_handle , match_any_tag);

Argument | Description
ugc_query_handle | The query handle to use.
match_any_tag | Sets whether the UGC item tags should match anything or not.

Returns: Boolean

Description

This function can be used to further filter any given UGC query, specifically to switch on or off tag matching. The query handle is the value returned when you created the query (using, for example, steam_ugc_create_query_user()) and the second argument is either true or false depending on whether you require a check for matching tags. The function will return true if the query filter was correctly set, or false otherwise.

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByVote, ugc_match_Items, 1);
steam_ugc_query_set_match_any_tag(query_handle, false);
steam_ugc_query_add_excluded_tag(query_handle, "walking simulator");
steam_ugc_query_set_return_long_description(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_query_set_search_text

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_query_set_ranked_by_trend_days

Sets the number of days over which to run the query.

Syntax:

steam_ugc_query_set_ranked_by_trend_days(ugc_query_handle , days);

Argument | Description
ugc_query_handle | The query handle to use.
days | The number of days to query.

Returns: Boolean

Description

This function can be used to further filter any UGC query made using the ugc_query_RankedByTrend constant, specifically to search over a number of days. The query handle is the value returned when you created the query (using, for example, steam_ugc_create_query_user()) and the second argument is the number of days over which you want the query to run. The function will return true if the query filter was correctly set, or false otherwise.

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByTrend, ugc_match_Items, 1);
steam_ugc_query_set_ranked_by_trend_days(query_handle, 5);
steam_ugc_query_set_return_long_description(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_query_add_required_tag

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_query_set_return_long_description

Sets a tag that should be excluded from the UGC query.

Syntax:

steam_ugc_query_set_return_long_description(ugc_query_handle , long_description);

Argument | Description
ugc_query_handle | The query handle to use.
long_description | Whether to have the query return the long description text.

Returns: Boolean

Description

This function can be used to further filter any given UGC query, specifically to retrieve the long description text in the call back event triggered when the query was sent. The query handle is the value returned when you created the query (using, for example, steam_ugc_create_query_user()) and the second argument is either true or false. The function will return true if the query filter was correctly set, or false otherwise.

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByVote, ugc_match_Items, 1);
steam_ugc_query_set_return_long_description(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_query_set_return_total_only


steam_ugc_query_set_return_total_only

Sets the return callback to only show the number of hits for the query.

Syntax:

steam_ugc_query_set_return_total_only(ugc_query_handle , total_only);

Argument | Description
ugc_query_handle | The query handle to use.
total_only | Whether to have the query return only the total number of hits or not.

Returns: Boolean

Description

This function can be used to further filter any given UGC query, specifically to request only the number of results without any other information (meaning that the DS map generated by the send function will contain the key "num_results" without any further map data). The query handle is the value returned when you created the query (using, for example, steam_ugc_create_query_user()) and the second argument is either true or false. The function will return true if the query filter was correctly set, or false otherwise.

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByVote, ugc_match_Items, 1);
steam_ugc_query_set_return_total_only(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_query_set_allow_cached_response


steam_ugc_query_set_search_text

Sets the search text to use for a given query.

Syntax:

steam_ugc_query_set_search_text(ugc_query_handle , search_text);

Argument | Description
ugc_query_handle | The query handle to use.
search_text | The search text to use (a string) for the query.

Returns: Boolean

Description

This function can be used to further filter any given UGC query, specifically to search for the given string in the title and description of the UGC items. The query handle is the value returned when you created the query (using, for example, steam_ugc_create_query_user()) and the second argument is a string you want to use as the search term. The function will return true if the query filter was correctly set, or false otherwise.

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByVote, ugc_match_Items, 1);
steam_ugc_query_set_search_text(query_handle, "texture");
steam_ugc_query_set_return_long_description(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_query_set_ranked_by_trend_days


steam_ugc_request_item_details

Requests information about the an item.

Syntax:

steam_ugc_request_item_details(published_file_id, max_age_seconds);

Argument | Description
published_file_id | The unique file ID for the UGC to be checked.
max_age_seconds | The "age" of the data to check (recommended 30 - 60 seconds).

Returns: Async ID

Description

This function can be used to retrieve information about a given file ID. You give the file ID and supply a maximum age for checking (see the Steam docs for more information), then the function returns a unique async ID value which can be used to check the details correctly in the Steam Async event. This event will have the async_load DS map which will be populated with the following key/value pairs:

  1. "id" - The async ID returned by the function that triggered the event

  2. "result" - The result of the operation (a real value). This will either be the GML constant ugc_result_success or some other real number. So you should check for this constant to ensure that the call was successful, and if otherwise somthing has not worked correctly. The rest of the possible values returned are shown as the result of the Steam "EResult" value and you should see steamclientpublic.h in the SDK headers for all 89 possible values.

  3. "event_type" - The string "ugc_item_details"

  4. "cached_data" - Will be true if the returned details are from the local cache or false if they are taken from the server

  5. "published_file_id"" -Holds the unique published file id for the item

  6. "file_type" - The type of file used

  7. "creator_app_id" - The Steam ID of the item creator

  8. "consumer_app_id" - The Steam ID of the item consumer

  9. "title" - The title of the item

  10. "description" - The description of the item

  11. "steam_id_owner" - The Steam ID of the item owner

  12. "time_created" - The time the item was first created

  13. "time_updated" - The last time the item was updated

  14. "time_added_to_user_list" - The time that the item was subscribed to

  15. "visibility" - The visibility of the item (see steam_ugc_set_item_visibility() for the returned constants)

  16. "banned" - Whether the item has been banned (true) or not (false)

  17. "accepted_for_use" - Whether the item has been accepted for use (true) or not (false)

  18. "tags_truncated" - Short version of the tags as an array

  19. "tags" - An array of the tags for the item

  20. "handle_file" - The unique file handle for the item

  21. "handle_preview_file" - The unique handle for the image preview for the item (can be used as an argument with steam_ugc_download() to download a preview image)

  22. "filename" - The name of the item file

  23. "file_size" - The size of the item file

  24. "preview_file_size" - The size of the preview image

  25. "url" - The full URL for the item

  26. "votes_up" - The number of up-votes received

  27. "votes_down" - The number of down-votes received

  28. "score" - The overall score of the item

  29. "account_id_owner" - The account ID from the Steam ID owner (this can be used in the function steam_ugc_create_query_user_ex())

Extended Example:

In this example we send off a details request for an item and then parse the resulting async_load DS map to set some variables. First we send of the request:

steam_details = steam_ugc_request_item_details(global.fileID, 60);

The above code will request details on the item with the file ID stored in the global variable and will trigger a Steam Async event with the returned information. In this event we can then parse the map and store some of the values in variables which can then be used to display the information to the user:

var map_id = async_load[? "id"];
var result = async_load[? "result"];
if (map_id == steam_details) && (result == ugc_result_success)
{
mTitle = async_load[? "title"];
mDesc = async_load[? "description"];
mTags = async_load[? "tags"];
m_hPreviewFile = async_load[? "handle_preview_file"];
m_hOwnerSteamId = async_load[? "steam_id_owner"];
mOwnerAccountId = async_load[? "account_id_owner"];
mPubFileId = async_load[? "published_file_id"];
mScore = async_load[? "score"];
}

Back: Steam API - User Generated Content
Next: steam_ugc_create_query_user

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_send_query

Sets whether to check the local cache for the query.

Syntax:

steam_ugc_send_query(ugc_query_handle);

Argument | Description
ugc_query_handle | The query handle to send.

Returns: Boolean

Description

This function can be used to send a query request. You first define the query using the appropriate steam_ugc_create_query_*() functions which will return a "query Handle". This handle is then used to set filters etc.... before being used in this funtion to send off the query request. The function returns a unique async ID value which can be used to check the details correctly in the Steam Async event. This event will have the async_load DS map which will be populated with the following key/value pairs:

  1. "id" - The async ID returned by the function that triggered the event

  2. "result" - The result of the operation (a real value). This will either be the GML constant ugc_result_success or some other real number. So you should check for this constant to ensure that the call was successful, and if otherwise somthing has not worked correctly. The rest of the possible values returned are shown as the result of the Steam "EResult" value and you should see steamclientpublic.h in the SDK headers for all 89 possible values.

  3. "event_type" - The string "ugc_query"

  4. "num_results" - The number of results returned (max 50 )

  5. "total_matching" - The total number of matching results

  6. "cached_data" - Indicates whether this data was retrieved from the local on-disk cache or not (will be either true or false)

  7. "results_list" - A DS list index index, where each list entry is a DS Map index containing details of the particular item

When you get the async event type "ugc_query", you can then parse the results list and extract the following information from each of the DS maps (one map per item in the list):

  1. "published_file_id"" -Holds the unique published file id for the item

  2. "file_type" - The type of file used

  3. "creator_app_id" - The Steam ID of the item creator

  4. "consumer_app_id" - The Steam ID of the item consumer

  5. "title" - The title of the item

  6. "description" - The description of the item

  7. "steam_id_owner" - The Steam ID of the item owner

  8. "time_created" - The time the item was first created

  9. "time_updated" - The last time the item was updated

  10. "time_added_to_user_list" - The time that the item was subscribed to

  11. "visibility" - The visibility of the item (see steam_ugc_set_item_visibility() for the returned constants)

  12. "banned" - Whether the item has been banned (true) or not (false)

  13. "accepted_for_use" - Whether the item has been accepted for use (true) or not (false)

  14. "tags_truncated" - Short version of the tags as an array

  15. "tags" - A string containing the tags for the item, each one separated by a comma

  16. "handle_file" - The unique file handle for the item

  17. "handle_preview_file" - The unique handle for the image preview for the item (can be used as an argument with steam_ugc_download() to download a preview image)

  18. "filename" - The name of the item file

  19. "file_size" - The size of the item file

  20. "preview_file_size" - The size of the preview image

  21. "url" - The full URL for the item

  22. "votes_up" - The number of up-votes received

  23. "votes_down" - The number of down-votes received

  24. "score" - The overall score of the item

  25. "account_id_owner" - The account ID from the Steam ID owner (this can be used in the function steam_ugc_create_query_user_ex())

Example:

var query_handle = steam_ugc_create_query_all(ugc_query_RankedByTrend, ugc_match_Items, 1);
steam_ugc_query_add_required_tag(query_handle, "RPG");
steam_ugc_query_set_return_long_description(query_handle, true);
steam_ugc_query_set_allow_cached_response(query_handle, true);
query_ID = steam_ugc_send_query(query_handle);

The above code creates a query request and stores it's handle in a local variable for future use in the rest of the functions which further define the query request before sending the query.

Back: Steam API - User Generated Content
Next: steam_ugc_create_item

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_set_item_content

Set (or update) the content path for the given item handle.

Syntax:

steam_ugc_set_item_content(ugc_update_handle, content);

Argument | Description
ugc_update_handle | The unique handle for the UGC to be updated.
content | The content (a path) to be used for the item.

Returns: Boolean

Description

This function will set the content path to be used for the given item, and it should be a relative path to the folder which contains the content files to upload - which in turn should be in the save are or the game bundle (ie: an included file). The update handle is the value returned when you called the function steam_ugc_start_item_update. The function will return true if the API was successfully accessed and false if there was an issue.

Example:

var app_id = steam_get_app_id();
var updateHandle = steam_ugc_start_item_update(app_id, global.Publish_ID);
steam_ugc_set_item_title(updateHandle, "My workshop item(3)!");
steam_ugc_set_item_description( updateHandle, "testing workshop...");
steam_ugc_set_item_visibility(updateHandle, ugc_visibility_public);
var tagArray;
tagArray[0] = "Test";
tagArray[1] = "New";
steam_ugc_set_item_tags(updateHandle, tagArray);
steam_ugc_set_item_preview(updateHandle, "promo.jpg");
steam_ugc_set_item_content(updateHandle, "WorkshopContent1");
requestId = steam_ugc_submit_item_update(updateHandle, "Version 1.2");

The above code gets the game ID, then uses that along with a previously stored published file ID to generate an update handle for the item. This handle is then used to update various pieces of information before the update is pushed to the Workshop servers.

Back: Steam API - User Generated Content
Next: steam_ugc_set_item_preview

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_set_item_description

Set (or update) the description for the given item handle.

Syntax:

steam_ugc_set_item_description(ugc_update_handle, description);

Argument | Description
ugc_update_handle | The unique handle for the UGC to be updated.
description | The description (a string - max 8000 characters) to be used for the item.

Returns: Boolean

Description

This function will set the description to be used for the given item. The description should be a string and the update handle is the value returned when you called the function steam_ugc_start_item_update. The function will return true if the API was successfully accessed and false if there was an issue.

Example:

var app_id = steam_get_app_id();
var updateHandle = steam_ugc_start_item_update(app_id, global.Publish_ID);
steam_ugc_set_item_title(updateHandle, "My workshop item(3)!");
steam_ugc_set_item_description( updateHandle, "testing workshop...");
steam_ugc_set_item_visibility(updateHandle, ugc_visibility_public);
var tagArray;
tagArray[0] = "Test";
tagArray[1] = "New";
steam_ugc_set_item_tags(updateHandle, tagArray);
steam_ugc_set_item_preview(updateHandle, "promo.jpg");
steam_ugc_set_item_content(updateHandle, "WorkshopContent1");
requestId = steam_ugc_submit_item_update(updateHandle, "Version 1.2");

The above code gets the game ID, then uses that along with a previously stored published file ID to generate an update handle for the item. This handle is then used to update various pieces of information before the update is pushed to the Workshop servers.

Back: Steam API - User Generated Content
Next: steam_ugc_set_item_visibility

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_set_item_preview

Set (or update) the preview image for the given item handle.

Syntax:

steam_ugc_set_item_preview(ugc_update_handle, preview);

Argument | Description
ugc_update_handle | The unique handle for the UGC to be updated.
preview | The preview image (JPG, GIF or PNG - max size 1MB) to be used for the item.

Returns: Boolean

Description

This function will set the preview image to be used for the given item. The image should be supplied as either a PNG, JPG or GIF format file with a maximum size of 1MB. The path to the image should be a relative path in the save are or the game bundle (ie: an included file). The update handle is the value returned when you called the function steam_ugc_start_item_update. The function will return true if the API was successfully accessed and false if there was an issue.

Example:

var app_id = steam_get_app_id();
var updateHandle = steam_ugc_start_item_update(app_id, global.Publish_ID);
steam_ugc_set_item_title(updateHandle, "My workshop item(3)!");
steam_ugc_set_item_description( updateHandle, "testing workshop...");
steam_ugc_set_item_visibility(updateHandle, ugc_visibility_public);
var tagArray;
tagArray[0] = "Test";
tagArray[1] = "New";
steam_ugc_set_item_tags(updateHandle, tagArray);
steam_ugc_set_item_preview(updateHandle, "promo.jpg");
steam_ugc_set_item_content(updateHandle, "WorkshopContent1");
requestId = steam_ugc_submit_item_update(updateHandle, "Version 1.2");

The above code gets the game ID, then uses that along with a previously stored published file ID to generate an update handle for the item. This handle is then used to update various pieces of information before the update is pushed to the Workshop servers.

Back: Steam API - User Generated Content
Next: steam_ugc_submit_item_update

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_set_item_tags

Set (or update) the tags for the given item handle.

Syntax:

steam_ugc_set_item_tags(ugc_update_handle, tags);

Argument | Description
ugc_update_handle | The unique handle for the UGC to be updated.
tags | The tags (as an array) to be used for the item.

Returns: Boolean

Description

This function will set the tags to be used for the given item. The tags should be added to a 1D array as string elements and the array passed to the function. The update handle is the value returned when you called the function steam_ugc_start_item_update. The function will return true if the API was successfully accessed and false if there was an issue.

Example:

var app_id = steam_get_app_id();
var updateHandle = steam_ugc_start_item_update(app_id, global.Publish_ID);
steam_ugc_set_item_title(updateHandle, "My workshop item(3)!");
steam_ugc_set_item_description( updateHandle, "testing workshop...");
steam_ugc_set_item_visibility(updateHandle, ugc_visibility_public);
var tagArray;
tagArray[0] = "Test";
tagArray[1] = "New";
steam_ugc_set_item_tags(updateHandle, tagArray);
steam_ugc_set_item_preview(updateHandle, "promo.jpg");
steam_ugc_set_item_content(updateHandle, "WorkshopContent1");
requestId = steam_ugc_submit_item_update(updateHandle, "Version 1.2");

The above code gets the game ID, then uses that along with a previously stored published file ID to generate an update handle for the item. This handle is then used to update various pieces of information before the update is pushed to the Workshop servers.

Back: Steam API - User Generated Content
Next: steam_ugc_set_item_content

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_set_item_title

Set (or update) the title for the given item handle.

Syntax:

steam_ugc_set_item_title(ugc_update_handle, title);

Argument | Description
ugc_update_handle | The unique handle for the UGC to be updated.
title | The title (a string - max 128 characters) to be used for the item.

Returns: Boolean

Description

This function will set the title to be used for the given item. The title should be a string and the update handle is the value returned when you called the function steam_ugc_start_item_update. The function will return true if the API was successfully accessed and false if there was an issue.

Example:

var app_id = steam_get_app_id();
var updateHandle = steam_ugc_start_item_update(app_id, global.Publish_ID);
steam_ugc_set_item_title(updateHandle, "My workshop item(3)!");
steam_ugc_set_item_description( updateHandle, "testing workshop...");
steam_ugc_set_item_visibility(updateHandle, ugc_visibility_public);
var tagArray;
tagArray[0] = "Test";
tagArray[1] = "New";
steam_ugc_set_item_tags(updateHandle, tagArray);
steam_ugc_set_item_preview(updateHandle, "promo.jpg");
steam_ugc_set_item_content(updateHandle, "WorkshopContent1");
requestId = steam_ugc_submit_item_update(updateHandle, "Version 1.2");

The above code gets the game ID, then uses that along with a previously stored published file ID to generate an update handle for the item. This handle is then used to update various pieces of information before the update is pushed to the Workshop servers.

Back: Steam API - User Generated Content
Next: steam_ugc_set_item_description

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_set_item_visibility

Set (or update) the visibility of the given item handle.

Syntax:

steam_ugc_set_item_visibility(ugc_update_handle, visibility);

Argument | Description
ugc_update_handle | The unique handle for the UGC to be updated.
visibility | The visibility (a constant, listed below) to be used for the item.

Returns: Boolean

Description

This function will set the visibility of the given item, set using one of the following constants:

Constant | Description
ugc_visibility_public | Set the item to be publicly visible
ugc_visibility_friends_only | Set the item to be visible to only people on the users friends list
ugc_visibility_private | Set the item to be private

The update handle is the value returned when you called the function steam_ugc_start_item_update, and function will return true if the API was successfully accessed and false if there was an issue.

Example:

var app_id = steam_get_app_id();
var updateHandle = steam_ugc_start_item_update(app_id, global.Publish_ID);
steam_ugc_set_item_title(updateHandle, "My workshop item(3)!");
steam_ugc_set_item_description( updateHandle, "testing workshop...");
steam_ugc_set_item_visibility(updateHandle, ugc_visibility_public);
var tagArray;
tagArray[0] = "Test";
tagArray[1] = "New";
steam_ugc_set_item_tags(updateHandle, tagArray);
steam_ugc_set_item_preview(updateHandle, "promo.jpg");
steam_ugc_set_item_content(updateHandle, "WorkshopContent1");
requestId = steam_ugc_submit_item_update(updateHandle, "Version 1.2");

The above code gets the game ID, then uses that along with a previously stored published file ID to generate an update handle for the item. This handle is then used to update various pieces of information before the update is pushed to the Workshop servers.

Back: Steam API - User Generated Content
Next: steam_ugc_set_item_tags

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_start_item_update

Add or update a UGC item to the Steam Workshop.

Syntax:

steam_ugc_start_item_update(consumer_app_id, published_file_id);

Argument | Description
consumer_app_id | The unique App ID for your game on Steam.
published_file_id | The unique published file ID value for the item.

Returns: Handle

Description

This function must be called before adding or updating information on a UGC item. You need to supply the unique App ID for your game on Steam, along with the unique published file ID that was returned for the item when you created it using the function steam_ugc_create_item. The function will return a unique update handle for the item, which you can then use in the UGC item functions to update (or add) information for uploading.

Example:

var app_id = steam_get_app_id();
var updateHandle = steam_ugc_start_item_update(app_id, global.Publish_ID);
steam_ugc_set_item_title(updateHandle, "My workshop item(3)!");
steam_ugc_set_item_description( updateHandle, "testing workshop...");
steam_ugc_set_item_visibility(updateHandle, ugc_visibility_public);
var tagArray;
tagArray[0] = "Test";
tagArray[1] = "New";
steam_ugc_set_item_tags(updateHandle, tagArray);
steam_ugc_set_item_preview(updateHandle, "promo.jpg");
steam_ugc_set_item_content(updateHandle, "WorkshopContent1");
requestId = steam_ugc_submit_item_update(updateHandle, "Version 1.2");

The above code gets the game ID, then uses that along with a previously stored published file ID to generate an update handle for the item. This handle is then used to update various peices of information before the update is pushed to the Workshop servers.

Back: Steam API - User Generated Content
Next: steam_ugc_set_item_title

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_submit_item_update

Submit (or update) an item.

Syntax:

steam_ugc_submit_item_update(ugc_update_handle, change_note);

Argument | Description
ugc_update_handle | The unique handle for the UGC to be updated.
change_note | The change notes (a string) to be used for the item.

Returns: Async ID

Description

This function will submit the UGC item inexed by the given handle to the Steam Workshop servers, adding the change notes to be used for the given item. The change notes should be a string and the update handle is the value returned when you called the function steam_ugc_start_item_update. When using this function it will return an async ID value which can then be parsed when the Steam Asynchronous event is triggered to report the creation of the item. The event will contain the following key/map values in the async_load ds_map:

  1. "id" - The async ID returned by the calling function

  2. "result" - The result of the operation (a real value). This will either be the GML constant ugc_result_success or some other real number. So you should check for this constant to ensure that the call was successful, and if otherwise somthing has not worked correctly. The rest of the possible values returned are shown as the result of the Steam "EResult" value and you should see steamclientpublic.h in the SDK headers for all 89 possible values.

  3. "event_type" - This key will hold the value "ugc_update_item"

  4. "legal_agreement_required" - Will be true or false (see the Steam docs for more details)

Example:

var app_id = steam_get_app_id();
var updateHandle = steam_ugc_start_item_update(app_id, global.Publish_ID);
steam_ugc_set_item_title(updateHandle, "My workshop item(3)!");
steam_ugc_set_item_description( updateHandle, "testing workshop...");
steam_ugc_set_item_visibility(updateHandle, ugc_visibility_public);
var tagArray;
tagArray[0] = "Test";
tagArray[1] = "New";
steam_ugc_set_item_tags(updateHandle, tagArray);
steam_ugc_set_item_preview(updateHandle, "promo.jpg");
steam_ugc_set_item_content(updateHandle, "WorkshopContent1");
requestId = steam_ugc_submit_item_update(updateHandle, "Version 1.2");

The above code gets the game ID, then uses that along with a previously stored published file ID to generate an update handle for the item. This handle is then used to update various pieces of information before the update is pushed to the Workshop servers.

Back: Steam API - User Generated Content
Next: steam_ugc_get_item_update_progress

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_subscribe_item

Subscribe to a given UGC item.

Syntax:

steam_ugc_subscribe_item(published_file_id);

Argument | Description
published_file_id | The unique file ID for the UGC to subscribe to.

Returns: Async ID

Description

This function can be used to subscribe to a UGC item. You supply the published file ID and then the function returns a unique async ID value which can be used to check when the subscribed item has been downloaded in the Steam Async event. This event will have the async_load DS map which will be populated with the following key/value pairs:

  1. "id" - The async ID returned by the function that triggered the event

  2. "result" - The result of the operation (a real value). This will either be the GML constant ugc_result_success or some other real number. So you should check for this constant to ensure that the call was successful, and if otherwise somthing has not worked correctly. The rest of the possible values returned are shown as the result of the Steam "EResult" value and you should see steamclientpublic.h in the SDK headers for all 89 possible values.

  3. "event_type" - The string "ugc_subscribe_item".

  4. "published_file_id" - The unique ID for the published item.

Example:

steam_sub = steam_ugc_subscribe_item(global.pubFileID);

The above code will subscribe (and download) the item with the file ID stored in the global variable "pubFileID".

Back: Steam API - User Generated Content
Next: steam_ugc_unsubscribe_item

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


steam_ugc_unsubscribe_item

Unsubscribe from a given UGC item.

Syntax:

steam_ugc_unsubscribe_item(published_file_id);

Argument | Description
published_file_id | The unique file ID for the UGC to unsubscribe from.

Returns: Async ID

Description

This function can be used to unsubscribe from a UGC item. You supply the published file ID and then the function returns a unique async ID value which can be used to check that the item has been unsubscribed correctly in the Steam Async event. This event will have the async_load DS map which will be populated with the following key/value pairs:

  1. "id" - The async ID returned by the function that triggered the event

  2. "result" - The result of the operation (a real value). This will either be the GML constant ugc_result_success or some other real number. So you should check for this constant to ensure that the call was successful, and if otherwise somthing has not worked correctly. The rest of the possible values returned are shown as the result of the Steam "EResult" value and you should see steamclientpublic.h in the SDK headers for all 89 possible values.

  3. "event_type" - The string "ugc_unsubscribe_item".

  4. "published_file_id" - The unique ID for the published item.

Example:

steam_sub = steam_ugc_subscribe_item(global.pubFileID);

The above code will subscribe (and download) the item with the file ID stored in the global variable "pubFileID".

Back: Steam API - User Generated Content
Next: steam_ugc_num_subscribed_items

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Strings

The following functions exist that deal with Strings.

At some time when making your game you will need to use text. Text in games is dealt with by using the string functions (a string is just another way of saying a line of text) and GameMaker: Studio has a complete set of functions that permit you to manipulate strings in many ways, including the insertion of one string in another, the copying of strings and the ability to parse strings for the digits or the letters that they contain.

It is worth noting that there are certain conventions that you can use when creating strings. You can, for example, create a string with quotes using the single quotation marks like this: "...and so Sam said 'Hi there!'". You can also force a line break using the # symbol or by adding a new line in the string creation like this:

str = "Hello#World";

// or

str = "Hello
World";

If you need to actually draw the "#" symbol as part of the text, you can precede it using the "\" symbol like this:

str = "this will draw the \# symbol";

Another thing to note is that the unicode character 9647 (▯) is used to substitute any missing glyphs that you may have in your designated font when rendering it in the draw event. So if your font doesn't have, for example, the ° symbol, then writing 90° will actually produce 90▯.

The following list of functions are all for dealing with strings:

  1. ansi_char
  2. chr
  3. ord
  4. real
  5. is_string
  6. string
  7. string_byte_at
  8. string_byte_length
  9. string_set_byte_at
  10. string_char_at
  11. string_ord_at
  12. string_copy
  13. string_count
  14. string_delete
  15. string_digits
  16. string_format
  17. string_insert
  18. string_length
  19. string_letters
  20. string_lettersdigits
  21. string_lower
  22. string_pos
  23. string_repeat
  24. string_replace
  25. string_replace_all
  26. string_upper
  27. string_height
  28. string_height_ext
  29. string_width
  30. string_width_ext

Other than those functions that relate specifically to strings, the Windows target also permits you to use access the clipboard to get and set text information:

  1. clipboard_has_text
  2. clipboard_get_text
  3. clipboard_set_text

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ansi_char

Returns a string containing the character with raw BYTE value set.

Syntax:

ansi_char(val);

Argument | Description
val | The raw byte value.

Returns: String (Single character)

Description

This function returns a string containing the character with raw BYTE value set. This will not, and should not, be displayed, but it will save correctly to disk for use in encoding.

Back: Strings
Next: chr

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


chr

Returns a string containing the character with the given Unicode code.

Syntax:

chr(val);

Argument | Description
val | The Unicode code to get the string from.

Returns: String

Description

This function returns a string containing the character which relates to the input Unicode code for displaying. This character depends on the current drawing font's character set codepage and if no font is set, it will use the default code page for the machine.

Example:

mystring = chr(53) + chr(48);

This would set mystring to "50" (a string, not an integer) as chr(53) is "5" and chr(48) is "0".

Back: Strings
Next: ord

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clipboard_get_text

Returns the current text from the clipboard.

Syntax:

clipboard_get_text();

Returns: String

Description

This function will return a string of the text contained on the clipboard. if no text is stored it will return an empty string "".

NOTE: This function is only valid for the Windows target.

Example:

if clipboard_has_text()
{
str = clipboard_get_text();
clipboard_set_text("");
}

The above code checks the clipboard for text and if it contains any, it is read as a string into the variable "str". Finally the clipboard is cleared by setting it to an empty string.

Back: Strings
Next: clipboard_set_text

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clipboard_has_text

Returns whether there is any text in the clipboard.

Syntax:

clipboard_has_text();

Returns: Boolean

Description

This function will return true if the clipboard contains text or false if it does not.

NOTE: This function is only valid for the Windows target.

Example:

if clipboard_has_text()
{
str = clipboard_get_text();
clipboard_set_text("");
}

The above code checks the clipboard for text and if it contains any, it is read as a string into the variable "str". Finally the clipboard is cleared by setting it to an empty string.

Back: Strings
Next: clipboard_get_text

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


clipboard_set_text

Returns the current text from the clipboard.

Syntax:

clipboard_set_text(str);

Argument | Description
str | The text (as a string) to set the clipboard to hold.

Returns: N/A

Description

This function will set the clipboard to hold the defined string. You can set it to an empty string "" to effectively clear the clipboard of text.

NOTE: This function is only valid for the Windows target.

Example:

if clipboard_has_text()
{
str = clipboard_get_text();
clipboard_set_text("");
}

The above code checks the clipboard for text and if it contains any, it is read as a string into the variable "str". Finally the clipboard is cleared by setting it to an empty string.

Back: Strings
Next: clipboard_has_text

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


ord

Returns the Unicode value code of the first character in the given string.

Syntax:

ord(str);

Argument | Description
str | The string with which to find the Unicode code.

Returns: Real

Description

This function takes a string (of a single character only) and returns the Unicode value for that character. In this way you can, for example, store as integers individual key presses, and it is most commonly used by the keyboard_check() functions.

Example:

if keyboard_check(ord("W"))
{
y -= 4;
}

This will move the calling instance four pixels upwards if the key W is held down.

Back: Strings
Next: real

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


real

Takes a string and returns it into a real number.

Syntax:

real( str );

Argument | Description
str | The string to be converted to a real value.

Returns: Real

Description

This function can be used to turn a given string into a real number. When using this function, numbers, minus signs, decimal points and exponential parts in the string are taken into account, while other characters (such as letters) will cause an error to be thrown. If you know, or suspect, that a string may have other characters then you can use string_digits() to remove all non-numeric characters, before using this function to turn the resulting string into a real number.

Example:

var t_str;
t_str = string_digits(input_str);
age = real(t_str);

The above code will take the input string, strip it of all characters other than numbers and then set the variable "age" to hold the real number value of the return string.

Back: Strings
Next: is_string

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string

Turns a real number into a string.

Syntax:

string(realNum);

Argument | Description
realNum | The real number to be turned into a string.

Returns: String

Description

With this function you can turn any real number into a string. If the real number is an integer, it will be saved with no decimal places, otherwise, it will be saved with two decimal places.

Example:

draw_text(100, 100, "Score: " + string(score) + " / Health: " + string(health));

The above code uses the string function to draw both real numbers and strings together (draw will only accept either a string or a real, but not both).

Back: Strings
Next: string_byte_at

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_byte_at

Returns the raw byte value as a real value at a given position in the given string.

Syntax:

string_byte_at(str, index);

Argument | Description
str | The string to check.
index | The position to get the byte from.

Returns: Real

Example:

newbyte = string_byte_at("Hello World", 6);

This will set newbyte to the value of the sixth byte of "Hello World".

Back: Strings
Next: string_byte_length

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_byte_length

Returns the number of bytes in a string.

Syntax:

string_byte_length( str );

Argument | Description
str | The string to measure the number of bytes of.

Returns: Real

Description

This function returns the number of bytes in a string, but you should note that due to their being held as UTF8, this will not be equal to their string length.

Example:

bytesize = string_byte_length("Hello World");

This would set bytesize to the number of bytes in "Hello World".

Back: Strings
Next: string_set_byte_at

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_char_at

Checks a given string and returns the character at a given position.

Syntax:

string_char_at(str, index);

Argument | Description
str | The string to check.
index | The position to get the character from.

Returns: String

Description

You can use this function to return a specific character at a specific position within a string, with the index starting at 1 for the first character. If no character is found or the string is shorter than the value given to index, an empty string "" is returned.

Example:

str1 = "Hello World";
str2 = string_char_at(str1, 7);

This will set str2 to the seventh character ("H" counting as the 1st) in string str1, in this case "W".

Back: Strings
Next: string_ord_at

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_copy

Returns all or part of another string.

Syntax:

string_copy(str, index, count);

Argument | Description
str | The string to copy from.
index | The position of the first character in the string to copy from (numbered from 1)
count | The number of characters, starting from the position of the first, to copy

Returns: string

Description

With this function you can easily select a number of characters from within a string to be copied to another one. The first character in a string is always numbered as "1", so to copy (for example) the first five characters of string you would have string_copy(str, 1, 5). A further example is provided below.

Example:

name = keyboard_string;
if string_length(name) > 15 )
{
keyboard_string = string_copy(name, 1, 15 );
}

The above code will allow the player to input a string through the keyboard which is then stored in the variable "name". This variable is then checked to see if it exceeds the maximum length of 15 characters and if it does, the keyboard_string is replaced by a 15 character copy of the "name" string. This effectively limits the player input to 15 characters.

Back: Strings
Next: string_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_count

Returns the number of instances of a substring found within a given string.

Syntax:

string_count(substr, str);

Argument | Description
substr | The substring to check the string for.
str | The string to check.

Returns: Real

Description

This function will return the amount of times the given substring appears within a specific string. In this way you can check for how many times a single letter or a phrase is repeated in a section of stored text.

Example:

str1 = "Hello World";
ocount = string_count( "o", str1 );

This will set ocount to the number of "o"s in str1, in this case 2.

Back: Strings
Next: string_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_delete

Returns a copy of a given string with a selected section deleted.

Syntax:

string_delete(str, index, count);

Argument | Description
str | The string to copy and delete from.
index | The position of the first character to remove.
count | The number of characters to remove.

Returns: String

Description

You can use this function to remove a specific part of a string. So, you supply the input string and the start and end position within that string to remove characters (index starts at 1) and the function will return a new string without that section in it.

Example:

str1 = "Helloo World";
str2 = string_delete(str1, 5, 1);

This will set str2 to "Hello World", as it removes the extra "o" from "Hello", ie: the string counts along from the first letter 5 places, then deletes 1 character).

Back: Strings
Next: string_digits

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_digits

Returns a copy of a given string with everything but its digits removed.

Syntax:

string_digits( str );

Argument | Description
str | The string to get the digits from.

Returns: String

Description

You can use this function to parse a given string and get any numbers from it. For example, say you have this text - "I am 81 years old". With this function you would get a return string of "81".

Example:

var t_str;
t_str = string_digits(input_str);
age = real(t_str);

The above code will take the input string, strip it of all characters other than numbers and then set the variable "age" to hold the real number value of the return string.

Back: Strings
Next: string_format

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_format

Turns a real number into a string using your own formatting.

Syntax:

string_format(val, tot, dec);

Argument | Description
val | The real number to be turned into a string.
tot | The total number of places of the main number to be shown. Zeroes or spaces will be inserted to match this.
dec | The number of decimal places to be included.

Returns: String

Description

Turns a real number into a string using your own formatting, where you can choose how many "places" are saved to the string and how many decimal places are saved also. Both can be very handy, some games prefer to display a score as a set number of digits, while control over decimal places can be good for a high accuracy the two decimal places of string() cannot provide. If the number of places specified is greater than the value to be shown and/or the number plus the decimal places that have been specified is less than the total places, then spaces will be added before the value to make up the difference (see the example below). Zeros will be added to the right of the decimal point if the value given is less than the total and the number of decimal places to include.

Example:

str1 = string_format(1234, 8, 0);
str2 = string_format(pi, 1, 10);
str3 = string_format(pi, 5, 5);

This will set str1 to " 1234", str2 to "3.1415926535" and str3 to " 3.14159".

Back: Strings
Next: string_insert

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_height

Returns the height in pixels of a string.

Syntax:

string_height(string);

Argument | Description
string | The string to measure the height of.

Returns: Real

Description

This function will return the height (in pixels) of the input string. It is very handy for calculating distances between text elements based on the tallest of the letters that make up the string as it would be drawn with draw_text using the currently defined font.

Example:

var hh;
hh = string_height("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
draw_text(32, 32, string(score));
draw_text(32, 32 + hh, string(lives);

The above code will get the height of the given string and then draw two lines of text, using the returned string height as a separator.

Back: Strings
Next: string_height_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_height_ext

Returns the height in pixels of a string based on the given separation and line-break width.

Syntax:

string_height_ext(string, sep, w);

Argument | Description
string | The string to measure the height of.
sep | The distance in pixels between lines of text as if the string was being drawn.
w | The maximum width (in pixels) of the string before a line break as if the string was bring drawn.

Returns: Real

Description

This function will return the height (in pixels) of the input string, taking into account the line separation and line-break width (which is defined as the number of pixels that the string can occupy before a line break is inserted). It is very handy for calculating distances between text elements based on the tallest of the letters that make up the string as well as the actual string length itself when spread over several lines as it would be drawn with draw_text_ext using the currently defined font. Separation and width can be set to -1 to get the default spacing.

Example:

var hh;
hh = string_height_ext(str_Story_Text[1], -1, 100);
draw_text_ext(32, 32, str_Story_Text[1], -1, 100);
draw_text_ext(32, 32 + hh, str_Story_Text[2], -1, 100);

The above code will get the height of the given string, taking into account the line separation and line-break width, and then draw two lines of text, using the returned total string height as a separator.

Back: Strings
Next: string_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_insert

Returns a copy of a given string with a substring inserted into a chosen position.

Syntax:

string_insert(substr, str, index);

Argument | Description
substr | The substring to be inserted.
str | The string to be copied.
index | The position in characters of the string to insert the substring.

Returns: String

Description

With this function you can create a new string made up of two strings, where one has been inserted into the other at a given position. It can be useful, for example, to add a user name into a predefined text and so make the player of your game feel more involved in the action.

Example:

str2 = string_insert(username, "Hello, , how are you?", 7);

This will insert the string in the "username" variable into the given phrase with the resulting string looking like this: "Hello, NAME, how are you?".

Back: Strings
Next: string_length

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_length

Returns the number of characters comprising a given string.

Syntax:

string_length(str);

Argument | Description
str | The string to measure the number of characters of.

Returns: Real

Description

This function returns the number of characters comprising a given string. It can be useful for things like working out when to limit a custom text entry's character length (eg: capping a player's name to 10 characters). Remember that this is different to string_width in that it measures the number of characters in the string, not its width as drawn on the screen in pixels.

Example:

if string_length(name) > 10
{
name = string_copy(name, 1, 10);
}

This will check if the string of name is greater than ten characters and if it is, it will copy and use the first ten characters only.

Back: Strings
Next: string_letters

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_letters

Returns a copy of a given string with everything but its letters removed.

Syntax:

string_letters(str);

Argument | Description
str | The string to convert to letters.

Returns: String

Description

With this function you can remove all characters that are not classed as letters. This is handy for preventing people from entering unwanted characters into a text entry (like entering "#" to force a new line).

Note: This function only detects the 26 letter english alphabet from A - Z.

Example:

username = string_letters(username);

The above code will set the "username" variable to only hold the letter characters of the original string.

Back: Strings
Next: string_lettersdigits

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_lettersdigits

Returns a copy of a given string with everything but its letters and digits removed.

Syntax:

string_lettersdigits(str);

Argument | Description
str | The string to convert to letters and digits.

Returns: String

Description

This function will return a copy of a given string with everything but its letters and digits removed, which means it can be used to remove any unwanted characters (like "#" or "?") from, for example, a login name or a password.

Note: This function only detects the 26 letter english alphabet from A - Z.

Example:

if string_length(password) > string_length(string_lettersdigits(password))
{
draw_text(32,32,"Invalid Password! Only Letters and numbers please!");
}

The above code will check the length of a string against the length of the same string, but with all symbols removed. If they are not the same a message is drawn on the screen.

Back: Strings
Next: string_lower

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_lower

Returns a copy of a given string in all lowercase letters.

Syntax:

string_lower( str );

Argument | Description
str | The string to convert to lowercase.

Returns: String

Description

With this function you can force a string to contain only lower case characters.

Note: This function only detects the 26 letter english alphabet from A - Z.

Example:

str1 = "Hello World";
str2 = string_lower(str1);

This will set str2 to "hello world".

Back: Strings
Next: string_pos

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_ord_at

Checks a given string and returns the character code for the character at a given position.

Syntax:

string_ord_at(str, index);

Argument | Description
str | The string to check.
index | The position to get the character code from.

Returns: String

Description

You can use this function to return a specific character code at a specific position within a string, with the index starting at 1 for the first character. If no character is found or the string is shorter than the value given to index, an empty string "" is returned.

Example:

str = "Hello World";
char_code = string_ord_at(str1, 7);

This will get the character code for the seventh character (where "H" counts as the first) in string "str" and store it in the variable "char_code".

Back: Strings
Next: string_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_pos

Returns the position of a given sub-string in a string.

Syntax:

string_pos(substr, str);

Argument | Description
substr | The substring to look for in the string.
str | The string.

Returns: Real

Description

This function will return the character position of an instance of a sub-string within a string, or 0 if it's not found at all. One use for this is for filtering words that may be considered offensive, or for finding the correct place to insert some text into another string.

Example:

if string_pos(",", text) != 0
{
string_insert(name, text, string_pos(",", text));
}

The above code searches the string "text" for a comma, and if it finds one it inserts the substring "name" at that position.

Back: Strings
Next: string_repeat

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_repeat

Returns a copy of a given string repeated a given number of times.

Syntax:

string_repeat(str, count);

Argument | Description
str | The string to repeat.
count | The number of times to repeat the string.

Returns: String

Description

This function simply returns the same string repeated a given number of times over itself.

Example:

str1 = 'Hello World';
str2 = string_repeat(str1, 3);

This will set str2 to 'Hello WorldHello WorldHello World'.

Back: Strings
Next: string_replace

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_replace

Returns a copy of a string with the first instance of a given substring replaced with a new substring.

Syntax:

string_replace(str, substr, newstr);

Argument | Description
str | The string to be copied.
substr | The substring within the string to be replaced.
newstr | The new substring to replace the previous one.

Returns: String

Description

You can use this function to parse a string looking for a specific part, which can then be replaced by the new string that you have specified.

Example:

str1 = 'Hello Earth';
str2 = string_replace(str1, 'Earth', 'World');

This will set str2 to str1, but with its instance of 'Earth' replaced with 'World', resulting in str2 being 'Hello World'.

Back: Strings
Next: string_replace_all

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_replace_all

Returns a copy of a string with all instances of a given substring replaced with a new substring.

Syntax:

string_replace_all(str, substr, newstr);

Argument | Description
str | The string to be copied.
substr | The substring within the string to be replaced in all instances.
newstr | The new substring to replace the previous one(s).

Returns: String

Description

You can use this function to parse a string looking for specific parts, which can then be replaced by the new string that you have specified in all places that they occur.

Example:

str1 = 'Hexxo Worxd';
str2 = string_replace_all(str1, 'x', 'l');

This will set str2 to str1, but with its instances of 'x' replaced with 'l', resulting in str2 being 'Hello World'.

Back: Strings
Next: string_upper

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_set_byte_at

Set a byte in a string.

Syntax:

string_set_byte_at(str, pos, byte);

Argument | Description
str | The string to change the byte of.
pos | The position within the string (starting at 1) to change the byte of.
byte | The new byte value.

Returns:string

Description

This function sets a byte directly in a string (based on the UTF8 format) and returns a copy of the string with the changes.

NOTE: This function is incredibly slow so consider carefully whether it is necessary and where you use it.

Example:

str = string_set_byte_at("hello", 2, 97);

The above code would change the byte value of the second letter in the string, and so set the variable "str" to hold "hallo".

Back: Strings
Next: string_char_at

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_upper

Returns a copy of a given string in all uppercase (capital) letters.

Syntax:

string_upper( str );

Argument | Description
str | The string to convert to uppercase.

Returns: String

Description

With this function you can force a string to contain only upper case characters.

Note: This function only detects the 26 letter english alphabet from A - Z.

Example:

str1 = 'Hello World';
str2 = string_upper( str1 );

This will set str2 to 'HELLO WORLD'.

Back: Strings
Next: string_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_width

Returns the width in pixels of a given string.

Syntax:

string_width(string);

Argument | Description
string | The string to measure the width of.

Returns: Real

Description

This function will return the width (in pixels) of the input string. It is very handy for calculating distances between text elements based on the total width of the letters that make up the string as it would be drawn with draw_text using the currently defined font.

var ww;
ww = string_width(str_Name + " ");
draw_text(32, 32, str_Name));
draw_text(32 + ww, 32, "has won the game!");

The above code will get the width of the given string and then draw two lines of text, using the returned string width as a separator.

Back: Strings
Next: string_width_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


string_width_ext

Returns the maximum width in pixels of a string based on the given separation and line-break width.

Syntax:

string_width_ext(string, sep, w);

Argument | Description
string | The string to measure the width of.
sep | The distance in pixels between lines of text as if the string was being drawn.
w | The maximum width (in pixels) of the string before a line break as if the string was being drawn.

Returns: Real

Description

This function will return the maximum width (in pixels) of the input string, taking into account the line separation and line-break width (which is defined as the number of pixels that the string can occupy before a line break is inserted). It is very handy for calculating distances between text elements based on the maximum width of a string that is split over several lines as it would be drawn with draw_text_ext using the currently defined font. Separation and width can be set to -1 to get the default spacing.

Example:

var ww;
ww = string_width_ext(str_Story_Text[1], -1, 100);
draw_text_ext(32, 32, str_Story_Text[1], -1, 100);
draw_text_ext(32 + ww, 32, str_Story_Text[2], -1, 100);

The above code will get the width of the given string, taking into account the line separation and line-break width, and then draw two lines of text, using the returned total string width as a separator.

Back: Strings

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Surfaces

This section deals with the functions related to creating and manipulating surfaces.

In the normal draw events, GameMaker: Studio doesn't actually draw directly to the screen, but rather draws to a surface called the application surface. This surface is basically a blank "canvas" that can then later be manipulated before being drawn to the screen when needed, and in most cases GameMaker: Studio handles this for you (although you can also manipulate it yourself in code for shaders, scaling and many other things - further details are given below).

However, apart from this application surface, you can also create your own surfaces and use them to create stunning or subtle special effects in your game. For example, you can use surfaces to "catch" instances, which can then be destroyed, and in this way you can create a decal effect where the sprite for the instance is displayed on the surface as if it still existed, permitting graphical effects like debris, blood, etc... without any real processing overhead. Another thing you can do with surfaces is use them as textures to be manipulated, or to create sprites "on the fly", or to create complex overlays. in fact, the uses for surfaces are endless!

Normal surfaces are quite easy to use, but there are a few basic rules to be followed when you use them:

  • First, you should realise that surfaces (except the application surface) are "volatile". This means that if the device or window loses focus or is minimised (good examples are when a screensaver comes up in Windows, or on an Android device when the app loses focus due to a call) then the surface may be destroyed. This is because it is stored in the texture memory and may be overwritten when the target platform needs that memory for something else which means that you should always have some type of fail-safe code in place, usually with the surface_exists function.

  • Second, you should note that surfaces require large quantities of texture memory to be used, and so you should attempt to keep them as small as possible. Normally you would try and keep them no larger than the size of the view or display window.

  • Third, you should try to draw to surfaces in the draw event. This is not always possible, but due to the optimised way in which GameMaker: Studio draws to the screen, it is recommended that you keep all draw functions within the draw event.

  • Fourth, when drawing to a surface manually, the surface is always at the position of (0,0). This means that you may need to convert absolute coordinates into local coordinates for the surface. For example, if you have a view-sized surface and wish to draw something that is currently in view to that surface, you should subtract the view x and y coordinates from the actual x and y coordinates to get a relative position to the surface (0,0) position. So, the code would look something like this:

    if view_current = 0
    {
    surface_set_target(surf);
    with (obj_Effect)
    {
    draw_sprite(sprite_index, image_index, x - view_xview[1], y - view_yview[1]);
    }
    surface_reset_target();
    }
    else
    {
    draw_surface(surf, 0, 0);
    }

The basic use of a surface would be as follows - You first create a surface and assign its index to a variable. You would then set the drawing target to the surface rather than the display and draw the things you wish as well as perform any other manipulations. Once you are done you reset the drawing target so that all further drawing happens on the screen again. One thing to note is that should you require drawing the whole display to a surface (including tiles, backgrounds etc...) you can simply access the application surface itself (see below for further details) or you could assign a surface to a view using the variable view_surface_id[0..7]as with this all that is visible in that view will be drawn to the corresponding surface.

The following functions exist to deal with surfaces:

  1. surface_exists
  2. surface_create
  3. surface_create_ext
  4. surface_resize
  5. surface_set_target
  6. surface_set_target_ext
  7. surface_reset_target
  8. surface_copy
  9. surface_copy_part
  10. surface_get_height
  11. surface_get_width
  12. surface_get_texture
  13. surface_getpixel
  14. surface_getpixel_ext
  15. surface_free
  16. surface_save
  17. surface_save_part

These functions are specific for creating and manipulating surfaces, but to actually draw them to the screen you should be using the specific draw functions that can be found in the section on Drawing Surfaces.

The Application Surface

As mentioned above, all normal drawing in your game is done on the application surface, and this surface can be changed and manipulated just like a normal surface. However, it is not a normal surface and advanced users will find that it enables complete control over how and when things are drawn in GameMaker: Studio. For more details, as well as specific functions for this feature, please see the following section:

  1. The Application Surface

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


application_get_position

Get the position for default drawing of the application surface.

Syntax:

application_get_position();

Returns: Array

Description

When you have "maintain aspect ratio" ticked in the Global Game Settings for a target platform, GameMaker: Studio will automatically set the draw position for the application surface so that it is displayed correctly centered and scaled on the given display. However if you are manipulating this surface and wish to draw it yourself, then this function gives you an easy way to find exactly where within the display or window that the surface was being drawn so that you can then draw it there yourself, or align GUI images or post draw images to it.

The function will return an array with four keys, where key 0 and 1 are the x and y position of the top lefthand corner of the surface, and keys 2 and 3 are the x and y of the bottom righthand corner of the surface, all relative to the size of the display or window.

Example:

var a = application_get_position();
xx = a[0];
yy = a[1];
ww = a[2] - a[0];
hh = a[3] - a[1];

The above code will get the position of the application surface, as well as the absolute width and height in relation to the display window, and store them in four variables for future use.

Back: Surfaces
Next: application_surface_draw_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


application_surface

A global variable that is used to get access to the application surface index.

Syntax:

application_surface;

Returns: Pointer

Description

This global scope, built-in variable can be used to access the application surface using any of the surface functions. This surface is permanently available and is where the bulk of drawing is done by GameMaker: Studio.

Example:

surface_resize(application_surface, display_get_gui_width(), display_get_gui_height());

The above code will resize the application surface to have a 1:1 ratio with the GUI layer.

Back: Surfaces
Next: application_surface_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


application_surface_draw_enable

Enable or disable the automatic drawing of the application surface.

Syntax:

application_surface_draw_enable(flag);

Argument | Description
flag | The flag will be either true (enabled, the default value) or false (disabled).

Returns: N/A

Description

You can use this function to enable or disable the automatic drawing of the application surface. By default this is enabled, but in many cases you will want to take over when and how the surface is drawn (when using shaders for example), in which case you would use this function to set it to false so that you can draw it yourself when and how you require.

Example:

application_surface_draw_enable(false);

The above code will switch off the automatic drawing of the application surface.

Back: Surfaces
Next: application_surface

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


application_surface_enable

Enable or disable the use of the application surface.

Syntax:

application_surface_enable(enable);

Argument | Description
enable | Set to enable (true) or disable (false) the application surface.

Returns: N/A

Description

With this function you can enable or disable the application surface. By default the application surface is enabled and all drawing for the Draw events will be done to that and the surface drawn to the screen. However on some older devices and specific chipsets this may result in poorer performance. In those cases you can switch off drawing to the application surface and all Draw event drawing will then be done directly to the screen buffer.

You can use this function to enable or disable the application surface at any time in your game, but you should note that it requires at least one frame (step) for the changes to take effect. Switching it off will switch off all aspect ratio correction, as set in the Global Game Settings for the target platform. This means that you should have some method in place that scales the game to the required device, window or screen dimensions. If you switch it back on again, then the Global Game Settings will take effect again the next step.

It is recommended that you use this function carefully as it will impact on how everything is drawn to the screen. In general you would want to have it as an option in a menu of your game, or call it only once at the start of your game and write your code around whether you have it enabled or disabled.

Example:

if keyboard_check_pressed(vk_space)
{
if application_surface_is_enabled()
{
application_surface_enable(false);
}
else
{
application_surface_enable(true);
}
}

The above code check for a key press and the toggle the application surface on or off depending on its state (like in an options menu).

Back: Surfaces
Next: application_surface_is_enabled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


application_surface_is_enabled

Returns whether the application surface is enabled or not.

Syntax:

application_surface_is_enabled();

Returns: Boolean

Description

This function will return true if the application surface is being used for drawing, or false if the screen buffer is being used.

Example:

if keyboard_check_pressed(vk_space)
{
if application_surface_is_enabled()
{
application_surface_enable(false);
}
else
{
application_surface_enable(true);
}
}

The above code check for a key press and the toggle the application surface on or off depending on its state (like in an options menu).

Back: Surfaces
Next: application_get_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_copy

Copies a source surface into a destination surface.

Syntax:

surface_copy(destination, x, y, source);

Argument | Description
destination | The ID of the surface to copy the other surface to.
x | The x position to copy to.
y | The y position to copy to.
source | The ID of surface to be copied.

Returns: N/A

Description

This function simply takes the image from one surface and copies it onto another one at the specified local position within that surface (where the (0,0) position is the top left corner of the destination surface). If the destination surface already has information this will be overwritten by the copy, and the function does not change the source surface in any way.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

if view_current == 0
{
surface_copy(surf, 0, 0, temp_surf);
}
else
{
draw_surface(surf, 0, 0);
}

The above code will check the current view being drawn and if it is view[0] it copies the surface indexed in the variable "temp_surf" onto the surface indexed in the variable "surf". If the current view is anything other than view[0] the surface "surf" is drawn to the screen.

Back: Surfaces
Next: surface_copy_part

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_copy_part

Copies part of a source surface onto a destination surface (without any form of blending.)

Syntax:

surface_copy_part(destination, x, y, source, xs, ys, ws, hs);

Argument | Description
destination | The ID of the surface to copy the other surface to.
x | The x position to copy to.
y | The y position to copy to.
source | The ID of the surface to be copied.
xs | The x position in the source surface to copy from.
ys | The y position in the source surface to copy from.
ws | The width of the area in the source surface to copy from.
hs | The height of the area in the source surface to copy from.

Returns: N/A

Description

This function simply takes the image from one surface and copies it onto another one at the specified local position within that surface (where the (0,0) position is the top left corner of the destination surface). You can specify a local x and y position to copy from as well as the width and height of the section. Please note that these are coordinates based on the surface size and not on the position at which the surface is being drawn in the room (see the main page on Surfaces for further information). If the destination surface already has information this will be overwritten by the copy, and the function does not change the source surface in any way.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

if view_current == 0
{
surface_copy_part(surf, 0, 0, temp_surf, 0, 0, view_xview[1] - mouse_x, view_yview[1] - mouse_y);
}
else
{
draw_surface(surf, 0, 0);
}

The above code will check the current view being drawn and if it is view[0] it copies the surface indexed in the variable "temp_surf" onto the surface indexed in the variable "surf". the area copied corresponds to a rectangle formed by the relative position of the mouse within the surface as it would be drawn in view[1]. If the current view is anything other than view[0] the surface "surf" is drawn to the screen.

Back: Surfaces
Next: surface_get_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_create

Creates a surface.

Syntax:

surface_create(w, h);

Argument | Description
w | The width of the surface to be created.
h | The height of the surface to be created.

Returns: Real

Description

This function is used to create a surface and will return the index of the surface which should be stored in a variable for future function calls. When the surface is first created, it may contain "noise" as basically it is just an area of memory that is put aside for the purpose (and that memory may still contain information), so you may want to clear the surface before use with a function like draw_clear_alpha.

It is highly recommended that all surfaces be created with a size that is a power of 2, ie: 16, 128, 512 or 1024 pixels in size, for example. This is not exactly necessary on certain platforms (like Windows and MacOS) but it will certainly increase compatibility on those targets, while for HTML5 and devices it is essential and very it's important that you remember this or you may run into problems later.

Example:

if !surface_exists(surf)
{
surf = surface_create(1024, 1024);
surface_set_target(surf);
draw_clear_alpha(c_black, 0);
surface_reset_target();
view_surface_id[0] = surf;
}

The above code checks to see if a surface exists and if it does not it will create a surface that is 1024 pixels wide and 1024 pixels high, assigning the index to the variable "surf". The drawing target is then set to the new surface, which is cleared and made transparent before having the drawing target reset to the display. Finally the surface is assigned to a view.

Back: Surfaces
Next: surface_create_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_create_ext

Creates a surface and links it to an HTML5 canvas element.

Syntax:

surface_create_ext(name, w, h);

Argument | Description
name | The name of the canvas element to link the surface to.
w | The width of the surface to be created.
h | The height of the surface to be created.

Returns: Real

Description

NOTE: This function is only available for use with the HTML5 module!

This function allows you to attach a surface to a canvas element that already exists in your web page, meaning that you can effectively split up portions of your game to be drawn at various different places within the page. To that end, you must have defined the canvas element correctly within the *.html page of your game using the correct sizes and names that correspond to the surfaces you wish to create. So, you would have your "main" canvas, and then your secondary surface canvas elements, which will be assigned using this function to the correct surfaces. The following image is an example of how a page with three canvas elements would be set up: The page layout can be tricky, especially if you wish all the elements to line up correctly, but once the hard task of creating the layout has been completed, you can then add this html file as the default page file for the game using the HTML5 Tab of the Global Game Settings. The next thing you should do is set up your room and views, as each surface will need to be associated with a specific view to "capture" the game images (see the view variable view_surface_id[0...7]). The image below shows how the game room for the above canvas example would be set out: Finally you would then use this function to create the surfaces, with the name being the same as that used for the canvas elements and the size corresponding to the size of that same canvas. The function will return the index of the surface which should be stored in a variable for future function calls. When the surface is first created, it may contain "noise" as basically it is just an area of memory that is put aside for the purpose (and that memory may still contain information), so you may want to clear the surface before use with a function like draw_clear_alpha.

Example:

s1 = surface_create_ext("surface1", 192, 550);
s2 = surface_create_ext("surface2", 608, 186);
view_surface_id[1] = s1;
view_surface_id[2] = s2;

The above code creates two surfaces of different sizes, assigning each one to a different canvas element, and then those surfaces are assigned to two views so that the correct part of the room is captured.

Back: Surfaces
Next: surface_resize

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_exists

Finds whether a given surface exists or not.

Syntax:

surface_exists(surface_id);

Argument | Description
surface_id | The ID of the surface to check.

Returns: Boolean

Description

This function is essential when working with surfaces due to their volatile nature. Surfaces are always held in texture memory which means that they can be destroyed from one moment to the next (for example, when a screensaver starts on windows, or when minimised on an Android device), so you should always check that a surface exists before doing anything with it (this includes drawing it to the screen). The example code below shows a typical use of this command in the draw event of an instance to check for a surface and re-create it if it has been removed (note that the surface will have been originally created in the create event of the object).

Example:

if !surface_exists(surf)
{
surf = surface_create(1024, 1024);
}
else
{
if view_current = 1
{
draw_surface(surf,0,0);
}
}

The above code will check to see if a surface indexed in the variable "surf" exists, and if it does not, it will re-create it. If it does exist, it then checks to see which view is currently being drawn and if it is view[1] it draws the surface.

Back: Surfaces
Next: surface_create

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_free

Destroys the surface, freeing it from memory.

Syntax:

surface_free(surface_id);

Argument | Description
surface_id | The ID of the surface to be freed.

Returns: N/A

Description

When you are working with surfaces, you should always use this function whenever you are finished using them. Surfaces take up space in memory and so need to be removed, normally at the end of a room, but it can be done at any time depending on the use you put them to. Failure to do so can cause memory leaks which will eventually slow down and crash your game.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

if keyboard_check_pressed(vk_escape)
{
surface_free(surf);
room_goto(rm_Menu);
}

The above code checks for a key press and if it detects one it frees the memory reserved for the surface indexed in the variable "surf" and then changes room.

Back: Surfaces
Next: surface_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_get_height

Finds the pixel height of a surface.

Syntax:

surface_get_height(surface_id);

Argument | Description
surface_id | The ID of the surface to get the height of.

Returns: Real

Description

This function simply returns the height, in pixels, of the indexed surface.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

sh = surface_get_height(surf);

The above code will store the height of the surface indexed in the variable "surf" in the variable "sh".

Back: Surfaces
Next: surface_get_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_get_texture

Returns the texture id for the given surface.

Syntax:

surface_get_texture(surface_id);

Argument | Description
surface_id | The ID of the surface to get the width of.

Returns: Pointer

Description

This function returns a special pointer for the surface texture. This value can then be used in other draw functions, particularly in general 3D and some of the 2D primitive functions.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

var tex;
tex = surface_get_texture(surf);
draw_primitive_begin_texture(pr_trianglestrip, tex);
draw_vertex_texture(0, 480, 0, 0);
draw_vertex_texture(640, 480, 1, 0);
draw_vertex_texture(640, 480, 1, 1);
draw_vertex_texture(0, 480, 0, 1);
draw_primitive_end();

The above code will draw a 4 vertex triangle strip textured with the texture held in the "tex" variable, which is itself taken from a previously created surface.

Back: Surfaces
Next: surface_getpixel

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_get_width

Finds the pixel width of a surface.

Syntax:

surface_get_width(surface_id);

Argument | Description
surface_id | The ID of the surface to get the width of.

Returns: Real

Description

This function simply returns the width, in pixels, of the indexed surface.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

sw = surface_get_width(surf);

The above code will store the width of the surface indexed in the variable "surf" in the variable "sw".

Back: Surfaces
Next: surface_get_texture

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_getpixel

Returns the colour of the pixel corresponding a position in the surface.

Syntax:

surface_getpixel(surface_id, x, y);

Argument | Description
surface_id | The ID of the surface.
x | The x position on the surface from which to get the pixel.
y | The y position on the surface from which to get the pixel.

Returns: Real

Description

This function can be used to get the colour of a specific pixel from a surface, using the local coordinates of the surface where (0,0) is the top left corner. This function should not be used very often as it is extremely slow and may cause a pause in your game.

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

col = surface_getpixel(surf, 56, 78 );

This will return the colour of the pixel at coordinates (56,78) of the surface indexed in the variable "surf".

Back: Surfaces
Next: surface_getpixel_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_getpixel_ext

Returns the full 32bit value for the pixel at a given coordinate on a surface.

Syntax:

surface_getpixel_ext(surface_id, x, y);

Argument | Description
surface_id | The ID of the surface to use.
x | The x coordinate of the pixel to check
y | The y coordinate of the pixel to check

Returns: Real

Description

With this function you can get the full abgr 32bit value of any pixel of a (previously created) surface.

NOTE: This function is slow and so should only be used when absolutely necessary.

Example:

col = surface_getpixel_ext(mouse_x, mouse_y);
alpha = (col >> 24) & 255;
blue = (col >> 16) & 255;
green = (col >> 8) & 255;
red = col & 255;

The above code will get the 32bit colour value at the position of the mouse and then split it into its component values, storing them in variables.

Back: Surfaces
Next: surface_free

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_reset_target

Sets the drawing target back to the screen, which is the default setting.

Syntax:

surface_reset_target();

Returns: N/A

Description

With this function you reset all further drawing from the target surface back to the screen. Please note that to start drawing to a surface you must first have called the function surface_set_target and then this one after you have finished, for each surface target that you have set or else nothing will be drawn on the screen as all further drawing (even in other instances) will be done on the surface. You should also realise that nothing will be seen if the surface itself is not drawn on the screen in the draw event of an instance.

NOTE: if you have not previously set a render target with the function surface_set_target, using this function will silently (ie: without any error messages) end all further code execution for the event.

Example:

if view_current = 0
{
surface_set_target(surf);
with (obj_Effect)
{
draw_self();
}
surface_reset_target();
}
else
{
draw_surface(surf, 0, 0);
}

The above code will check to see which view is currently being drawn, and if it is view[0] it sets the draw target to a surface and draws all instances of the object "obj_Effect" before resetting the draw target again. If the view is not view[0] the surface is drawn to the screen.

Back: Surfaces
Next: surface_copy

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_resize

Resize a previously created surface.

Syntax:

surface_resize(surface_id, w, h);

Argument | Description
surface_id | The ID of the surface to change.
w | The width of the new surface.
h | The height of the new surface.

Returns: N/A

Description

This function will resize a surface to the given dimensions (in pixels). The surface_id is that of a surface you have created previously, or the application_suface, and the function will resize that surface. Note that this will neither crop nor stretch the contents of the surface, but rather it destroys the current surface and recreates it with the same handle (surface_id) with the new dimensions, meaning that it will need to be cleared and drawn to again (unless it is the application_surface in which case GameMaker: Studio will do this automatically).

NOTE: If you are resizing the application surface, these changes will not be registered until the start of the next draw frame, meaning that calling the surface_get_width() or surface_get_height() functions in the same event or step will return the previous values.

Example:

if view_wport[0] != surface_get_width(application_surface) || view_hport[0] != surface_get_height(application_surface)
{
surface_resize(application_surface, view_wport[0],view_hport[0]);
}

The above code will check the view port size against that of the surface "aplication_surface" and if it is different, the surface is re-sized.

Back: Surfaces
Next: surface_set_target

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_save

Saves a surface to disc.

Syntax:

surface_save(surface_id, fname);

Argument | Description
surface_id | The ID of the surface to set as the drawing target.
fname | The name of the saved image file.

Returns: N/A

Description

This function will save a surface to disc using the given filename. The surface must be saved as a *.png format file.

Example:

if keyboard_check_pressed(ord("S")
{
surface_save(surf, "test.png");
}

The above code will check to see if the user presses the "S" key on the keyboard and if they do it will save the surface indexed in the variable "surf" to disc.

Back: Surfaces
Next: surface_save_part

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_save_part

Saves a part of a surface to disc.

Syntax:

surface_save_part(surface_id, fname, x, y, width, height);

Argument | Description
surface_id | The ID of the surface to set as the drawing target.
fname | The name of the saved image file.
x | The starting x position within the surface.
y | The starting y position within the surface.
width | The width of the part to save.
height | The height of the part to save.

Returns: N/A

Description

This function will save a part of a surface to disc using the given filename. The surface must be saved as a *.png format file, and the (x,y) position must be given as local coordinates to the surface, bearing in mind that the top left corner of the surface is always (0,0).

Example:

if keyboard_check_pressed(ord("S")
{
surface_save_part(surf, "test.png", 0, 0, 100, 100);
}

The above code will check to see if the user presses the "S" key on the keyboard and if they do it will save a part of the surface indexed in the variable "surf" to disc.

Back: Surfaces
Next: surface_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_set_target

Sets the drawing target to a specific surface.

Syntax:

surface_set_target(surface_id);

Argument | Description
surface_id | The ID of the surface to set as the drawing target.

Returns: Boolean

Description

With this function you set all further drawing to the target surface rather than the screen and in this way you can tell GameMaker: Studio to only draw specific things to the specified surface. Please note that if you do not call surface_reset_target after you have finished, nothing will be drawn on the screen as all further drawing (even in other instances) will be done on the surface. You should also realise that nothing will be seen if the surface itself is not drawn on the screen in the draw event of an instance. You can check the return value of this function too as a debug tool to check whether the surface target was set or not, with a return value of 0 being a failure to set the target and any other positive value being a success.

One thing that should be noted is that surfaces are stacked so you cannot jump from target to target and then reset to the normal draw target at the end, but rather you must open and close rendering targets. For example, this will not work correctly:

surface_set_target(surf1);
draw_text(32, 32, "surface1");
surface_set_target(surf2);
draw_text(32, 64, "surface2");
surface_reset_target();

Instead, you must reset the target for each of the surfaces that you set, much like you must use opening and closing brackets {} for code blocks. So the above should be written as either this:

surface_set_target(surf1);
draw_text(32, 32, "surface1");
surface_reset_target();
surface_set_target(surf2);
draw_text(32, 64, "surface2");
surface_reset_target();

or as this:

surface_set_target(surf1);
draw_text(32, 32, "surface1");
surface_set_target(surf2);
draw_text(32, 64, "surface2");
surface_reset_target();
surface_reset_target();

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

if view_current = 0
{
surface_set_target(surf);
with (obj_Effect)
{
draw_self();
}
surface_reset_target();
}
else
{
draw_surface(surf, 0, 0);
}

The above code will check to see which view is currently being drawn, and if it is view[0] it sets the draw target to a surface and draws all instances of the object "obj_Effect" before resetting the draw target again. If the view is not view[0] the surface is drawn to the screen.

Back: Surfaces
Next: surface_set_target_ext

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


surface_set_target_ext

Sets the MRT output target to a specific surface.

Syntax:

surface_set_target_ext(index, surface_id);

Argument | Description
index | The render target index to use (from 0 to 3).
surface_id | The ID of the surface to use.

Returns: Boolean

Description

This function is for use with the Shader Functions and sets the MRT (0 - 3) for native level shaders (DX9, DX11, OpenGL).

NOTE: When working with surfaces there is the possibility that they can cease to exist at any time due to them being stored in texture memory. You should ALWAYS check that a surface exists using surface_exists before referencing them directly. For further information see Surfaces.

Example:

surface_set_target_ext(0, surf);

The above code will set the render target 0 to the surface ID indexed in the variable "surf".

Back: Surfaces
Next: surface_reset_target

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Application Surface

This section deals with the application surface and the functions specific to it.

GameMaker: Studio doesn't actually render most things to the screen directly, but instead it renders them to the application surface. This is essentially a surface, just like any that you can make yourself using the surface functions, and as such can be manipulated with the surface functions, drawn to, sent to shaders and anything else that you would normally do with surface are also applicable to this.

NOTE: The only thing you cannot do with the application surface is free it. It always exists, although the index value to access it may change.

When you run your game, this surface is created the first time that the draw event is called in each new room that you enter, which means that nothing is drawn until that point. However, you can still get the application surface position and resize it in the CreateEvent or any other event without getting any errors and the values used will be relevant to the surface when it is created. The actual sequence of events is as follows:

  • Pre-draw event

  • --- > application surface created and render target set

  • For each visible view, or, if no views are active, once
    Draw begin event
    Draw event
    Draw end event
  • --- > the application surface target is reset here

  • Post draw event

  • --- > the application surface is now drawn to the back buffer by default (although you can switch this off)

  • Draw GUI begin event
  • Draw GUI event
  • Draw GUI end event

The use of this surface means that you can easily create incredible transitions using shaders, or take the screen and wrap it around a 3D form, or simply scale a low-res game up to any resolution screen... The possibilities are endless!

To access this surface, you need to use the built-in global variable application_surface which is explained on the following page:

  1. application_surface

You also have a couple of specialist functions that are designed only for use with the application surface:

  1. application_surface_enable
  2. application_surface_is_enabled
  3. application_get_position
  4. application_surface_draw_enable

Back: Surfaces

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Time Lines

This section deals with timeline functions.

Time lines are a powerful mechanism for controlling events in your game, and are based on "moments", where a "moment" is simply a single game step. These timelines are generally created from the Resource Tree in a similar way to an object, ie: you create a timeline, then in each moment that you require it to perform an action you add some code or a D'n'D icon for it to perform. Once created, you can then stop, start, and manipulate timelines through code. You can even modify individual moments by defining a script and adding it into the timeline dynamically from a controller object (for example), making this a very powerful and versatile tool when creating your games.

Timeline Functions

The following functions are for adding and manipulating Timelines from within your game:

  1. timeline_exists
  2. timeline_get_name
  3. timeline_add
  4. timeline_delete
  5. timeline_moment_add_script
  6. timeline_moment_clear
  7. timeline_clear
  8. timeline_size
  9. timeline_max_moment

Timeline Instance Variables

The following variables are "built in" to all instances to make working with Timelines easier and give you control over:

  1. timeline_index
  2. timeline_running
  3. timeline_speed
  4. timeline_position
  5. timeline_loop

Back: Game Assets

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_index

Returns the time line index for the instance.

Syntax:

timeline_index;

Returns: Real

Description

This variable holds the index of the time line currently associated with the instance. You can set this to a particular time line to use that one, or set it to -1 to stop using a time line for the instance (if no time line is defined for the instance, -1 is returned too). Note that this does not start the time line - for that use the variable timeline_running.

Example:

if timeline_exists(global.tl)
{
timeline_index = global.tl;
}

The above code will assign the instance running the code a time line indexed in the variable "global.tl" if that time line exists.

Back: Timelines
Next: timeline_running

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_add

Adds a new time line.

Syntax:

timeline_add();

Returns: Real

Description

With this function you can add a new (empty) time line into your game. the function returns the index of this new time line which should be stored in a variable for use in all further function calls that involve this new time line. You should also be sure to use the function timeline_delete whenever you no longer wish to use the time line (like at the end of the room) so as to prevent any possible memory leaks that could slow down or crash your game.

Example:

global.tl = timeline_add();

The above code creates a new time line and stores its index in the variable "global.tl".

Back: Timelines
Next: timeline_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_clear

Clears the time line of all moments.

Syntax:

timeline_clear(ind);

Argument | Description
ind | The index of the time line to clear.

Returns: N/A

Description

With this function you can clear a specific time line of "moments", removing all codes and actions for that time line and leaving it empty.

Example:

if timeline_position > 200
{
timeline_clear(global.tl);
timeline_index = -1;
}

The above code will clear the specified time line indexed by the variable "global.tl" of all moments when a specific moment has been passed.

Back: Timelines
Next: timeline_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_delete

Deletes a given time line.

Syntax:

timeline_delete( ind );

Argument | Description
ind | The index of the time line to delete.

Returns: N/A

Description

With this function you can delete any time line from your game. if this time line was created in the GameMaker: Studio resource tree, please note that it is removed completely from the game and trying to call the indexed time line again after using this function will cause an error. If the time line was created dynamically using the timeline_add function, then this function should be used the moment that the time line is no longer needed to prevent any memory leaks that could slow down (and eventually crash) your game.

Example:

if timeline_exists(global.tl) timeline_delete(global.tl);

The above code checks to see if a time line exists and is indexed in the global variable "tl" and if so it then deletes that time line.

Back: Timelines
Next: timeline_moment_add_script

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_exists

Checks if a given time line exists.

Syntax:

timeline_exists(ind);

Argument | Description
ind | The index of the time line to check for.

Returns: Boolean

Description

With this function you can check and see whether a time line exists (returns true) or not (returns false). This is particularly useful when creating Timelines dynamically using the timeline_add function, but you should note that if you search for an uninitialised variable (that would otherwise be assigned to a time line's index) an error will be thrown.

Example:

if timeline_exists(global.tl) timeline_delete(global.tl);

The above code checks to see if a time line exists and is indexed in the global variable "tl" and if so it then deletes that time line.

Back: Timelines
Next: timeline_get_name

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_get_name

Gets the name of a given time line.

Syntax:

timeline_get_name( ind );

Argument | Description
ind | The index of the time line to check the name of.

Returns: String

Description

This function can be used to get the name of a time line as a string. if the time line has been created dynamically using the timeline_add function, the name returned will have the format "__newtimelineN" where "N" is the number of the time line (starting from 0). Please note that this is only a string and cannot be used to reference the timeline directly - for that you would need the timeline index. You can, however, use this string to get the timeline index using the returned string along with the function asset_get_index().

Example:

str = timeline_get_name(global.tl);

The above code will store the name of the time line indexed in the variable "global.tl".

Back: Timelines
Next: timeline_add

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_loop

Sets whether a time line should loop or not.

Syntax:

timeline_loop;

Returns: Boolean

Description

This variable will return whether the time line is looping (true) or not (false). You can change this variable to switch looping on or off and it works with a negative time line speed (if the time line position goes below 0 it will start again at the last defined moment).

Example:

if !timeline_loop timeline_loop = true;

The above code checks to see of the time line currently assigned to an instance will loop or not and if it doesn't it sets it to true.

Back: Timelines
Next: timeline_exists

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_max_moment

Gives you the maximum moment placed in a given timeline.

Syntax:

timeline_max_moment(ind);

Argument | Description
ind | The index of the timeline to get the last moment of.

Returns: N/A

Description

This function will return the value of the moment in which the timeline performs its final action. So, if you have a timeline with 8 different actions placed 20 moments apart, this function would return the moment value of the last action in that timeline, which would be 160. This function is a good way to test whether a timeline has passed the last active moment when running, since the timeline position will continue incrementing every step of the game whether there are further actions or not.

Example:

if timeline_position > timeline_max_moment(timeline_index)
{
timeline_running = false;
}

The above code will check the current timeline position against the maximum active moment, and if it is greater the timeline will be stopped.

Back: Timelines
Next: timeline_index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_moment_add_script

Adds a script to the time line at the given step.

Syntax:

timeline_moment_add_script(ind, step, script);

Argument | Description
ind | The index of the time line to add a moment to.
step | The moment (step) to add to.
script | The index of the script to add into the moment.

Returns: N/A

Description

With this function you can dynamically add scripts to Timelines (the scripts must already exist in the game resources) at any given "moment" within that time line, where a "moment" is the equivalent of one game tick (or step). In this way you can create a new time line using the timeline_add function and add different behaviours at any point, or simply modify a previously created time line resource with new behaviours. Note that the script cannot require any additional arguments when using this function.

Example:

global.tl = timeline_add();
var i = room_speed * 60;
repeat(3)
{
timeline_moment_add_script(global.tl, i, choose(scr_AlienAttack_1, scr_AlienAttack_2, scr_AlienAttack_3);
i += room_speed * 60;
}

The above code will create a new time line and store its index in the variable "global.tl". It will then add three scripts to the time line, chosen at random, at one minute intervals.

Back: Timelines
Next: timeline_index

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_moment_clear

Clears the given moment of a time line.

Syntax:

timeline_moment_clear(ind, step);

Argument | Description
ind | The index of the time line to clear.
step | The moment to clear.

Returns: N/A

Description

With this function you can clear a specific moment of any previously defined time line of all codes and actions.

Example:

timeline_moment_clear(global.tl, room_speed * 30);

The above code will clear the specified moment of the time line indexed by the variable "global.tl".

Back: Timelines
Next: timeline_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_position

Sets the position for the next step of a time line.

Syntax:

timeline_position;

Returns: Real

Description

This variable holds the current position (moment) a time line is currently at. You can change this value to skip parts of the time line, or to repeat parts or to start the time line again from the beginning.

Example:

if !timeline_running
{
timeline_position = 0;
timeline_running = true;
}

The above code will check to see if the instance is running a time line, and if it is not then it resets the assigned time line to start at the first moment and then starts it.

Back: Timelines
Next: timeline_loop

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_running

Sets a time line to run or stop.

Syntax:

timeline_running;

Returns: Boolean

Description

This variable holds current state of the assigned time line and will return true if it is running and false if it is not. You can also set this variable to either true or false to start and stop the time line at any time. it should be noted that a stopped time line is not reset, and so starting it again at a later time will start it from the exact moment that it was stopped at.

Example:

if !timeline_running
{
timeline_position = 0;
timeline_running = true;
}

The above code will check to see if the instance is running a time line, and if it is not then it resets the assigned time line to start at the first moment and then starts it.

Back: Timelines
Next: timeline_speed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_size

Returns the number of active moments from a given timeline.

Syntax:

timeline_size(ind);

Argument | Description
ind | The index of the timeline get the information from.

Returns: N/A

Description

With this function you can get the total number of active moments for a timeline (an "active" moment is one which has code or D'n'D added to it). This can be handy when creating dynamic timelines using the timeline_moment_add_script() and timeline_moment_clear() functions, as you can check to see if a given timeline has the correct number of active moments or none at all.

Example:

if timeline_size(global.tl) == 0
{
timeline_moment_add_script(global.tl, room_speed + irandom(room_speed), scr_spawn_enemy);
}

The above code check the given timeline size, and if it returns 0 (ie: the timeline has no active moments) it will add a script to be used at a random moment within the timeline indexed in the global variable "tl".

Back: Timelines
Next: timeline_max_moment

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


timeline_speed

Sets the speed that a time line will run at.

Syntax:

timeline_speed;

Returns: Real

Description

Normally, in each step the position in the time line is increased by 1, however you can change this amount by setting this variable to a different value. You can use real numbers (like 0.5, or 2.4 for example) and if the value is larger than one, several moments can happen within the same time step (they will all be performed in the same order as defined for the time line, so no actions will be skipped). You can also use a negative value to let the time line play backwards (until it reaches moment 0, at which point it will stop unless the timeline_loop variable is set to true).

Example:

if !timeline_running
{
timeline_running = true;
timeline_speed = 0.5;
}

The above code will check and see if the instance is running its associated time line and if it is not, it will start the time line running at half speed.

Back: Timelines
Next: timeline_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Display, Windows And Views

This section deals with the functions for manipulating views and the game window.

The "window" is where GameMaker: Studio displays your game, and, depending on the target device, there are different things that can be done with it, like set it to fullscreen or not (for example). Views, however, govern what you see within that window, and so have another series of functions dedicated to them. The following two sections deal with these two aspects of displaying your game:

  1. The Game Window
  2. Views

However, sometimes it's not enough to get information about the game window and views only, and you really need to know things about the display itself. The following function all give you details about the size and orientation of the display, details about the GUI layer, and information on the mouse:

  1. display_reset
  2. display_get_height
  3. display_get_width
  4. display_get_orientation
  5. display_get_dpi_x
  6. display_get_dpi_y
  7. display_set_gui_size
  8. display_set_gui_maximise
  9. display_get_gui_width
  10. display_get_gui_height
  11. display_set_ui_visibility
  12. display_set_windows_vertex_buffer_method
  13. display_set_windows_alternate_sync
  14. display_get_windows_vertex_buffer_method
  15. display_get_windows_alternate_sync
  16. display_mouse_get_x
  17. display_mouse_get_y
  18. display_mouse_set

There are also a couple of special functions that can be used to save the display, or part of it, to an image file:

  1. screen_save
  2. screen_save_part

NOTE: On Windows SurfaceRT devices, there is a canvas limit of 2048x2048, which means the drawing canvas cannot go above those dimensions (neither with views, nor by setting the game window directly) otherwise your game graphics will be corrupted or degraded.

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_get_dpi_x

Returns the dpi value of the x axis of the display.

Syntax:

display_get_dpi_x();

Returns: Real

Description

Dots per inch (DPI) is a measure of spatial printing or video dot density, in particular the number of individual dots that can be placed in a line within the span of 1 inch (2.54 cm). When working on mobile devices (in particular Android devices) this is an important factor to take into consideration as what may be appropriate for one display resolution, may not be appropriate for another. For example, you may have two displays with the same resolution of 400 x 800, but display 1 has a dpi of 60 and display 2 has a dpi of 30. In this case, any text or image displayed on display 2 will appear much larger, even though the actual resolution is the same.

This function will get the dpi of the device display along the x axis (this value is also dependant on the orientation of the device). Please note that Mac and iOS do not return specific dpi settings but appear to return the same values as the OS, which are not correct (but will have to do) as Apple do not give the correct values.

Example:

dpx = display_get_dpi_x();

This would set the variable "dpx" to the dpi value of the x axis.

Back: Windows And Views
Next: display_get_dpi_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_get_dpi_y

Returns the dpi value of the y axis of the display.

Syntax:

display_get_dpi_y();

Returns: Real

Description

Dots per inch (DPI) is a measure of spatial printing or video dot density, in particular the number of individual dots that can be placed in a line within the span of 1 inch (2.54 cm). When working on mobile devices (in particular Android devices) this is an important factor to take into consideration as what may be appropriate for one display resolution, may not be appropriate for another. For example, you may have two displays with the same resolution of 400 x 800, but display 1 has a dpi of 60 and display 2 has a dpi of 30. In this case, any text or image displayed on display 2 will appear much larger, even though the actual resolution is the same.

This function will get the dpi of the device display along the y axis (this value is also dependant on the orientation of the device). Please note that Mac and iOS do not return specific dpi settings but appear to return the same values as the OS, which are not correct (but will have to do) as Apple do not give the correct values.

Example:

dpy = display_get_dpi_y();

This would set the variable "dpy" to the dpi value of the y axis.

Back: Windows And Views
Next: display_set_gui_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_get_gui_height

Returns the height of the GUI.

Syntax:

display_get_gui_height();

Returns: Real

Description

With this function you can get the height (in pixels) of the GUI as used in the Draw Gui Event.

Example:

ads_move(0, display_get_gui_height() - ads_get_display_height(0), 0);

The above code will set an advert to display at the bottom left-hand corner of the display.

Back: Windows And Views
Next: display_set_ui_visibility

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_get_gui_width

Returns the width of the GUI.

Syntax:

display_get_gui_width();

Returns: Real

Description

With this function you can get the width (in pixels) of the GUI as used in the Draw Gui Event.

Example:

ads_move(display_get_gui_width() - ads_get_display_width(0), 0, 0);

The above code will set an advert to display at the top right-hand of the display.

Back: Windows And Views
Next: display_get_gui_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_get_height

Returns the height of the display.

Syntax:

display_get_height();

Returns: Real

Description

This function will return the height of the display (in pixels). Note that on the HTML5 target, this value is the height of the browser window, rather than the physical display size.

Example:

myheight = display_get_height();

This would set the variable "myheight" to the display's height.

Back: Windows And Views
Next: display_get_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_get_orientation

This variable holds a different constant depending on the orientation of the device.

Syntax:

display_get_orientation()

Returns: Constant

Description

This function will return one of two constant GameMaker: Studio has to tell you whether the device running the game is being held in landscape or portrait mode:

Constant | Description
display_landscape | The device is being held horizontally ie: The longest edge is from left to right, and the menu button is on the right.
display_landscape_flipped | As above, only now the menu button is on the left.
display_portrait | The device is being held vertically ie: The longest edge is from top to bottom, and the menu button is at the bottom.
display_portrait_flipped | As above, only now the menu button is at the top.

Please note that this function may not correctly detect the orientation of the device when used in the HTML5 target module. However this is easily mimicked by the use of the following script:

return (browser_width < browser_height);

It will return true for portrait and false for landscape.

Example:

if display_get_orientation() = display_landscape
{
global.Config = 0;
}
else
{
global.Config = 1;
}

The above code checks the orientation of the device and sets a global variable depending on the value returned.

Back: Windows And Views
Next: display_get_dpi_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_get_width

Returns the width of the display.

Syntax:

display_get_width();

Returns: Real

Description

This function will return the width of the display (in pixels). Note that on the HTML5 target, this value is the width of the browser window, rather than the physical display size.

Example:

mywidth = display_get_width();

This would set the variable "mywidth" to the display's width.

Back: Windows And Views
Next: display_get_orientation

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_get_windows_alternate_sync

Get the current vertical synchronisation method (Windows Only).

Syntax:

display_get_windows_alternate_sync();

Returns: Boolean

Description

This Windows only function can be used to get the current vertical synchronisation method at runtime. It will return true if you have active the alternative method v-sync method, or false if you are using the regular v-sync option. Note that this does not report if v-sync is active or not (you can switch function display_reset()), and that you can set the v-sync method from the Global Game Settings or using the function display_set_windows_alternate_sync().

Example:

if !display_get_windows_alternate_sync()
{
display_set_windows_alternate_sync(true);
}

The above code will check to see if the v-sync method is using the alternative or the default, and if it's the default it will switch to the alternative instead.

Back: Windows and Views
Next: display_set_gui_maximise

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_get_windows_vertex_buffer_method

Gets the buffer method used on the Windows target platform.

Syntax:

display_get_windows_vertex_buffer_method();

Returns:Constant

Description

This Windows only function permits you to find out the current method for handling the game geometry vertex buffer. This can be set in the Global Game Settings Windows tab or with the function display_set_windows_vertex_buffer_method(), and will return one of the following constants:

Constant | Description
vbm_fast | This is the default method and is the one recommended by Nvidia - it should give the highest performance.
vbm_compatible | This is the deprecated method that GameMaker: Studio used to use before adopting the fast method - poorer performance on newer machines
vbm_most_compatible | This is the legacy method that was used in previous versions of GameMaker - performance is poorer than the other two, but it should be compatible with almost any machine.

Example:

if display_get_windows_vertex_buffer_method() != vbm_fast
{
display_set_windows_vertex_buffer_method(vbm_fast);
}

The above code will check the current geometry method and set it to "fast" if it is not already.

Back: Windows and Views
Next: display_get_windows_alternate_sync

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_mouse_get_x

Returns the x coordinate of the mouse relative to the display.

Syntax:

display_mouse_get_x();

Returns: Real

Description

This function will return the mouse x position within the screen. It should be noted that this function only works properly when used on the Windows target. It can be used for HTML5 too, but will only return a value relative to the 0,0 of the canvas itself, and will not return any value while the mouse is outside of the canvas. For other devices it will return 0, and you should use the device_mouse_raw_x and device_mouse_raw_y functions instead.

Example:

my_x = display_mouse_get_x();

This would set my_x to the x coordinate of the mouse relative to the display.

Back: Windows And Views
Next: display_mouse_get_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_mouse_get_y

Returns the y coordinate of the mouse relative to the display.

Syntax:

display_mouse_get_y();

Returns:Real

Description

This function will return the mouse y position within the screen. It should be noted that this function only works properly when used on the Windows target. It can be used for HTML5 too, but will only return a value relative to the 0,0 of the canvas itself, and will not return any value while the mouse is outside of the canvas. For other devices it will return 0, and you should use the device_mouse_raw_x and device_mouse_raw_y functions instead.

Example:

my_y = display_mouse_get_y();

This would set my_y to the y coordinate of the mouse relative to the display.

Back: Windows And Views
Next: display_mouse_set

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_mouse_set

Sets the position of the mouse on the display to the indicated values.

Syntax:

display_mouse_set(x, y);

Argument | Description
x | The x coordinate in the display.
y | The y coordinate in the display.

Returns:N/A

Description

With this function you can change or set the position of the mouse within the game display which can be useful for FPS games, for example. The function will only work while the game is in focus and using alt + tab will unlock the mouse.

Example:

display_mouse_set(display_get_width() / 2, display_get_height() / 2);

The above code would center the mouse in the game display.

Back: Windows and Views
Next: screen_save

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_reset

Resets the display and changes the anti-aliasing filtering and vsync.

Syntax:

display_reset(aa, vsync);

Argument | Description
aa | The level of anti-aliasing filtering (0, 2, 4 or 8).
vsync | Toggle vertical synchronisation to on (true) or off (false).

Returns: Real

Description

This function Resets the display settings to the ones that were set when the game was started, but also allows you to change the current level of full screen anti-aliasing being used and whether to use vertical synchronisation. The available anti-aliasing levels are 0,2,4 and 8, with the default startup value being set to 0, and the default v-sync setting is false (off). Switching v-sync on may give a smoother gaming experience but it will also need more processing power and so its impact must be considered careful before use, and the same goes for the anti-aliasing where the higher the number the more processing that is required.

Since not all target devices are the same, some may not support 8x or 4x anti-aliasing for example, and so there is a read only variable available for getting the different levels of AA that the device running the game can display:

display_aa

This variable will return a value based on the setting of bits for the different levels. So for only 2xAA, this will report 2, for 2x and 4x availability it will report 6. For 8 and 4 it will report 12. For all 3 levels (2,4 and 8) it will report 14.

Example:

if display_aa > 12 display_reset(8, true);

The above code will set the anti-aliasing level to 8 if supported and switch v-sync to on.

Back: Windows And Views
Next: display_get_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_set_gui_maximise

Scales the GUI to the given width or height.

Syntax:

display_set_gui_maximise(xscale, yscale, xoffset, yoffset);

Argument | Description
xscale | <Optional> The horizontal scaling factor (use -1 to reset to default).
yscale | <Optional> The vertical scaling factor (use -1 to reset to default).
xoffset | <Optional> The x offset position for drawing.
yoffset | <Optional> The y offset position for drawing.

Returns:N/A

Description

This function can be used to maximise the GUI layer and set it to be scaled and offset in relation to the screen dimensions, rather than the default application surface position and dimensions. By default, the GUI layer is 1:1 with the application surface resolution and drawn at the (0,0) position of the surface too. However this is not always what you want and so you can use this function to set it to be drawn relative to the absolute (0,0) position of the display or game window.

What arguments you provide to this function will depend on the effect you wish it to have on the GUI layer. Simply calling the function with no arguments will set the GUI layer to be drawn at the (0,0) position of the screen or game window, with the width and height being scaled to fit the whole area.

display_set_gui_maximise();

However, you can set the scaling factor for the GUI layer, and the width and height will be scaled by that amount. Remember that the GUI layer is always made to fit the size of the display or game window, or the application surface, so setting this value to anything other than 1 basically scales the pixel count along the width and height. If your display is 1024x768 and you set the scaling factor to scale by 0.5, then your GUI layer will be half the size of the display, effectively doubling the pixel size.

display_set_gui_maximise(0.5, 0.5);

Setting the values in this way will also set the draw position to the (0,0) of the display or game window, so you can provide offset values to "move" the (0,0) position:

var pos = application_get_position();
display_set_gui_maximise(0.5, 0.5, pos[0], pos[1]);

Finally, you can reset the GUI layer using this function by setting the scaling factors to -1. This will set the GUI layer to have a 1:1 scale again and set the draw position to the (0,0) position of the application surface rather than the display or window.

display_set_gui_maximise(-1, -1);

Example:

display_set_gui_size(display_get_width() / 2, display_get_height() / 2;
display_set_gui_maximise(2, 2, 0, 0);

The above code will lock the draw GUI event to the given width and height, scaling all components to fit the display, using that proportion.

Back: Windows and Views
Next: display_get_gui_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_set_gui_size

Scales the GUI to the given width or height.

Syntax:

display_set_gui_size(width, height);

Argument | Description
width | The new GUI width
height | The new GUI height

Returns:N/A

Description

This function will only affect things drawn in the Draw GUI Event and can be used to set a specific width and height for all GUI components in that event, and no matter what size of display or window is used to display the GUI, it will be scaled to fit correctly. Where the GUI is positioned (ie: the (0,0) position) will depend on whether you have used the function display_set_gui_maximise() or not. If you do not use this function (the default setting) then the GUI layer will be positioned with its (0,0) point at the same position as that for the application surface (the area where your game is being drawn) and the width and height will be stretched to fit the this surface, such that setting a GUI width of 256px with this function when the application surface is 512px would stretch those 256 pixels to fit, effectively making the pixels twice as large. This is ideal for those games that have aspect ratio correction set in the global Game Settings.

If you have used the display_set_gui_maximise() function then the (0,0) position for the GUI layer will default to the top left corner of the game window (or the display when in fullscreen or on devices), with the scaling factor set by that function, and the width and height set by this one.

You can reset the GUI layer at any time to the default configuration by calling this function using -1 as both the width and height - this will set the GUI's (0, 0) position to the application_surface's top-left corner and the GUI width and height will be sized 1:1 with the application_surface.

Examples:

display_set_gui_size(768, 1024);

The above code will set the GUI to the given width and height, scaling all components to fit the application_surface using that proportion.

display_set_gui_size(-1, -1);

The above code will reset the GUI event to the same position, width and height as the application_surface.

Back: Windows and Views
Next: display_set_gui_maximise

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


display_set_ui_visibility

Scales the GUI to the given width or height.

Syntax:

display_set_ui_visibility(flags);

Argument | Description
flags | The Android SYSTEM flags to use (as an integer value).

Returns:N/A

Description

This function can be used to show or hide the system UI on Android only. The function requires you to supply one or more system flags as an integer value. When using more than a single flag, these need to be merged using the bitwise "or", as shown in the example below. You can find a list of Android system flags here.

Example:

var flags = 1024|4096;
display_set_ui_visibility(flags);

The above code will use the Android system flags "SYSTEM_UI_FLAG_IMMERSIVE_STICKY" and "SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN" to set the visibility of the display.

Back: Windows and Views
Next: display_set_windows_vertex_buffer_method


display_set_windows_alternate_sync

Set the vertical synchronisation method (Windows Only).

Syntax:

display_set_windows_alternate_sync(flag);

Argument | Description
flag | Use an alternative method (true) or the regular method (false).

Returns:N/A

Description

This Windows only function can be used to change the vertical synchronisation method at runtime. When set to true (and you have vSync active) an alternative method will be used to that which is the default, with the aim to reduce any possible visual lag or stuttering of your game. Note that this can also be set in the Global Game Settings and that it is only applicable Windows 7 and above - it will just use the default method if you have this option ticked and run on XP or Vista - and that it does not switch it on or off, for that you would use the function display_reset().

Example:

if !display_get_windows_alternate_sync()
{
display_set_windows_alternate_sync(true);
}

The above code will check to see if the v-sync method is using the alternative or the default, and if it's the default it will switch to the alternative instead.

Back: Windows and Views
Next: display_get_windows_vertex_buffer_method


display_set_windows_vertex_buffer_method

Sets the buffer method used on the Windows target platform.

Syntax:

display_set_windows_vertex_buffer_method(method);

Argument | Description
method | The buffer method to use (see the constants list below).

Returns:N/A

Description

This Windows only function permits you to choose one of various different ways of handling the game geometry vertex buffer, some of which may work better on different machines. This can be set in the Global Game Settings Windows tab too, and will affect performance to different degrees depending on the machine. The constants available are:

Constant | Description
vbm_fast | This is the default method and is the one recommended by Nvidia - it should give the highest performance.
vbm_compatible | This is the deprecated method that GameMaker: Studio used to use before adopting the fast method - poorer performance on newer machines
vbm_most_compatible | This is the legacy method that was used in previous versions of GameMaker - performance is poorer than the other two, but it should be compatible with almost any machine.

Example:

if display_get_windows_vertex_buffer_method() != vbm_fast
{
display_set_windows_vertex_buffer_method(vbm_fast);
}

The above code will check the current geometry method and set it to "fast" if it is not already.

Back: Windows and Views
Next: display_set_windows_alternate_sync

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


screen_save

Saves a screenshot of the game as a *.png.

Syntax:

screen_save(fname);

Argument | Description
fname | The filename for the screenshot to save

Returns: N/A

Description

With this function you can save a screenshot of the game as it currently appears in the game window or browser. The file will be saved to the working directory of the game, which in windows is located at "C:\Users\YOURUSERNAME\AppData\Local\YOURGAMENAME\" This is an image of the whole display region and not just a specific section or view and your are saving out what is being drawn to the back buffer at the time, meaning that depending on where you call the function the results will differ. If you don't want the GUI layer, then you can save the screen before rendering the GUI (ie: in the Draw event), but if you do want GUI elements to be included, then you save after the Draw GUI event. Should you need more control, you should use the function screen_save_part.

NOTE: This function does not work on the HTML5 target.

Example:

if keyboard_check_pressed(ord("S"))
{
screen_save(working_directory + "\Screens\Screen_"+string(num)+".png")
num += 1;
}

The above code takes a screenshot of the game when the user presses the "S" key. This screen shot is saved to a specific directory and numbered using a variable which is then incremented.

Back: Windows and Views
Next: screen_save_part

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


screen_save_part

Saves a screenshot of a defined area of the game window as a .png to a given filename.

Syntax:

screen_save_part(fname,x,y,w,h);

Argument | Description
fname | The filename for the screenshot to save
x | The x coordinate of the top left corner of the area of the screen to capture
y | The y coordinate of the top left corner of the area of the screen to capture
w | The width of the area of the screen to capture
h | The height of the area of the screen to capture

Returns: N/A

Description

With this function you can save a screenshot of a part of the game as it currently appears in the game window or browser. The selection coordinates are based on the absolute size of the display, so (0,0) is always the top left hand corner of the screen. Below is an image that shows how this function works: The file will be saved to the working directory of the game.

NOTE: This function does not work on the HTML5 target.

Example:

if keyboard_check_pressed(ord("S"))
{
screen_save_part(working_directory + "\Screens\Screen_"+string(num)+".png", 0, 0, 100, 100)
num += 1;
}

The above code takes a screenshot of a part of the game screen that is 100 pixels square when the user presses the "S" key. This screen shot is saved to a specific directory and numbered using a variable which is then incremented.

Back: Windows and Views
Next: display_reset

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


The Game Window

This section has all the functions related to the game window

The actual game you create happens in a window, and this window has a number of properties, like whether it has a border, whether it is full screen, etc. Normally these values are set in the Windows Tab of the Global game Settings but you can change them during the game.

NOTE: These functions are for Windows, Ubuntu (Linux), MacOS and HTML5 target modules only and may not work on any other device.

The following image illustrates how all the windows functions relate and interact with each other: The following functions exist to change and get game window properties:

  1. window_center
  2. window_handle
  3. window_get_caption
  4. window_get_colour
  5. window_get_fullscreen
  6. window_get_height
  7. window_get_width
  8. window_get_x
  9. window_get_y
  10. window_get_cursor
  11. window_get_visible_rects
  12. window_mouse_get_x
  13. window_mouse_get_y
  14. window_mouse_set
  15. window_set_caption
  16. window_set_colour
  17. window_set_fullscreen
  18. window_set_position
  19. window_set_size
  20. window_set_rectangle
  21. window_set_cursor
  22. window_set_min_width
  23. window_set_max_width
  24. window_set_min_height
  25. window_set_max_height
  26. window_has_focus
  27. window_device

Back: Windows And Views
Next: Views

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_center

Centers the region based on the viewable or browser area.

Syntax:

window_center();

Returns: N/A

Description

With this function you can center the game window in the display when the target module is Windows, Ubuntu (Linux) or MacOS, or you can center it in the browser if the target module is HTML5. This function has no effect on any other device.

NOTE: If you have resized the game window (for example, by switching from full screen to windowed), and wish to center the new window, this function should be called in an alarm[0] at least one step later than the window size change, otherwise it will not work correctly.

Example:

if !window_get_fullscreen()
{
window_center();
}

The above code will center the game window within the display if it is not in full screen mode.

Back: The Game Window
Next: window_handle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_device

Returns the current d3d device pointer.

Syntax:

window_device();

Returns: Pointer

Description

This function will return the current d3d device pointer, which you can then (for example) pass through to a DLL.

NOTE: This function is only valid for the Windows and Mac OSX only (on Mac OSX it contains a pointer to an NSWindow class).

Example:

gfx_pointer = window_device()

The above code will store the d3d device pointer in a variable.

Back: The Game Window
Next: window_center

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_get_caption

Returns the caption of the window.

Syntax:

window_get_caption();

Returns: N/A

Description

This function returns the caption of the window (this is the text that appears on the top of the window, beside its icon) and by default this shows the caption of the room you're currently in.

Example:

if window_get_caption() != ""
{
window_set_caption("");
}

The above code will check the windows caption to see if it has text or not, and if it does it sets it to an empty string so as no caption is displayed.

Back: The Game Window
Next: window_get_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_get_colour

Gets the colour of the region inside the window/browser but outside the visible views (default is black).

Syntax:

window_get_colour();

Returns: N/A

Description

This function returns the background colour of the game window. This colour represents that which will be used for those areas of the game window that are not occupied by any views. The following image illustrates this:

The above image has two views with two view ports, each one drawn at different positions. This stretches the game window to accommodate both ports and uses the window colour to colour the background where no view is shown.

Example:

if window_get_colour() != c_black
{
window_set_colour(c_black);
}

The above code will check the window colour to see if it is set as black or not, and if it is not it sets it to black.

Back: The Game Window
Next: window_get_fullscreen

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_get_cursor

Gets the current cursor being used in the game window.

Syntax:

window_get_cursor();

Returns:Constant

Description

With this function you can get the current cursor being used in the game window, with the return value being any one of the constants listed below (to set the current cursor being used you can use the function window_set_cursor which also takes these constants):

Constant | Cursor
cr_none |
cr_default |
cr_arrow |
cr_cross |
cr_beam |
cr_size_nesw |
cr_size_ns |
cr_size_nwse |
cr_size_we |
cr_uparrow |
cr_hourglass |
cr_drag |
cr_appstart |
cr_handpoint |
cr_size_all |

Example:

if mouse_check_button_pressed(mb_left)
{
if window_get_cursor() != cr_drag window_set_cursor(cr_drag);
}

The above code will change the window cursor to the standard windows drag cursor if the left mouse button has been pressed and it has not already been changed previously.

Back: The Game Window
Next: window_get_visible_rects

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_get_fullscreen

Returns whether the game is run in fullscreen or not.

Syntax:

window_get_fullscreen();

Returns: Boolean

Description

This function returns whether the game window is in fullscreen mode (true) or not (false).

Example:

if window_get_fullscreen()
{
draw_text(32, 32, "Fullscreen is ON");
}
else
   {
draw_text(32, 32, "Fullscreen is OFF");
}

The above code will check to see if the window is in full screen mode or not and draw a text message depending on the returned value.

Back: The Game Window
Next: window_get_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_get_height

Gets the height of the window.

Syntax:

window_get_height();

Returns: Real

Description

With this function you can get the current height (in pixels) of the game window.

Example:

hh = window_get_height();

The above code will store the current window height in the variable "hh".

Back: The Game Window
Next: window_get_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_get_visible_rects

Find the overlapping region of the rectangle defined by (x1,y1) to (x2,y2) on each of the attached displays.

Syntax:

window_get_visible_rects(x1, y1, x2, y2);

Argument | Description
x1 | The left edge of the rectangle to check
y1 | The top edge of the rectangle to check.
x2 | The right edge of the rectangle to check
y2 | The bottom edge of the rectangle to check.

Returns: Array

Description

With this function you can find the overlapping region of the rectangle defined by (x1,y1) to (x2,y2) on each of the attached displays. The function will return an array with 8 values per display (ie: if you have two displays, the array will have a length of 16 indices), where the values [0 ... 3] correspond to the overlapx1, overlapy1, overlapx2, overlapy2 - defining the region of overlap on this display and will be set to 0,0,0,0 if no overlap - and the values [4 ... 7] corresponds to the monitorx1, monitory1, monitorx2, monitory2 - the coordinates of the display in the virtual display space. This can be used to test whether a saved window position is going to be visible or not (the user may have disconnected an external monitor or moved the window off screen which left the window position that was saved as not being valid), for example.

Example:

var wx = window_get_x();
var wy = window_get_y();
var ww = window_get_width();
var wh = window_get_height();
display_data = window_get_visible_rects(wx, wy, wx + ww, wy + wh);
display_num = array_length_1d(display_data) / 8;

The above code will generate a 1D array held in the variable display_data containing the information about the displays, as well as create the variable display_num to hold the number of active displays found.

Back: The Game Window
Next: window_mouse_get_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_get_width

Gets the width of the window.

Syntax:

window_get_width();

Returns: Real

Description

With this function you can get the current width (in pixels) of the game window.

Example:

ww = window_get_width();

The above code will store the current window width in the variable "ww".

Back: The Game Window
Next: window_get_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_get_x

Gets the x position of the window inside the browser/visible area of the screen.

Syntax:

window_get_x();

Returns: Real

Description

With this function you can get the x position (in pixels) within the browser if it is an HTML5 game or within the display if it is a Windows, Ubuntu (Linux) or MacOS game.

Example:

wx = window_get_x();

The above code stores the current x axis window position in the variable "wx".

Back: The Game Window
Next: window_get_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_get_y

Gets the y position of the window inside the browser/visible area of the screen.

Syntax:

window_get_y();

Returns: Real

Description

With this function you can get the y position (in pixels) within the browser if it is an HTML5 game or within the display if it is a Windows, Ubuntu (Linux) or MacOS game.

Example:

wy = window_get_y();

The above code stores the current y axis window position in the variable "wy".

Back: The Game Window
Next: window_get_cursor

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_handle

Returns the id of the game window.

Syntax:

window_handle();

Returns: Pointer

Description

With this function you can get the internal Windows id value (the HWND, a pointer). This function is really only useful for extension writers who need the window handle to call Windows API's in DLL code (the returned pointer should be cast into a string and then in the C++ just cast it to an HWND).

NOTE: This functions is for Windows and Mac OSX only (on Mac OSX it contains a pointer to an NSWindow class).

Example:

win_id = windows_handle();

The above code will store the game window id in a variable.

Back: The Game Window
Next: window_get_caption

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_has_focus

Returns if the game window is in focus or not.

Syntax:

window_has_focus();

Returns: Boolean

Description

With this function you can poll the window (or tab) state and if it loses focus the function will return false otherwise it will return true. In most cases you can simply use the os_is_paused function to test this, but in some very specific cases (for example games on Chrome Apps) that function will not trigger, in which case you should use this function instead.

NOTE: This function is only valid for the HTML5, Windows, and MacOS modules.

Example:

if !window_has_focus()
{
scr_PauseGame();
}

The above code will check to see if the game window is in focus or not, and if the function returns false a script will be called.

Back: The Game Window
Next: window_device

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_mouse_get_x

Returns the x coordinate of the mouse in the window.

Syntax:

window_mouse_get_x();

Returns: Real

Description

With this function you can get the x position of the mouse cursor (in pixels) within the browser if it is an HTML5 game or within the display if it is a Windows, Ubuntu (Linux) or MacOS game.

NOTE: For regular mouse functions see the section on Mouse Input.

Example:

wx = window_mouse_get_x();

The above code stores the current x axis window position of the mouse in the variable "wx".

Back: The Game Window
Next: window_mouse_get_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_mouse_get_y

Returns the y coordinate of the mouse in the window.

Syntax:

window_mouse_get_y();

Returns: Real

Description

With this function you can get the y position of the mouse cursor (in pixels) within the browser if it is an HTML5 game or within the display if it is a Windows, Ubuntu (Linux) or MacOS game.

NOTE: For regular mouse functions see the section on Mouse Input.

Example:

wy = window_mouse_get_y();

The above code stores the current y axis window position of the mouse in the variable "wy".

Back: The Game Window
Next: window_set_caption

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_mouse_set

Sets the position of the mouse in the window to the indicated values.

Syntax:

window_mouse_set(x, y);

Argument | Description
x | The x coordinate in the window.
y | The y coordinate in the window.

Returns:N/A

Description

With this function you can change or set the position of the mouse within the game window which can be useful for FPS games, for example. The function will only work while the game is in focus and using alt + tab will unlock the mouse.

NOTE: For regular mouse functions see the section on Mouse Input.

Example:

window_mouse_set(window_get_width() / 2, window_get_height() / 2);

The above code would center the mouse in the game window.

Back: The Game Window
Next: window_center

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_caption

Sets the caption of the window.

Syntax:

window_set_caption(caption);

Argument | Description
caption | The new caption.

Returns:N/A

Description

With this function you can change or set the windows caption for the room that you are currently in. This caption appears at the top of the window, beside the game icon, when the game is not in full screen mode.

NOTE: This function is for the Pro version of GameMaker: Studio only..

Example:

if window_get_caption() != ""
{
window_set_caption("");
}

The above code will check the windows caption to see if it has text or not, and if it does it sets it to an empty string so as no caption is displayed.

Back: The Game Window
Next: window_set_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_colour

Sets the colour of the region inside the game window but outside the visible views (default is black).

Syntax:

window_set_colour(colour);

Argument | Description
colour | The colour to set the region.

Returns:N/A

Description

This function can set the background colour of the game window. This colour represents that which will be used for those areas of the game window that are not occupied by any views. The following image illustrates this:

The above image has two views with two view ports, each one drawn at different positions. This stretches the game window to accommodate both ports and uses the window colour to colour the background where no view is shown.

Example:

if window_get_colour() != c_black
{
window_set_colour(c_black);
}

The above code will check the window colour to see if it is set as black or not, and if it is not it sets it to black.

Back: The Game Window
Next: window_set_fullscreen

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_cursor

Sets the standard cursor for the game window.

Syntax:

window_set_cursor(cursor);

Argument | Description
cursor | The cursor to set for the game window.

Returns:N/A

Description

With this function you can set the cursor for the game window to any one of the constants listed below (to find the current cursor being used you can use the function window_get_cursor which will also return one of these constants):

Constant | Cursor
cr_none |
cr_default |
cr_arrow |
cr_cross |
cr_beam |
cr_size_nesw |
cr_size_ns |
cr_size_nwse |
cr_size_we |
cr_uparrow |
cr_hourglass |
cr_drag |
cr_appstart |
cr_handpoint |
cr_size_all |

Example:

if mouse_check_button_pressed(mb_left)
{
window_set_cursor(cr_drag);
}

The above code will change the window cursor to the standard windows drag cursor if the left mouse button has been pressed.

Back: The Game Window
Next: window_set_min_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_fullscreen

Sets whether the game is run in fullscreen or not.

Syntax:

window_set_fullscreen(full);

Argument | Description
full | Whether to set the screen to fullscreen (true) or not (false).

Returns: N/A

Description

With this function you can set the game window to be full screen (true) or not (false). Please note that for the Mac OSX target, you must have the "Start In Fullscreen" option selected in the Global Game Settings, otherwise this function will fail.

Example:

if mouse_check_button_pressed(mb_left)
{
if window_get_fullscreen()
{
window_set_fullscreen(false);
}
else
{
window_set_fullscreen(true);
}
}

The above code checks for a mouse button press and then sets the window to fullscreen if it is not already, or sets it to windowed if it is already.

Back: The Game Window
Next: window_set_position

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_max_height

Sets a maximum width for the game window.

Syntax:

window_set_max_height(height);

Argument | Description
height | The maximum height in pixels for the game window.

Returns:N/A

Description

This function can be used to set a maximum window height for your game. If you enable the window resize option in the Global Game Settings for the target platform, then the player can resize the game window to any size they wish, however by using this function you can limit the maximum height to the size you specify. If you wish to go back to the default behaviour (ie: no mimimum), then use a value of -1.

NOTE: This function is only available on the Windows, Mac OSX and Linux platforms.

Example:

window_set_min_width(640);
window_set_min_height(480);
window_set_max_width(1280);
window_set_max_height(960);

The above code will set the minimum and maximum width and height for the game window.

Back: The Game Window
Next: window_has_focus

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_max_width

Sets a maximum width for the game window.

Syntax:

window_set_max_width(width);

Argument | Description
width | The maximum width in pixels for the game window.

Returns:N/A

Description

This function can be used to set a maximum window width for your game. If you enable the window resize option in the Global Game Settings for the target platform, then the player can resize the game window to any size they wish, however by using this function you can limit the maximum width to the size you specify. If you wish to go back to the default behaviour (ie: no mimimum), then use a value of -1.

NOTE: This function is only available on the Windows, Mac OSX and Linux platforms.

Example:

window_set_min_width(640);
window_set_min_height(480);
window_set_max_width(1280);
window_set_max_height(960);

The above code will set the minimum and maximum width and height for the game window.

Back: The Game Window
Next: window_set_min_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_min_height

Sets a minimum height for the game window.

Syntax:

window_set_min_height(height);

Argument | Description
height | The minimum height in pixels for the game window.

Returns:N/A

Description

This function can be used to set a minimum window height for your game. If you enable the window resize option in the Global Game Settings for the target platform, then the player can resize the game window to any size they wish, however by using this function you can limit the minimum height to the size you specify. If you wish to go back to the default behaviour (ie: no mimimum), then use a value of -1.

NOTE: This function is only available on the Windows, Mac OSX and Linux platforms.

Example:

window_set_min_width(640);
window_set_min_height(480);
window_set_max_width(1280);
window_set_max_height(960);

The above code will set the minimum and maximum width and height for the game window.

Back: The Game Window
Next: window_set_max_height

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_min_width

Sets a minimum width for the game window.

Syntax:

window_set_min_width(width);

Argument | Description
width | The minimum width in pixels for the game window.

Returns:N/A

Description

This function can be used to set a minimum window width for your game. If you enable the window resize option in the Global Game Settings for the target platform, then the player can resize the game window to any size they wish, however by using this function you can limit the minimum width to the size you specify. If you wish to go back to the default behaviour (ie: no mimimum), then use a value of -1.

NOTE: This function is only available on the Windows, Mac OSX and Linux platforms.

Example:

window_set_min_width(640);
window_set_min_height(480);
window_set_max_width(1280);
window_set_max_height(960);

The above code will set the minimum and maximum width and height for the game window.

Back: The Game Window
Next: window_set_max_width

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_position

Sets the position of the window inside the browser/visible area of the screen.

Syntax:

window_set_position(x, y);

Argument | Description
x | The x coordinate of where to position the window.
y | The y coordinate of where to position the window.

Returns:N/A

Description

With this function you can set the game window to a specific position within the display (on MacOS, Linux(Ubuntu) and Windows) or within the browser (HTML5).

NOTE: If your HTML5 game uses a custom index.html and that sets the canvas to a fixed position then this function will have no effect on the window position.

Example:

window_set_position(0, 0);

The above code will position the game window in the upper left corner of the browser or display (depending on the target module being used).

Back: The Game Window
Next: window_set_size

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_rectangle

Sets the position and size of the window rectangle.

Syntax:

window_set_rectangle(x, y, w, h);

Argument | Description
x | The new x coordinate of the window.
y | The new y coordinate of the window.
w | The new width of the window.
h | The new height of the window.

Returns:N/A

Description

With this function you can set the position of the game window within the browser (HTML5) or display (Windows, Ubuntu (Linux) or MacOS) and set the scale of the window too. For more information on window position and window size, see window_set_position and window_set_size.

Example:

window_set_rectangle(0, 0, display_get_width(), display_get_height());

The above code will set the game window to occupy the whole display area (either the browser or the screen, depending on the target platform).

Back: The Game Window
Next: window_set_cursor

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_set_size

Sets the size of the window in pixels.

Syntax:

window_set_size( w, h );

Argument | Description
w | The new width of the window.
h | The new height of the window.

Returns:N/A

Description

With this function you can change the size of the game window. If you use this function to change the size of the game window, the contents of the window will be scaled to fit with a 1:1 ratio to the background canvas which will keep the image crisp and clear (although scaled if the window is other than the room or view size). For example, if you have a 200 x 150 pixel window, and the player stretches the window by dragging the borders, the final window size may be 400 x 300 pixels, but the drawing canvas is STILL 200 x 150, which gives a blurred image as the pixel ratio is now 1:2. However, if you use this function to set the window size, the 1:1 ratio is maintained, even though the image is scaled to fit the new window size.

Example:

if mouse_check_button_pressed(mb_left)
{
global.scale += 1;
window_set_size(200 * global.scale, 150 * global.scale);
}

The above code will change the size of the window based on the value of the variable "global.scale" when the mouse button is pressed.

Back: The Game Window
Next: window_set_rectangle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Views

This section deals with the functions for defining view properties.

Views are one of the most important of the display properties that you can manipulate with GameMaker: Studio. They are, basically, little windows into your game world that enable you to show the player parts of a room, either scaled or 1:1, and as such they are essential when your game room is larger than the display size. For information on how views can be set up without code directly from the room editor, please see the section More About Rooms - Views.

GameMaker: Studio permits you 8 independent views (numbered from 0 - 7), all of which can be active at any one time, and all of which can show different parts of the same room. This means that you can use views to draw HUD elements or to have split screen effects for example. Each view also has its own associated view port. If the view is a section of the room that the player can see, the port is the area of the screen on which this view is drawn, and as such you can distort and scale the view if it is a size other than the view port.

Something to note about views and view ports is that the total area of the bounding box for all active view ports in the first room of the game is what defines the background canvas size (or window size for MacOS, Ubuntu (Linux) and Windows), as illustrated by the image below: Finally, you should take care when using multiple views as the draw event for all instances is called once for each view, so if you have three views active in one room, the draw event will be run three times every step (basically doing three times the work) which can be a cause for slowdown if the game is large or complex. The view_current variable can be used to help limit these draw calls however.

The following functions exist that deal with views:

  1. view_enabled
  2. view_current
  3. view_visible
  4. view_object
  5. view_angle
  6. view_xview
  7. view_yview
  8. view_hview
  9. view_wview
  10. view_hborder
  11. view_vborder
  12. view_hspeed
  13. view_vspeed
  14. view_xport
  15. view_yport
  16. view_hport
  17. view_wport
  18. view_surface_id
  19. window_view_mouse_get_x
  20. window_view_mouse_get_y
  21. window_views_mouse_get_x
  22. window_views_mouse_get_y

Back: Windows and Views

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_angle

Rotation angle used for the view in the room.

Syntax:

view_angle[0...7]

Returns: Real

Description

With this variable, you can get (or set) the angle at which the view is to be drawn. The default angle is 0º but it can be set to any angle between -359º and 359º. This will not affect how the game is played as it is only for setting the angle at which the view is drawn. Often it is used to create a rotating minimap, or to "shake" the view for example.

NOTE: This variable will not work on the HTML5 target module.

Example:

if shake
{
view_angle[0] = -10 + random(20);
}
else
{
view_angle[0] = 0;
}

the above code will check the variable "shake" and if it returns true, it will then change the view[0] angle to a random value between -10 and 10 every step until the variable returns false, at which time it will return the view[0] angle to 0º.

Back: Views
Next: view_xview

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_current

Returns the current view being rendered.

Syntax:

view_current

Returns: Real

Description

This read only variable is only valid in the Draw Event and returns the current view being rendered. The return value will change during the draw event when you have various views as the draw event is called once for each view in succession. So when (for example) you are using view[0] and view[1] in your game room, the draw event for ALL instances will be run twice, once for each view, and with this variable you can check to see what view is currently being drawn. In general, this is used to only render specific details to a single view when multiple views are visible in the room at the same time. See the example code below.

Example:

if view_current == 0
{
draw_text(view_xview[0] + 32, view_yview[0] + 32, "Player 1");
}
else
{
draw_text(view_xview[1] + 32, view_yview[1] + 32, "Player 2");
}

The above code checks to see which view is currently being drawn and then draws a different text to each view based on the return value.

Back: Views
Next: view_visible

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_enabled

Whether views are enabled or not.

Syntax:

view_enabled

Returns: Boolean

Description

This variable controls whether any views that are visible within the room are enabled or not. If you have views visible and then disable this option, the whole room will be drawn to the screen scaled to the window size.

Example:

if !view_enabled
{
view_visible[0] = true;
view_enabled = true;
}

The above code checks to see if views are enabled for the room, and if they are not, it makes sure that view[0] is visible and then enables views for the room.

Back: Views
Next: view_current

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_hborder

Size of horizontal border for view following.

Syntax:

view_hborder[0...7]

Returns: Real

Description

This variable sets the horizontal border width for view following. You can set the view to follow a specific instance using the view_object variable (or in the room editor) and by setting this value you can control how near or far from the edge of the view the instance needs to be before the view will move. For example, if you have a view width of 320 and set the horizontal view border to 160, the object that the view must follow will always be in the middle of the view. However, make the horizontal view border 0 and the instance must be right on the edge of the view before it will move.

NOTE: if you are not setting the x and y position of the view manually, the view never leaves the boundaries of the room. This means that when the view reaches the edge of a room, the horizontal and vertical borders are ignored and the instance will move freely within the view.

Example:

view_hborder[0] = view_wview[0] / 2;
view_vborder[0] = view_hview[0] / 2;

The above code will set the view follow borders to half the width and height of the view, effectively forcing the view to always be centered on the follow object.

Back: Views
Next: view_vborder

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_hport

Height of the viewport in the drawing region.

Syntax:

view_hport[0...7]

Returns: Real

Description

This variable can be used to get or to set the height of the specified viewport. The height of the viewport (or combined view ports if more than one are active) define the height of the game window or background canvas at the start of the game, but changing this value after the game has started will have no visible effect on the game window size. If you have a larger or smaller port size than that assigned to the view, the view will be scaled down or up to fit, as illustrated by the image below.

Example:

view_hview[0] = view_hport[0]; view_wview[0] = view_wport[0];

The above code sets the width and height of the view to be the same as the width and height of the view port.

Back: Views
Next: view_wport

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_hspeed

Maximal horizontal speed of the view.

Syntax:

view_hspeed[0...7]

Returns: Real

Description

This variable controls the horizontal movement speed of the view when it has an instance to follow (this can be set with the view_object variable or in the room editor). Care should be taken when setting this value, as setting it too low can result in the instance moving faster than the view can and so it may disappear out one side of the view until it stops and the view catches it again.

Example:

view_hspeed[0] = view_object[0].hspeed;
view_vspeed[0] = view_object[0].vspeed;

The above code sets the speed of the view following to be the same as the currently selected follow object.

Back: Views
Next: view_vspeed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_hview

Height of the view in the room.

Syntax:

view_hview[0...7]

Returns: Real

Description

This variable can be used to get or to set the height of the view in the room. By changing this value you can change the amount of a room that you can see through the view, but bear in mind that this does not change the view port so setting a view height larger than the view port height will result in the view being scaled down to fit the port, just as a view height smaller than the port height will scale the view up to fit. The following image illustrates this:

Example:

var ratio;
ratio = view_hport[0] / view_wport[0];
view_wview[0] -= sc_amt;
view_hview[0] -= sc_amt * ratio;

The above code will scale the view width and height based on the ratio of the view port width and height.

Back: Views
Next: view_wview

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_object

Object whose instance must remain visible in the view.

Syntax:

view_object[0...7]

Returns: Real

Description

With this variable you can get (or set) the object that has to be kept in the specified view (from 0 to 7) at all times. If there are multiple instances of this object, only one is followed (usually the first one created, but this is not guaranteed). You can also assign a single instance id to this variable, in which case that particular instance is followed. To prevent any view following, you can set this variable using the special keyword noone.

NOTE: You can set the distance that an instance or object can move before the view starts following using the view_hborder and view_vborder functions.

Example:

if instance_exists(obj_Player)
{
view_object[0] = obj_player;
}

The above code checks to see if an instance of the object "obj_Player" exists and if it does, it sets view[0] to follow that instance.

Back: Views
Next: view_angle

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_surface_id

Assign a surface to a view.

Syntax:

view_surface_id[0...7]

Returns: Real

Description

With this variable you can set a given view to draw to a surface, or get the current surface id if one has been assigned to a view. When working with surfaces, it is often required that you draw the whole visible region of the screen to the surface, and so you would assign it to a view using this function. This means that everything that is shown in the chosen view will now be drawn to the assigned surface. The view will now not be drawn to the screen, meaning that you will need to do either:

  • Enable a new view and draw the surface only in that view (using view_current to check which view is being drawn)

  • Draw the surface in the Draw GUI event of an instance, since the GUI layer is independent of views.

You can also read this variable to get the index of the surface that has been assigned to the chosen view or it will return -1 if no surface has been assigned, and generally the surface used for this function should be the size of the view itself (not the view port). The extended example below shows a basic setup for capturing a view and drawing it in the Draw GUI event, and for more information on surfaces see the section Reference - Surfaces.

Extended Example:

In this extended example, we will create a surface and assign it to view 0, then draw that to the screen in the Draw GUI event. To start with we need to initialise our surface variable in the Create Event of a controller instance:

surf = -1;

We set the surface variable to -1, as all surface functions should really be used in the Draw events to prevent odd errors or undefined behaviours. So, with that done, we would then have this in the main Draw event:

if !surface_exists(surf)
{
surf = surface_create(view_wview[0], view_hview[0]);
view_surface_id[0] = surf;
}

Surfaces are volatile meaning that they could be removed from memory at any time due to OS memory management and other things, so here we check to see if our surface exists and if it doesn't we create it and assign it to the view 0. With that done, everything that would appear in view 0 will now be drawn to the surface we have created instead. If you do nothing else at this point, when you run your game you will simply get a blank screen as all drawing is being done on the surface, but the surface itself is not being drawn anywhere. Therefore we now need to draw the surface to the screen in the Draw GUI event like this:

if surface_exists(surf)
{
draw_surface_stretched(surf, 0, 0, display_get_gui_width(), display_get_gui_height());
}

This code will now draw the surface that we have created from the view stretched to fill the entire GUI layer.

Back: Views
Next: window_view_mouse_get_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_vborder

Size of vertical border for view following.

Syntax:

view_vborder[0...7]

Returns: Real

Description

This variable sets the vertical border width for view following. You can set the view to follow a specific instance using the view_object variable (or in the room editor) and by setting this value you can control how near or far from the edge of the view the instance needs to be before the view will move. For example, if you have a view height of 240 and set the vertical view border to 120, the object that the view must follow will always be in the middle of the view. However, make the vertical view border 0 and the instance must be right on the edge of the view before it will move.

NOTE: if you are not setting the x and y position of the view manually, the view never leaves the boundaries of the room. This means that when the view reaches the edge of a room, the horizontal and vertical borders are ignored and the instance will move freely within the view.

Example:

view_hborder[0] = view_wview[0] / 2;
view_vborder[0] = view_hview[0] / 2;

The above code will set the view follow borders to half the width and height of the view, effectively forcing the view to always be centered on the follow object.

Back: Views
Next: view_hspeed

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_visible

Whether the particular view is visible on the screen.

Syntax:

view_visible[0...7]

Returns: Boolean

Description

This variable can be used to find out if a particular view is currently visible or not. You can also set this variable to effectively turn "on" or "off" a view by setting the value to true (visible) or false (invisible).

Example:

if !view_visible[0]
{
view_visible[0] = true;
}

The above code checks to see if view[0] is visible or not and if it is not, it then sets it to be visible.

Back: Views
Next: view_object

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_vspeed

Maximal vertical speed of the view.

Syntax:

view_vspeed[0...7]

Returns: Real

Description

This variable controls the vertical movement speed of the view when it has an instance to follow (this can be set with the view_object variable or in the room editor). Care should be taken when setting this value, as setting it too low can result in the instance moving faster than the view can and so it may disappear out one side of the view until it stops and the view catches it again.

Example:

view_hspeed[0] = view_object[0].hspeed;
view_vspeed[0] = view_object[0].vspeed;

The above code sets the speed of the view following to be the same as the currently selected follow object.

Back: Views
Next: view_xport

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_wport

Width of the viewport in the drawing region.

Syntax:

view_wport[0...7]

Returns: Real

Description

This variable can be used to get or to set the width of the specified viewport. The width of the viewport (or combined view ports if more than one are active) define the width of the game window or background canvas at the start of the game, but changing this value after the game has started will have no visible effect on the game window size. If you have a larger or smaller port size than that assigned to the view, the view will be scaled down or up to fit, as illustrated by the image below.

Example:

view_hview[0] = view_hport[0]; view_wview[0] = view_wport[0];

The above code sets the width and height of the view to be the same as the width and height of the view port.

Back: Views
Next: view_surface_id

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_wview

Width of the view in the room.

Syntax:

view_wview[0...7]

Returns: Real

Description

This variable can be used to get or to set the width of the view in the room. By changing this value you can change the amount of a room that you can see through the view, but bear in mind that this does not change the view port so setting a view width larger than the view port width will result in the view being scaled down to fit the port, just as a view width smaller than the port width will scale the view up to fit. The following image illustrates this:

Example:

var ratio;
ratio = view_hport[0] / view_wport[0];
view_wview[0] -= sc_amt;
view_hview[0] -= sc_amt * ratio;

The above code will scale the view width and height based on the ratio of the view port width and height.

Back: Views
Next: view_hborder

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_xport

The x-position of the viewport within the drawing region.

Syntax:

view_xport[0...7]

Returns: Real

Description

With this variable you can get or set the x position of the view port. The view port is the area on the screen where the view is drawn. Now, the default for GameMaker: Studio is that the game window (or background canvas) is the same size as the room, however when you activate views, this behaviour changes and the total size of the bounding box for all view ports is used. So, if you have two different view ports at two different positions, the total area that they cover defines the size of the game window. The following image illustrates this:

If you only have one view active (and so only one view port) setting the x or y value of the port can have some interesting effects but is not normally practical (see the image below) and so it is better to maintain the x and y position as (0,0).

Example:

view_xport[0] = 0; view_yport[0] = 0;

The above code resets the position of view port[0] to the (0,0) position (top left hand corner) of the display.

Back: Views
Next: view_yport

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_xview

X position of the view in the room.

Syntax:

view_xview[0...7]

Returns: Real

Description

This variable can be used to get or to set the x axis position for the view in the room. By changing this value you can set the view to a new position, with (0,0) being the upper left corner of the room, or you can reference this variable to ensure that an instance is always drawn at a relative position to the view (see example code below). This value can also be negative and so show an area that is outside of the room, in which case the window colour will be used (this colour can be set with window_set_colour).

Example:

draw_text(view_xview[0] + 32, view_yview[0] + 32, "Score: " + string(score));

The above code will draw the score at a position relative to the x and y coordinates of view[0].

Back: Views
Next: view_yview

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_yport

The y-position of the viewport within the drawing region.

Syntax:

view_yport[0...7]

Returns: Real

Description

With this variable you can get or set the y position of the view port. The view port is the area on the screen where the view is drawn. Now, the default for GameMaker: Studio is that the game window (or background canvas) is the same size as the room, however when you activate views, this behaviour changes and the total size of the bounding box for all view ports is used. So, if you have two different view ports at two different positions, the total area that they cover defines the size of the game window. The following image illustrates this:

If you only have one view active (and so only one view port) setting the x or y value of the port can have some interesting effects but is not normally practical (see the image below) and so it is better to maintain the x and y position as (0,0).

Example:

view_xport[0] = 0;
view_yport[0] = 0;

The above code resets the position of view port[0] to the (0,0) position (top left hand corner) of the display.

Back: Views
Next: view_hport

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


view_yview

Y position of the view in the room.

Syntax:

view_yview[0...7]

Returns: Real

Description

This variable can be used to get or to set the y axis position for the view in the room. By changing this value you can set the view to a new position, with (0,0) being the upper left corner of the room, or you can reference this variable to ensure that an instance is always drawn at a relative position to the view (see example code below). This value can also be negative and so show an area that is outside of the room, in which case the window colour will be used (this colour can be set with window_set_colour).

Example:

draw_text(view_xview[0] + 32, view_yview[0] + 32, "Score: " + string(score));

The above code will draw the score at a position relative to the x and y coordinates of view[0].

Back: Views
Next: view_hview

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_view_mouse_get_x

Returns the x coordinate of the mouse in the window with respect to the given view.

Syntax:

window_view_mouse_get_x( id );

Argument | Description
id | The id of the view to compare the mouse position to.

Returns: Real

Description

This function will return the mouse x position relative to the view selected. The following image illustrates how this works:

NOTE: For regular mouse functions see the section on Mouse Input.

Example:

if mouse_check_button_pressed(mb_left)
{
var xx, yy;
xx = window_view_mouse_get_x(0);
yy = window_view_mouse_get_y(0);
if xx > 0 && xx < 32 && yy > 0 && yy < 32
{
b_press[0] = true;
}
}

The above code will check for a mouse button being pressed, and if it is it then gets the mouse position relative to the view[0] and compares it to see if a variable should be set to true.

Back: Views
Next: window_view_mouse_get_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_view_mouse_get_y

Returns the y coordinate of the mouse in the window with respect to the given view.

Syntax:

window_view_mouse_get_y( id );

Argument | Description
id | The id of the view to compare the mouse position to.

Returns: Real

Description

This function will return the mouse y position relative to the view selected. The following image illustrates how this works:

NOTE: For regular mouse functions see the section on Mouse Input.

Example:

if mouse_check_button_pressed(mb_left)
{
var xx, yy;
xx = window_view_mouse_get_x(0);
yy = window_view_mouse_get_y(0);
if xx > 0 && xx < 32 && yy > 0 && yy < 32
{
b_press[0] = true;
}
}

The above code will check for a mouse button being pressed, and if it is it then gets the mouse position relative to the view[0] and compares it to see if a variable should be set to true.

Back: Views
Next: window_views_mouse_get_x

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_views_mouse_get_y

window_views_mouse_get_x

Returns the x-coordinate of the mouse with respect to the views.

Syntax:

window_views_mouse_get_x();

Returns: Real

Description

This function returns the x-coordinate of the mouse with respect to all the active views and returns the same value mouse_x.

NOTE: For regular mouse functions see the section on Mouse Input.

Example:

myx = window_views_mouse_get_x();

This would set myx to the x coordinate of the mouse in the window relative to all active views.

Back: Views
Next: window_views_mouse_get_y

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


window_views_mouse_get_y

Returns the y-coordinate of the mouse with respect to the views.

Syntax:

window_views_mouse_get_y();

Returns: Real

Description

This function returns the y-coordinate of the mouse with respect to all the active views and returns the same value mouse_y.

NOTE: For regular mouse functions see the section on Mouse Input.

Example:

myy = window_views_mouse_get_y();

This would set myy to the y coordinate of the mouse in the window relative to all active views.

Back: Views
Next: view_enabled

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Windows 8

These functions are provided specifically for the Windows 8 platform.

The Windows 8 module has some functions that are specifically designed to be used by the games that target it. These functions make the most of the Windows 8 tile system as well as permitting you to access and share files from within your game. The following functions have been split into the relevant sections to make finding the right one for your needs easier. Please note that these functions are for the Windows 8 desktop and Surface platforms, not Windows 8 Phone. For Windows 8 Phone please see the following section:

  1. Windows 8 Phone

NOTE: The Windows 8 (JS and Native) target won't allow multiple instances of the same app to run at a time, and if the file is running it can't overwrite it. This means that you will have to close the app before saving/testing a new version, and even then you may have to wait a short period of time between builds to enable Windows to close the app correctly.

Windows 8 games can run on devices that may, or may not, have a touch screen. This means that your games have to be developed with this in mind. To make things easier for you there is a special function for detecting whether the device running the game is touch enabled or not:

  1. win8_device_touchscreen_available

WARNING: If you have any functions in your Windows 8 game that require an internet connection, like an open URL call for example, then you must have the "Use Internet" capability ticked for the game in the Global Game Settings. Microsoft also specifies that if you use this capability you need to add a link to your Privacy Policy in the Settings pane of your Windows 8 game (see here as well as the functions for using the Settings Charm for further details).

Live Tiles

With the Windows 8 OS your game (or app) will be associated with its own Live Tile. A live tile is a dynamic link to your game which updates in real time, meaning that you can "push" images and text onto them for the user to see at specific times form your game. The following functions are the recommended method for creating Live Tile notifications:

  1. win8_livetile_notification_begin
  2. win8_livetile_notification_secondary_begin
  3. win8_livetile_notification_expiry
  4. win8_livetile_notification_tag
  5. win8_livetile_notification_text_add
  6. win8_livetile_notification_image_add
  7. win8_livetile_notification_end

However, there also exists the following legacy function (which should only be used if absolutely necessary):

  1. win8_livetile_tile_notification

Apart from pushing notifications to the main tile there are also a number of further things that can be done, like adding a badge or clearing the tile, using the following functions:

  1. win8_livetile_tile_clear
  2. win8_livetile_badge_notification
  3. win8_livetile_badge_clear
  4. win8_livetile_queue_enable

You also have access to the Secondary Live Tile. This is a second type of Live Tile that can be pinned to the main start page and used to access a specific section of your game, for example a saved game. It can be quite tricky to set up and get working as you need to supply certain command line parameters which will be parsed later by your game when it is called on from the secondary tile (using the parameter_string function). The following is a list of all the secondary tile functions:

NOTE: a Secondary Tile will include all of the mandatory properties used to create the standard wide tile.

  1. win8_secondarytile_pin
  2. win8_secondarytile_badge_notification
  3. win8_secondarytile_delete

You can find a list of the available Template Strings available for some of the Live Tile functions here:

  1. Windows 8 Live Tile Templates

Appbar commands

The App Bar is a special bar of buttons that can be made to pop up by right clicking on your game. These buttons can be defined through the following functions and linked to scripts within GameMaker: Studio to create pause menus, options etc...:

  1. win8_appbar_enable
  2. win8_appbar_add_element
  3. win8_appbar_remove_element

Settings Charm

When in your game, if you move the mouse to the top right (or bottom right) of the screen, a side-bar slides out that shows different "charms" (icons). These functions give you the ability to add custom options to the "Settings" charm, either through internal scripts, or external XAML formatted files:

  1. win8_settingscharm_add_entry
  2. win8_settingscharm_add_html_entry
  3. win8_settingscharm_add_xaml_entry
  4. win8_settingscharm_set_xaml_property
  5. win8_settingscharm_get_xaml_property
  6. win8_settingscharm_remove_entry

Share

These functions are effectively an advanced "Cut and Paste" option for Windows 8 and permit you to send information as either text, an image, a file or even as a URL:

  1. win8_share_image
  2. win8_share_screenshot
  3. win8_share_file
  4. win8_share_url
  5. win8_share_text

Search

Windows 8 can permit your game to search through the system as you would any other window. These functions control this:

  1. win8_search_enable
  2. win8_search_add_suggestions
  3. win8_search_disable

Trial Play

The Windows 8 App Store permits your game to be marketed with a trial period. This will let people play your game for a limited time with (if you choose) limited features and then, at the end of the trial period, it will prompt the user to buy the full version. The following functions can be used in your games:

  1. win8_license_trial_version
  2. win8_license_initialize_sandbox

Back: Reference

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_appbar_add_element

Add an element to the slide-out App Bar at the bottom of your game.

Syntax:

win8_appbar_add_element(type, icon, label, section, tooltip, callback);

Argument | Description
type | The type of element to add, either "button" or "separator".
icon | The icon name.
label | The icon label.
section | The section of the App Bar to add the element too. Either "selection" or "global".
tooltip | the tool-tip string to explain the button on hover
callback | The script to call when the element is used (-1 for no callback).

Returns: string

Description

This function will add an element to the App Bar for your game (the App Bar is accessed by right clicking on your game, but will only appear if you have enabled it using the function win8_appbar_enable). The function will return a unique identifier as a string that you can store to use in other functions later.

You must first choose whether to add a "button" or a "separator", and then pick an icon for it if it is a button (for a separator you should use an empty string "" for this). For a complete list of all icons available for the App Bar please see here.

Next you have the label which is a short name that will be placed beneath the icon (this can be an empty string "" if you wish), and then you should set the section of the App Bar that you want the element to be added to. The section string "global" maps to the right of the App Bar and "selection" maps to left in LTR (left-to-right) layouts (the opposite is true in RTL (right-to-left) layouts).

Finally you have to give it a tooltip so that when your player hovers the mouse over it they can get some information on what it does, and a callback script. The callback script will be run whenever the button is pressed (if it is a separator, or you do not wish to do anything, you can set this to -1).

Example:

win8_appbar_enable(true);
elementId[0] = win8_appbar_add_element("button", "repair", "Game Settings", "selection", "Change the global game settings", scr_Settings);
elementId[1] = win8_appbar_add_element("button", "pause", "Pause/Unpause", "selection", "Pause or unpause the game", scr_PauseGame);
elementId[2] = win8_appbar_add_element("button", "clear", "Quit", "global", "Quit to desktop", scr_QuitGame);

The above code will switch on the App Bar, then add three buttons to it. The first two are on the left and will run a script to change the game settings or pause/unpause the game, while the third will run a script to end the game. All three have their unique id stored in an array in case we need to access them later.

Back: Windows 8
Next: win8_appbar_remove_element

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_appbar_enable

Enable the App Bar for the game.

Syntax:

win8_appbar_enable(enabled);

Argument | Description
enabled | Set to true to enable the App Bar and false to disable.

Returns: N/A

Description

This function can be used to switch on (true) or off (false) the App Bar for your game. The App Bar is accessed by clicking the Right Mouse Button while in your game and, if it is on, then you can add your own custom buttons to it. If this is set to off, then the App Bar is disabled (the default value is false).

Example:

win8_appbar_enable(true);
win8_appbar_add_element("button", "mute", "Mute/Unmute Music", "selection", "Toggle the music on or off", scr_MusicSwitch);

The above code will switch on the App Bar, then add a button to it to mute the music.

Back: Windows 8
Next: win8_appbar_add_element

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_appbar_remove_element

Remove a previously defined element from the App Bar.

Syntax:

win8_appbar_remove_element(id);

Argument | Description
id | The id string of the element to be removed.

Returns: N/A

Description

With this function you can remove a previously defined element from the App Bar for your game. The element id is the one that is returned when using the function win8_appbar_add_element.

Example:

var i;
for (i = 0; i < 3; i += 1)
{
win8_appbar_remove_element(ab_element[i]);
}

The above code will remove three elements that have been created and had their ids stored in the variable array "ab_element" from the App Bar.

Back: Windows 8
Next: win8_settingscharm_add_entry

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_device_touchscreen_available

Check to see if the Windows 8 device has a touchscreen or not.

Syntax:

win8_device_touchscreen_available();

Returns: Boolean

Description

This function will check the device running your game and return true if it is touch screen enabled (like a Surface RT device) or false if it is not (like a desktop PC).

Example:

if win8_device_touchscreen_available()
{
vk[2] = virtual_key_add(32, display_get_height() - 128, 64, 64, vk_left);
vk[1] = virtual_key_add(128, display_get_height() - 128, 64, 64, vk_right);
vk[0] = virtual_key_add(display_get_width() - 96, display_get_height() - 128, 64, 64, vk_up);
}

The above code will check for touch screen availability and if it is enabled, create three virtual keys.

Back: Windows 8
Next: win8_livetile_tile_notification

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_license_initialize_sandbox

Initialize a sandbox with the trial properties for licencing.

Syntax:

win8_license_initialize_sandbox(xml);

Argument | Description
xml | The xml that defines the sandbox licence, as a string.

Returns: N/A

Description

This function enables a sandbox environment in which you can test the Trial Play features of your game on Windows 8. The function takes a string containing the XML that will define the sandbox. You can find complete details of all the possible settings from Microsoft here and the example code below gives a basic working string that you can use as a base.

Example:

var license;
license = '<?xml version="1.0" encoding="utf-16" ?>
<CurrentApp>
<ListingInformation>
<App>
<AppId>988b90e4-5d4d-4dea-99d0-e423e414ffbc</AppId>
<LinkUri></LinkUri>
<CurrentMarket>en-us</CurrentMarket>
<AgeRating>3</AgeRating>
<MarketData xml:lang="en-us">
<Name></Name>
<Description></Description>
<Price>0.99</Price>
<CurrencySymbol>$</CurrencySymbol>
<CurrencyCode>USD</CurrencyCode>
</MarketData>
</App>
</ListingInformation>
<LicenseInformation>
<App>
<IsActive>false</IsActive>
<IsTrial>true</IsTrial>
</App>
</LicenseInformation>
</CurrentApp>';
win8_license_initialize_sandbox(license);

The above code will create a sandbox to trial play your game, using the given string as the XML template.

Back: Windows 8
Next: win8_livetile_notification_begin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_license_trial_version

Return the state of the Trial Play for your Windows 8 game.

Syntax:

win8_license_trial_version();

Returns: Boolean

Description

This function will return true if your game is currently in Trial Play, or false if it is not. You can use this function to block features or limit game-play while your game is on trial by the user.

Example:

if win8_license_trial_version()
{
global.Level_Max = 20;
}
else
{
global.Level_max = 100;
}

The above code will check the status of your game and if it is on trial Play it will set the global variable "level_Max" to 20, otherwise it will be set to 100.

Back: Windows 8
Next: win8_license_initialize_sandbox

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_livetile_badge_clear

Clear the current badge from the Live Tile.

Syntax:

win8_livetile_badge_clear();

Returns: N/A

Description

This function clears the current badge from the Live Tile of your game.

Example:

if keyboard_check_pressed(ord("P"))
{
if global.Pause
{
global.Pause = false;
win8_livetile_badge_clear();
}
else
{
global.Pause = true;
win8_livetile_badge_notification("paused");
}
}

The above code will check for the key "P" being pressed and if it is detected, it will toggle the global variable "Paused" to true or false and push a badge onto the Live Tile (or remove it again) based on the value of this variable.

Back: Windows 8
Next: win8_livetile_queue_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_livetile_badge_notification

Create a badge on the game's live tile.

Syntax:

win8_livetile_badge_notification(id);

Argument | Description
id | This is the badge id and can either be a number or an icon from the badge catalogue.

Returns: N/A

Description

This function will "push" a badge onto the Live Tile of your game. The badge is a small square are on the bottom right of your games Live Tile and can show either a number from 0 to 99 (any value over 99 will be shown as "+99"), or a badge icon. Icons are decided based on the icon string that you pass through the function, which can be any of the following:

NOTE: The background colour for these icons will depend on what you have defined in the "Logos" part of the General section of the Windows 8 tab in the Global Game Settings.

Icon String | Badge Catalogue Image
none | No Badge Shown
activity |
alert |
available |
away |
busy |
unavailable |
newMessage |
paused |
playing |
error |
attention |

Example:

if keyboard_check_pressed(ord("P"))
{
if global.Pause
{
global.Pause = false;
win8_livetile_badge_clear();
}
else
{
global.Pause = true;
win8_livetile_badge_notification("paused");
}
}

The above code will check for the key "P" being pressed and if it is detected, it will toggle the global variable "Paused" to true or false and push a badge onto the Live Tile (or remove it again) based on the value of this variable.

Back: Windows 8
Next: win8_livetile_badge_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_livetile_notification_begin

Set the Windows 8 Live Tile template to be used by other Windows 8 functions.

Syntax:

win8_livetile_notification_begin(template);

Argument | Description
template | The template that the live tile notification should use (a string, see Live Tile Templates)

Returns: N/A

Description

To create a Live Tile notification you must use several GameMaker: Studiofunctions, starting with this one. This function takes a "template" and prepares GameMaker: Studio to fill it with the necessary information (using the rest of the Live Tile functions), before pushing it to Windows 8 using the win8_livetile_notification_end() function.

You can find a list of templates here and a complete overview for each one can be found from the Microsoft help pages here.

Live Tile notifications can be queued so that they show one after another, but to do that you must define each of them individually using the Windows 8 functions calling the "begin" and "end" functions each time (you can't call "begin" and then define 4 different notifications then "end" to push them to Windows 8).

NOTE: You can only queue up to 5 Live Tile notifications, and you must have activated queuing with the function win8_livetile_queue_enable.

Example:

var expiryTime;
expiryTime = date_current_datetime();
expiryTime = date_inc_minute(expiryTime, 5);
win8_livetile_notification_begin("TileSquarePeekImageAndText01");
win8_livetile_notification_expiry(expiryTime);
win8_livetile_notification_tag("tag0");
win8_livetile_notification_text_add("Current Score = " + string(score));
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "ScoreTile.png");
win8_livetile_notification_end();

The above code will push a new Live Tile notification through to Windows 8, with some text and an image, and the tile will be shown for 5 minutes.

Back: Windows 8
Next: win8_livetile_notification_secondary_begin


win8_livetile_notification_end

End the definition of a Live Tile notification.

Syntax:

win8_livetile_notification_end();

Returns: N/A

Description

This function must be called after defining a Live Tile notification to "push" it onto the Windows UI Live Tile for your game. The notification will be shown on the Live Tile for your game unless you have previously enabled queuing (using, win8_livetile_queue_enable), in which case it will be added onto the notification queue and will be shown after all previous notifications have been shown. This function requires you to have previously selected a Live tile template using win8_livetile_notification_begin, and set up the necessary text, images and tags using the appropriate Windows 8 functions.

NOTE: This function is also used to push notifications to Secondary tiles when used along with win8_livetile_notification_secondary_begin.

Example:

var expiryTime;
expiryTime = date_current_datetime();
expiryTime = date_inc_minute(expiryTime, 5);
win8_livetile_notification_begin("TileSquarePeekImageAndText01");
win8_livetile_notification_expiry(expiryTime);
win8_livetile_notification_tag("tag0");
win8_livetile_notification_text_add("Current Score = " + string(score));
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "ScoreTile.png");
win8_livetile_notification_end();

The above code will push a new Live Tile notification through to Windows 8, with some text and an image, and the tile will be shown for 5 minutes.

Back: Windows 8
Next: win8_livetile_tile_notification

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_livetile_notification_expiry

Set the expiry time for the notification push on the live (or Secondary) Tile.

Syntax:

win8_livetile_notification_expiry(expiry_time);

Argument | Description
expiry_time | Sets the time at which the notification should be cancelled.

Returns: N/A

Description

Use this function after calling win8_livetile_notification_begin to give the Windows 8 Live Tile an expiry time. This time is that at which the notification should be removed and is best calculated using the GameMaker: Studio Date and Time functions, as shown in the example below (setting this to -1 will show the notification indefinitely until you use the win8_livetile_tile_clear.

NOTE: This function can also apply to Secondary tiles when used along with win8_livetile_notification_secondary_begin.

Example:

var expiryTime;
expiryTime = date_current_datetime();
expiryTime = date_inc_minute(expiryTime, 5);
win8_livetile_notification_begin("TileSquarePeekImageAndText01");
win8_livetile_notification_expiry(expiryTime);
win8_livetile_notification_tag("tag0");
win8_livetile_notification_text_add("Current Score = " + string(score));
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "ScoreTile.png");
win8_livetile_notification_end();

The above code will push a new Live Tile notification through to Windows 8, with some text and an image, and the tile will be shown for 5 minutes.

Back: Windows 8
Next: win8_livetile_notification_tag

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_livetile_notification_image_add

Add images to a Live Tile notification.

Syntax:

win8_livetile_notification_image_add(image);

Argument | Description
image | The template that the live tile notification should take (see below)

Returns: N/A

Description

This function can be used to define an image for a Live Tile notification. You must have called win8_livetile_notification_begin before using this function, and you may need to call this it more than once if the Live Tile Template requires it. The image can be either from a local source (in which case the directory to get the file from must be preceded by ms-appx:///. See the example given below.) or from a URL.

NOTE: This function can also apply to Secondary tiles when used along with win8_livetile_notification_secondary_begin.

Example:

var expiryTime;
expiryTime = date_current_datetime();
expiryTime = date_inc_minute(expiryTime, 5);
win8_livetile_notification_begin("tileWideImageCollection");
win8_livetile_notification_expiry(expiryTime);
win8_livetile_notification_tag("tag0");
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "WideTile_Logo.png");
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "WideTile_SmallScreen_1.png");
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "WideTile_SmallScreen_2.png");
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "WideTile_SmallScreen_3.png");
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "WideTile_SmallScreen_4.png");
win8_livetile_notification_end();

The above code will push a new Live Tile notification through to Windows 8, with 5 images will shown for 5 minutes.

Back: Windows 8
Next: win8_livetile_notification_end

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_livetile_notification_secondary_begin

Set the Windows 8 Live Tile template to be used by other Windows 8 functions to create a Secondary Tile.

Syntax:

win8_livetile_notification_secondary_begin(template, tile_id);

Argument | Description
template | The template that the secondary tile notification should take (a string, see Live Tile Templates)
tile_id | The tile id that identifies the secondary tile (a string).

Returns: N/A

Description

This function is similar in use to that of win8_livetile_notification_begin, only here we are telling GameMaker: Studio that the tile you are to define is going to be a secondary tile. Secondary tiles must first be created, given a unique tile id and then pinned to the Windows 8 UI using the function before being modified in any way.

Example:

var expiryTime;
expiryTime = date_current_datetime();
expiryTime = date_inc_minute(expiryTime, 5);
win8_livetile_notification_secondary_begin("TileSquarePeekImageAndText01", "secondary");
win8_livetile_notification_expiry(expiryTime);
win8_livetile_notification_tag("tag0");
win8_livetile_notification_text_add("Current Score = " + string(score));
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "ScoreTile.png");
win8_livetile_notification_end();

The above code will push a new Live Tile notification through to the Secondary tile that you have previously pinned to the Windows 8 UI.

Back: Windows 8
Next: win8_livetile_notification_expiry

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_livetile_notification_tag

Set the "tag" for the Live Tile.

Syntax:

win8_livetile_notification_tag(tag);

Argument | Description
tag | The name "tag" of the notification.

Returns: N/A

Description

The tag is a string that you assign to the Live tile notification as a means to identify it later. Should you need to replace a Live Tile, or update it with another template or image, you would formulate another notification push (starting with the function win8_livetile_notification_begin) and use the same tag as in this function as that which you wish to change/replace.

You must have activated queuing with the function win8_livetile_queue_enable for this to function to be of any use as without queuing enabled, no matter what tag you use, any Live Tile notifications will overwrite the current Live tile rather than add a new one to the queue or modify an already queued one.

NOTE: This function can also apply to Secondary tiles when used along with win8_livetile_notification_secondary_begin.

Example:

var expiryTime;
expiryTime = date_current_datetime();
expiryTime = date_inc_minute(expiryTime, 5);
win8_livetile_notification_begin("TileSquarePeekImageAndText01");
win8_livetile_notification_expiry(expiryTime);
win8_livetile_notification_tag("tag0");
win8_livetile_notification_text_add("Current Score = " + string(score));
win8_livetile_notification_image_add("ms-appx:///" + working_directory + "ScoreTile.png");
win8_livetile_notification_end();

The above code will push a new Live Tile notification through to Windows 8, with some text and an image, and the tile will be shown for 5 minutes.

Back: Windows 8
Next: win8_livetile_notification_text_add


win8_livetile_notification_text_add

Add text to a Live Tile notification.

Syntax:

win8_livetile_notification_text_add(text);

Argument | Description
text | The text to be displayed by the Live Tile.

Returns: N/A

Description

This function can be used to define a line of text for a Live Tile notification. You must have called win8_livetile_notification_begin before using this function, and you may need to call this it more than once if the Live Tile Template requires it.

NOTE: This function can also apply to Secondary tiles when used along with win8_livetile_notification_secondary_begin.

Example:

var expiryTime;
expiryTime = date_current_datetime();
expiryTime = date_inc_minute(expiryTime, 5);
win8_livetile_notification_begin("tileWideText05");
win8_livetile_notification_expiry(expiryTime);
win8_livetile_notification_tag("tag0");
win8_livetile_notification_text_add("Current Score = " + string(score));
win8_livetile_notification_text_add("");
win8_livetile_notification_text_add("Current Lives = " + string(lives));
win8_livetile_notification_text_add("");
win8_livetile_notification_text_add("Current Time = " + string(time));
win8_livetile_notification_end();

The above code will push a new Live Tile notification through to Windows 8, with 5 lines of text that will shown for 5 minutes.

Back: Windows 8
Next: win8_livetile_notification_image_add


win8_livetile_queue_enable

Enable Live Tile notification queues.

Syntax:

win8_livetile_queue_enable(enabled);

Argument | Description
enabled | Set to true to enable notification queuing and false to disable.

Returns: N/A

Description

This function can be used to switch on (true) or off (false) notification queuing. If it is on, then you can push up to five notifications onto your games Live Tile and they will be queued and shown one after the other. If this is set to off, then notifications will overwrite each other. This is set to false (queuing off) by default.

Example:

win8_livetile_queue_enable(true);

The above code will switch notification queuing on for your games Live Tile.

Back: Windows 8
Next: win8_secondarytile_pin

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_livetile_tile_clear

Clear a Live tile of its current notifications.

Syntax:

win8_livetile_tile_clear();

Returns: N/A

Description

This function can be used to clear any notifications that may be showing currently on the Live Tile for your game. If you have queuing enabled, the next notification in the queue will be shown.

Example:

if !global.Pause
{
win8_livetile_tile_clear();
}

The above code will check a global variable and if it returns false it will clear the Live Tile of the game.

Back: Windows 8
Next: win8_livetile_badge_notification

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_livetile_tile_notification

Send a notification to the game's live tile.

Syntax:

win8_livetile_tile_notification(template, ds_map, expiry, tag);

Argument | Description
template | The template that the live tile notification should take (see below)
ds_map | A ds_map that contains the information for the notification
expiry | How long the notification should be shown
tag | The name "tag" of the notification

Returns: N/A

Description

This function will "push" a notification through to the live tile associated with your game. What exact information is sent will depend greatly on the template that you choose to use (you can find a complete list of the available templates here), as each template requires a different combination of text and/or images.

The ds_map that is sent along with the template, must contains the appropriate key-value pairs for that template, so for each entry the key should refer to the tag name of an element and the value (which can be either a single value or an array of multiple entries, in which case you should add them into a ds_list, then embed the ds_list into the ds_map). The tag names themselves can only be either "image" or "text", and the image can be either from a local source (in which case the directory to get the file from must be proceeded by ms-appx:///. See the examples given below.) or from a given URL.

The expiry is the time that the notification should be removed at and is best calculated using the GameMaker: Studio Date and Time functions, as shown in the functions below (setting this to -1 will show the notification indefinitely until you use the win8_livetile_tile_clear.

Finally you have the queue "tag". This is a string that you assign to the notification as a means to identify it later, should you need to replace it or update it with another one. in this case you would formulate another notification push with this function and use the same tag as that which you wish to change/replace.

NOTE: You can only queue up to 5 Live Tile notifications, and you must have activated queuing with the function win8_livetile_queue_enable.

Example:

var expiryTime, tileText, tileImage, tileData;
expiryTime = date_current_datetime();
expiryTime = date_inc_minute(expiryTime, 5);
tileText = ds_list_create();
ds_list_add(tileText, "C.T.H.");
ds_list_add(tileText, "This game is paused and awaiting your return!");
tileImage = ds_list_create();
ds_list_add(tileImage, "ms-appx:///" + working_directory + "WideTile_Screenshot.png");
ds_list_add(tileImage, "ms-appx:///" + working_directory + "MiniLogo.png");
tileData = ds_map_create();
ds_map_add(tileData, "text", tileText);
ds_map_add(tileData, "image", tileImage);
win8_livetile_tile_notification("tileWidePeekImage05", tileData, expiryTime, "Paused");
ds_list_destroy(tileText);
ds_list_destroy(tileImage);
ds_map_destroy(tileData);

The above code is for a wide tile, and it needs two lines of text (a header, and one line of long text), and two images (one large one for the whole tile, and one smaller one for beside the text), as this template will switch between the main image and the image/text combination. You need to add the text into a ds_list, with the first entry being the header, and then add the images into another, separate, ds_list, again, with the first image being the larger. Finally you add the text and the image lists into the ds_map, assigning them the appropriate key, and then use the function to send them to the live tile.

Back: Windows 8
Next: win8_livetile_tile_clear

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_search_add_suggestions

Set the search terms from a list of keywords.

Syntax:

win8_search_add_suggestions(list);

Argument | Description
list | a ds_list that holds all the search terms

Returns: N/A

Description

This function uses a ds_list to set a series of keyword search terms that the "search charm" will find if used.

Example:

win8_search_enable(scr_SearchWords);
var list;
list = ds_list_create();
ds_list_add(list, "smelly fish");
ds_list_add(list, "Haggis");
ds_list_add(list, "MacSweeney");
ds_list_add(list, "the quick brown fox");
ds_list_add(list, "99 red ballons");
win8_search_add_suggestions(list);
ds_list_destroy(list);

The above code will enable the search functions for your app and tell Windows to run the callback script should it find a corresponding search term. Some keywords are then added into a ds_list which is used to create the search terms that the "search charm" will find when used.

Back: Windows 8
Next: win8_search_disable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_search_disable

Disable the "search charm" for your game.

Syntax:

win8_search_disable();

Returns: N/A

Description

This function will switch off the ability to search your game for keywords using the "search charm".

Example:

win8_search_disable()

The above code will switch off the search functions for your game.

Back: Windows 8
Next: win8_license_trial_version

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_search_enable

Enable the "search charm" for your game.

Syntax:

win8_search_enable(callback);

Argument | Description
callback | The script to run should a search result come in

Returns: N/A

Description

This function enables the search function to register your game and include it in any results from the "search charm" of Windows 8. The callback script should take an argument[0] which is the returned search string that is passed to it when run, but it will only be called if you have supplied a series of search terms using the function win8_search_add_suggestions.

Example:

win8_search_enable(scr_SearchWords);
var list;
list = ds_list_create();
ds_list_add(list, "smelly fish");
ds_list_add(list, "Haggis");
ds_list_add(list, "MacSweeney");
ds_list_add(list, "the quick brown fox");
ds_list_add(list, "99 red ballons");
win8_search_add_suggestions(list);
ds_list_destroy(list);

The above code will enable the search functions for your app and tell Windows to run the callback script should it find a corresponding search term. Some keywords are then added into a ds_list which is used to create the search terms that the "search charm" will find when used.

Back: Windows 8
Next: win8_search_add_suggestions

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_secondarytile_badge_notification

Push a badge notification onto a secondary Live Tile.

Syntax:

win8_secondarytile_badge_notification(data, tile_id);

Argument | Description
data | This is the badge data and can either be a number or an icon from the badge catalogue.
tile_id | The unique identifying string of the tile to use.

Returns: N/A

Description

This function will "push" a badge onto the secondary Live Tile of your game. The tile to push the badge too is defined by the string containing the unique tile id which you gave when you pinned the secondary Live Tile using the function win8_secondarytile_pin. The badge itself is a small square area on the bottom right of the Live Tile and can show either a number from 0 to 99 (any value over 99 will be shown as "+99"), or a badge icon. Icons are decided based on the icon string that you pass through the function, which can be any of the following:

NOTE: The background colour for these icons will depend on what you have defined in the "Logos" part of the General section of the Windows 8 tab in the Global Game Settings.

Icon String | Badge Catalogue Image
none | No Badge Shown
activity |
alert |
available |
away |
busy |
unavailable |
newMessage |
paused |
playing |
error |
attention |

Example:

if keyboard_check_pressed(ord("P"))
{
global.Pause = true;
win8_secondarytile_badge_notification("paused", "SecondaryTile");
}

The above code will check for the key "P" being pressed and if it is detected, it will set the global variable "Paused" to true and push a badge onto the secondary Live Tile.

Back: Windows 8
Next: win8_secondarytile_delete

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_secondarytile_delete

Remove a secondary Live Tile from the Windows 8 UI.

Syntax:

win8_secondarytile_delete(tile_id);

Argument | Description
tile_id | The unique identifying string of the tile to use.

Returns: N/A

Description

This function can be used to remove a secondary Live Tile from the Windows 8 UI. You must provide the unique tile id string, which is defined when you pin the tile to the UI using win8_secondarytile_pin function.

Example:

win8_secondarytile_delete("StoreTile");

The above code will remove the secondary Live Tile with the id "StoreTile".

Back: Windows 8
Next: win8_appbar_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_secondarytile_pin

Pin a secondary Live Tile for your game to the Windows 8 UI.

Syntax:

win8_secondarytile_pin(tile_id, short_name, display_name, cmd_line_args, ds_list_options, image, wide_image, text_col);

Argument | Description
tile_id | A string that will uniquely identify the tile.
short_name | A short name to display directly on the tile (a string).
display_name | A name that is displayed in the tile's tooltip and when showing small tiles (a string).
cmd_line_args | The command line arguments that will be added to the tile (as a string).
ds_list_options | A ds_list that controls whether to show the game name or not on different sized tiles.
image | An image for the normal (square) Live Tile.
wide_image | An image for the wide Live Tile.
text_col | the text colour (either "dark" or "light").

Returns: N/A

Description

This function will pin a secondary tile to the start menu of the Windows 8 UI associated with your game. These secondary tiles are designed to start your game from a certain point, like a save game or a store page. you must give the tile a tile_id string (which will then be used in the other secondary tile functions) and two names, the display name and the short name. The short name is a short string to be displayed directly on the tile (if chosen to do so from the ds_list options, explained below), and the display name is a generally longer descriptive string that will be shown as a "tooltip" when your Live Tile is set to small by the user.

The command line arguments are used to tell the game where to start when launched from the secondary tile, and follow the http format of "value&value". These values will then be parsed using the GML parameter_count and parameter_string functions.

The options to use when pinning a secondary tile must be added first into a ds_list and the index for the ds_list passed through to the function. These options control whether to show the game name on the tile or not and can only be "None" (for no text on either tile), or "ShowNameOnLogo" and "ShowNameOnWideLogo" to show the name on both tiles (you cannot show on one and not the other). These strings are added to the ds_list and the list index used in the function (as shown below).

Finally you need to add in the images that are going to be used for the tile notification, with one image for each of the two sizes (square and wide). These images can be either from a local source (in which case the directory to get the file from must be preceded by ms-appx:///. See the example given below) or from a URL. You can also define the text colour, although the Windows 8 UI limits this to simply "light" or "dark" for the text, with the colour itself being chosen by Windows based on the user settings.

Extended Example:

This extended example provides a brief overview of how you would detect the command line parameters for the pinned secondary tile and make your game react accordingly. The first thing you would need to do is create and pin the Live Tile to the Windows 8 UI using the following code (note that the function arguments are spread over several lines - this is done to make the example legible but it will work fine in GameMaker: Studio, although normally you would have all the arguments on one line):

var optionsList = ds_list_create();
ds_list_add(optionsList, "None");
win8_secondarytile_pin(
"Store.Tile",
"MacSweeney Store",
"The MacSweeney Game Store",
"store=true&appBar=true",
optionsList,
"ms-appx:///" + working_directory + "MacSweeneyStoreTile.png",
"ms-appx:///" + working_directory + "MacSweeneyStoreWideTile.png",
"dark");

This code defines and pins a secondary Live Tile, with the parameters "store" and "appbar" set to true. When the user opens your game using this secondary tile, it will use the command line parameters that you have set, which means that you will need to have an instance in the first room of the game (on loading) to parse the parameters and setup the game accordingly. The following code in an example of how this can be achieved:

for (var i = 0; i < parameter_count(); i ++;)
{
var param = parameter_string(i);
if param == "appBar=enable")
{
win8_appbar_enable(true);
}
if (param == "store=true")
{
room_goto(rm_Store);
}
}

The above code will loop through all the available parameters and setup your game accordingly, in this case by activating the Windows 8 app bar and going to the specified room.

Back: Windows 8
Next: win8_secondarytile_badge_notification


win8_settingscharm_add_entry

Adds an option to the "Settings" charm.

Syntax:

win8_settingscharm_add_entry(name, callback);

Argument | Description
str | The name of the option to add to the charm.
callback | The script (or URL) to run if pressed.

Returns: N/A

Description

When you move your mouse to the top right, or bottom right, corner of the screen in Windows 8 you get a slide-out menu of "charms". These are special global icons that reference certain aspects of the OS. This function can be used to add your own options to the "charm" labelled as "Settings".

The first argument is the name of the option you are adding as a string, and the second argument is the script from your game that you wish the new option to access, or a URL that you wish the charm to open. If you choose a URL then it should be a string and start with http://, for example "http://www.google.co.uk".

Example:

win8_settingscharm_add_entry("Controls", scr_GameControls);

The above code will add an option to the Settings "charm" called "Controls", and when it is selected it will run the script "scr_GameControls".

Back: Windows 8
Next: win8_settingscharm_add_html_entry

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_settingscharm_add_html_entry

Adds an option to the "Settings" charm based on an external HTML file for the Windows 8 JavaScript target module.

Syntax:

win8_settingscharm_add_html_entry(id, name, htmlpath);

Argument | Description
id | The id (a string) of the new options. This must be the same as the "data-win-options" from the HTML file!
name | The name of the option to add to the charm.
htmlpath | Full path to the HTML file to use

Returns: N/A

Description

This function is similar to the win8_settingscharm_add_entry only this time you can define your own slide-out menu and options from an external HTML file.

The "id" argument is given as a string and must be exactly the same as the data-win-options specified in the HTML file you are using (there is an example HTML file here). You can then give your new options a name and finally you need to add in the path to get to the HTML file. You can find an example of how the HTML should be formatted from the YoYo Games Knowledge Base article HTML and XAML Examples For The Windows 8 Settings Charm.

NOTE: This function is for the Windows 8 JavaScript target module only. For Windows 8 Native support, please see win8_settingscharm_add_xaml_entry.

Example:

win8_settingscharm_add_html_entry("defaults", "News", "News.html");

The above code will create a new option within the settings "charm" called "News" which when presses, will open the exported HTML file.

Back: Windows 8
Next: win8_settingscharm_add_xaml_entry

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_settingscharm_add_xaml_entry

Adds an option to the "Settings" charm based on an external XAML file for the Windows 8 Native target module.

Syntax:

win8_settingscharm_add_xaml_entry(name, xamlPath, headerRGB, callback, wide);

Argument | Description
name | The name of the option to add to the charm.
xamlPath | Full path to the XAML file to use
headerRGB | The header colour of the flyout as a hex string, with the format "#RRGGBB".
callback | The script to run if pressed.
wide | Set to true for a wide fly-out or false otherwise.

Returns: String

Description

This function is similar to the win8_settingscharm_add_entry only this time you can define your own slide-out menu and options from an external XAML formatted file.

You can then give your new options a name (a string) to show on the fly-out, then you need to add in the path to get to the XAML file (this should be included in the game package as an Included File). You can also define the header colour of the fly-out as hex value #RRGGBB (for example, #ff40a0) and give a script to be called when the setting has been selected. This script must take the following arguments:

  • argument0: The element name, a string, which should be the same as that specified as the name in the XAML file.
  • argument1: The element type, a string, which can be one of the following:

    • "TextBox - TextChanged event, and the returned data is text content
    • "Button" - Click event with no data returned
    • "ToggleSwitch" - Toggled event, where the returned string is either "True" or "False"
    • "RadioButton" - Checked event, where the returned string data is either "True" or "False"
  • argument2: The returned value for the named element, as a string (see above for details).

The function itself will return the string "OK" if it has successfully added the XAML to the Settings Charm, otherwise it will return a string with the error details. You can find an example of how the XAML should be formatted from the YoYo Games Knowledge Base article HTML and XAML Examples For The Windows 8 Settings Charm.

NOTE: This function is for the Windows 8 Native target module only. For Windows 8 JavaScript support, please see win8_settingscharm_add_html_entry.

Example:

var result = win8_settingscharm_add_xaml_entry("Settings", "xaml2.txt", "#ff20a0", scr_SettingsCallback, false);

The above code will create a new option within the Settings Charm, taken from the given file, and associate it with the script "scr_SettingsCallback".

Back: Windows 8
Next: win8_settingscharm_set_xaml_property


win8_settingscharm_get_xaml_property

Get the current value of Settings Charm property element from a custom XAML file.

Syntax:

win8_settingscharm_get_xaml_property(entryName, elementName, propertyName);

Argument | Description
entryName | The name of the option in the settings charm.
elementName | The name of an element in the xaml.
propertyName | The property name of the element.

Returns: String

Description

With this function you can get the current value (as a string) from a given property that you have added to your XAML fly-out. The entryName is the name of the option in the Settings Charm, as specified by the first argument of the function win8_settingscharm_add_xaml_entry, while the elementName is the name of the element to get the value from as defined in the XAML file. The propertyName must be a string and is defined in the reference for that control following the Microsoft guidelines found here.

Example:

var text = win8_settingscharm_get_xaml_property("Settings", "IntroText", "Text" );
win8_settingscharm_set_xaml_property("Settings", "IntroText", "Text", "MacSweeney Games Is Best");

The above code will get the "Text" value of the XAML property "IntroText" and then change it to something else.

Back: Windows 8
Next: win8_settingscharm_remove_entry

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_settingscharm_remove_entry

Remove an entry from the Settings Charm.

Syntax:

win8_settingscharm_remove_entry(name);

Argument | Description
name | The name of the option to be removed.

Returns: N/A

Description

This function will remove the option with the given name (the same as was used when adding it) from the settings "charm" for your game.

Example:

win8_settingscharm_remove_entry("News");

The above code will remove the option labelled "News" from the settings "charm".

Back: Windows 8
Next: win8_share_image

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_settingscharm_set_xaml_property

Set a Settings Charm property element from a custom XAML file to a new value.

Syntax:

win8_settingscharm_set_xaml_property(entryName, elementName, propertyName, newValue);

Argument | Description
entryName | The name of the option in the settings charm.
elementName | The name of an element in the xaml.
propertyName | The property name of the element.
newValue | The new value for the element.

Returns: Boolean

Description

With this function you can set a given element property in your custom Settings Charm fly-out. The entryName is the name of the option in the Settings Charm, as specified by the first argument of the function win8_settingscharm_add_xaml_entry, while the elementName is the name of the element to set the value of as defined in the XAML file. The propertyName must be a string and is defined in the XAML file, following the Microsoft guidelines found here, whiole the newValue is the value that you wish to give the element.

Example:

var text = win8_settingscharm_get_xaml_property("Settings", "IntroText", "Text" );
win8_settingscharm_set_xaml_property("Settings", "IntroText", "Text", "MacSweeney Games Is Best");

The above code will get the "text" value of the XAML property "IntroText" and then change it to something else.

Back: Windows 8
Next: win8_settingscharm_get_xaml_property


win8_share_file

Share a file through the "Share Charm".

Syntax:

win8_share_file(filename, title, description, immediate);

Argument | Description
filename | The name of the file to share
title | The title of the file (a string)
description | A text description of the file
immediate | This flag can be set to true or false to share immediately or not.

Returns: N/A

Description

With this function you can share a file from your game. The file should be an included file (or one that your game has created) and part of the app "bundle", and you should give it a title and a description. Finally you should indicate whether it should be shared immediately (true) and shown in the slide-out share "charm" or not (false), in which case the user will have to manually call on the share "charm" to see the content.

Example:

if keyboard_check_pressed(ord("S"))
{
win8_share_file(working_directory + "New_Level_Save.txt", "C.T.H. Level", "Catch The Haggis user level.", true);
}

The above code will check for the "S" key being pressed and if it is detected it will take and share a file.

Back: Windows 8
Next: win8_share_url

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_share_image

Share an image through the "Share Charm".

Syntax:

win8_share_image(filename, title, description, immediate);

Argument | Description
filename | The name of the file to share
title | The title of the image (a string)
description | A text description of the image
immediate | This flag can be set to true or false to share immediately or not.

Returns: N/A

Description

With this function you can share an image from your game. The image should be an included file and part of the app "bundle", and you should give it a title and a description. Finally you should indicate whether it should be shared immediately (true) and shown in the slide-out share "charm" or not (false), in which case the user will have to manually call on the share "charm" to see the content.

Example:

if keyboard_check_pressed(ord("S"))
{
win8_share_image(working_directory + "ShareLogo.png", "Catch The Haggis", "I am playing Catch The Haggis!", true);
}

The above code will check for the "S" key being pressed and if it is detected it will share an image that has been bundled with the game.

Back: Windows 8
Next: win8_share_screenshot

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_share_screenshot

Share a screenshot through the "Share Charm".

Syntax:

win8_share_screenshot(title, description, immediate);

Argument | Description
title | The title of the image (a string)
description | A text description of the image
immediate | This flag can be set to true or false to share immediately or not.

Returns: N/A

Description

With this function you can take a screenshot from your game and share it. You should give it a title and a description, then you should indicate whether it should be shared immediately (true) and shown in the slide-out share "charm" or not (false), in which case the user will have to manually call on the share "charm" to see the content.

Example:

if keyboard_check_pressed(ord("S"))
{
win8_share_screenshot("C.T.H._Screen_" + string(scr_num), "Catch The Haggis screenshot " + string(scr_num) + ".", true);
scr_num += 1;
}

The above code will check for the "S" key being pressed and if it is detected it will take and share a screenshot.

Back: Windows 8
Next: win8_share_file

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_share_text

Share a some text through the "Share Charm".

Syntax:

win8_share_text(text, title, description, immediate);

Argument | Description
text | The text to share
title | The title of the file (a string)
description | A text description of the file
immediate | This flag can be set to true or false to share immediately or not.

Returns: N/A

Description

With this function you can share some text. Once you have added the text to be shared, you can also give it a title and a description. Finally you should indicate whether it should be shared immediately (true) and shown in the slide-out share "charm" or not (false), in which case the user will have to manually call on the share "charm" to see the content.

Example:

if keyboard_check_pressed(ord("S"))
{
win8_share_text("You have been invited to the Restaurant At The End Of The Universe", "Invitation", "Your carriage awaits", true);
}

The above code will check for the "S" key being pressed and if it is detected it will share the given text message.

Back: Windows 8
Next: win8_search_enable

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


win8_share_url

Share a URL through the "Share Charm".

Syntax:

win8_share_url(URL, title, description, immediate);

Argument | Description
URL | The URL to share (as a string)
title | The title of the file (a string)
description | A text description of the file
immediate | This flag can be set to true or false to share immediately or not.

Returns: N/A

Description

With this function you can share a URL. The URL should be complete and include "http://" and you can also give it a title and a description. Finally you should indicate whether it should be shared immediately (true) and shown in the slide-out share "charm" or not (false), in which case the user will have to manually call on the share "charm" to see the content.

Example:

if keyboard_check_pressed(ord("S"))
{
win8_share_url("http://www.MacSweeneyGames.com", "MacSweeney Games", "MacSweeny Games Homepage", true);
}

The above code will check for the "S" key being pressed and if it is detected it will share the given URL.

Back: Windows 8
Next: win8_share_text

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Windows 8 Live Tile Templates

win8_livetile_tile_notification

This is a list of the templates that you can use for Live Tile notifications.

The following template strings are for use with the Windows 8 Live Tile functions.

Square Template | Description
tileSquareImage | One square image that fills the entire tile, no text.
tileSquareBlock | One string of large block text over a single, short line of bold, regular text.
tileSquareText01 | One header string in larger text on the first line; three strings of regular text on each of the next three lines (text does not wrap).
tileSquareText02 | One header string in larger text on the first line, over one string of regular text wrapped over a maximum of three lines.
tileSquareText03 | Four strings of regular text on four lines (text does not wrap).
tileSquareText04 | One string of regular text wrapped over a maximum of four lines.
tileSquarePeekImageAndText01 | One square image, no text, and one header string in larger text on the first line, three strings of regular text on each of the next three lines (text does not wrap). First the image is displayed, then the text, then the image again, and this loops as long as the notification is being shown.
tileSquarePeekImageAndText02 | As above, only the with one header string in larger text on the first line, over one string of regular text wrapped over a maximum of three lines.
tileSquarePeekImageAndText03 | As above, only with four strings of regular text on four lines (text does not wrap).
tileSquarePeekImageAndText04 | As above only with one string of regular text wrapped over a maximum of four lines.

Wide Template | Description
tileWideImage | One wide image that fills the entire tile, no text.
tileWideImageCollection | One large square image with four smaller square images to its right, no text.
tileWideImageAndText01 | One wide image over one string of regular text wrapped over a maximum of two lines.
tileWideImageAndText02 | One wide image over two strings of regular text on two lines (text does not wrap).
tileWideBlockAndText01 | Four strings of regular, unwrapped text on the left; large block text over a single, short string of bold, regular text on the right.
tileWideBlockAndText02 | One string of regular text wrapped over a maximum of four lines on the left; large block text over a single, short string of bold, regular text on the right.
tileWidePeekImageCollection01 | One large square image with four smaller square images to its right, no text, and one header string in larger text over one string of regular text wrapped over a maximum of four lines. First the images are displayed, then the text, then the image again, and this loops as long as the notification is being shown.
tileWidePeekImageCollection02 | As above, only with one header string in larger text on the first line and four strings of regular text on the next four lines (text does not wrap).
tileWidePeekImageCollection03 | As above, only with one string of large text wrapped over a maximum of three lines.
tileWidePeekImageCollection04 | As above but with one string of regular text wrapped over a maximum of five lines.
tileWidePeekImageCollection05 | As above, only now the text is accompanied by one small image on the left. The text on the right is one header string of larger text on the first line over one string of regular text wrapped over a maximum of four lines.
tileWidePeekImageCollection06 | As above, only now the text is accompanied by one small image on the left. the text on the right is one string of large text on wrapped over a maximum of three lines.
tileWidePeekImageAndText01 | One wide image and one string of regular text wrapped over a maximum of five lines. First the image is displayed, then the text, then the image again, and this loops as long as the notification is being shown.
tileWidePeekImageAndText02 | One wide image and five strings of regular text wrapped over five lines. First the image is displayed, then the text, then the image again, and this loops as long as the notification is being shown.
tileWidePeekImage01 | One wide image and one header string in larger text over one string of regular text that wraps over a maximum of four lines. First the image is displayed, then the text, then the image again, and this loops as long as the notification is being shown.
tileWidePeekImage02 | As above, only now it has one header string in larger text on the first line, four strings of regular text on the next four lines (text does not wrap).
tileWidePeekImage03 | As above, only with one string of large text wrapped over a maximum of three lines.
tileWidePeekImage04 | As above, only with one string of regular text wrapped over a maximum of five lines.
tileWidePeekImage05 | As above, but with one small image on the left accompanying the text, which is one header string of larger text on the first line over one string of regular text wrapped over a maximum of four lines.
tileWidePeekImage06 | As above, but with one small image on the left accompanying the text, which is one string of large text wrapped over a maximum of three lines.
tileWideSmallImageAndText01 | A single tile with one small imageon the left and on the right, one string of large text wrapped over a maximum of three lines.
tileWideSmallImageAndText01 | As above, but with one header string on the right which has larger text on the first line and four strings of regular text on the next four lines (text does not wrap lines).
tileWideSmallImageAndText03 | As above, but with one string of regular text wrapped over a maximum of five lines.
tileWideSmallImageAndText04 | There is one header string in larger text over one string of regular text wrapped over a maximum of four lines on the left and on the right, one small image with 3:4 dimensions.
tileWideSmallImageAndText05 | A single tile with one small imageon the left and on the right, one string of large text wrapped over a maximum of three lines.
tileWideText01 | One header string in larger text on the first line, four strings of regular text on the next four lines (text does not wrap).
tileWideText02 | One header string in larger text over eight short strings arranged in two columns of four lines each (columns are of equal width).
tileWideText03 | One string of large text wrapped over a maximum of three lines.
tileWideText04 | One string of regular text wrapped over a maximum of five lines.
tileWideText05 | Five strings of regular text on five lines (text does not wrap).
tileWideText06 | Ten short strings of regular text, arranged in two columns of five lines each (columns are of equal width).
tileWideText07 | One header string in larger text over eight short strings of regular text arranged in two columns of four lines each. The column widths are such that the first column acts as a label and the second column as the content. This template is similar to TileWideText10, but the first column is wider.
tileWideText08 | Ten short strings of regular text arranged in two columns of five lines each. The column widths are such that the first column acts as a label and the second column as the content. This template is similar to TileWideText11, but the first column is wider.
tileWideText09 | One header string in larger text over one string of regular text wrapped over a maximum of four lines.
tileWideText10 | One header string in larger text over eight short strings of regular text arranged in two columns of four lines each. The column widths are such that the first column acts as a label and the second column as the content. This template is similar to TileWideText07, but the first column is narrower.
tileWideText11 | Ten short strings of regular text arranged in two columns of five lines each. The column widths are such that the first column acts as a label and the second column as the content. This template is similar to TileWideText08, but the first column is narrower..

Back: Windows 8

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


Windows 8 Phone

Windows 8 Phone (DEPRECATED)

These functions are provided specifically for the Windows 8 Phone platform.

IMPORTANT! The following pages are for the functions specific to Windows Phone 8. Be aware this platform is now deprecated in favour of UWP, so these pages are only intended as a reference resource for legacy projects.

While the Windows 8 Phone OS looks very similar to the standard Windows 8 desktop version, the live tiles and other functions are a bit more limited. At the moment GameMaker: Studio permits you to use special functions to modify the Live Tiles associated with your game, as well as one further function to check your game for Trial Play:

  1. winphone_license_trial_version

The tile functions are split into three groups (for the three different types of tiles that are available) and apart from the functions specific to the tile type, there are also two that are available for all types:

  1. winphone_tile_title
  2. winphone_tile_count

NOTE: As with other mobile target platforms, the Back Button on Windows Phone devices can be accessed using the vk_backspace keyboard check.

Flip Tile

A Flip Tile is one that has a back and a front image and the tile switches (or "flips") between them over time.

The following functions are available to help you control their visual aspects:

  1. winphone_tile_front_image
  2. winphone_tile_front_image_small
  3. winphone_tile_front_image_wide
  4. winphone_tile_back_title
  5. winphone_tile_back_content
  6. winphone_tile_back_content_wide
  7. winphone_tile_back_image
  8. winphone_tile_back_image_wide

Iconic Tile

The Iconic Tile is one that uses an "iconic" image in all formats. This image will occupy the whole tile for a small and medium tile, but will be reduced to a small icon over the chosen background colour for the wide tile (normally with some text associated with the tile two).

The following functions can be used to set these properties:

  1. winphone_tile_background_colour
  2. winphone_tile_icon_image
  3. winphone_tile_small_icon_image
  4. winphone_tile_wide_content

Cyclic Tile

The Cyclic Tile is one that uses a number of wide-tile format images and cycles between them. If the Live Tile is not a wide tile, then only a small image will be shown.

The following functions can be used to set these properties:

  1. winphone_tile_cycle_images
  2. winphone_tile_small_background_image

Back: Windows 8

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_license_trial_version

Return the state of the Trial Play for your Windows Phone game.

Syntax:

winphone_license_trial_version();

Returns: Boolean

Description

This function will return true if your game is currently in Trial Play, or false if it is not. You can use this function to block features or limit game-play while your game is on trial by the user.

Example:

if winphone_license_trial_version()
{
global.Level_Max = 20;
}
else
{
global.Level_max = 100;
}

The above code will check the status of your game and if it is on trial Play it will set the global variable "level_Max" to 20, otherwise it will be set to 100.

Back: Windows 8
Next: winphone_tile_title

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_back_content

Add a text message to the "back" of the games Flip Live Tile.

Syntax:

winphone_tile_back_content(string);

Argument | Description
string | A message to be shown on the tile back.

Returns: N/A

Description

With this function you can assign a message string to the back of the Flip Live Tile associated with your game. This message will only be shown if your tile is classed as being a "flip tile" with a "front" and a "back", in which case this message string will be shown when the tile flips to the "back", as shown in the following image:

Example:

if os_type = os_winphone
{
winphone_tile_title("Catch The Haggis");
winphone_tile_back_title("MacSweeney Games");
winphone_tile_back_content("You have played this game for " + string(time) + " minutes!");
}

The above code will set both the front and the back title for the games Live Tile to the given strings, as well as add a message to be displayed when the tile "flips" to the back.

Back: Windows 8 Phone
Next: winphone_tile_back_content_wide

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_back_content_wide

Add a text message to the "back" of the games wide Flip Live Tile.

Syntax:

winphone_tile_back_content_wide(string);

Argument | Description
string | A message to be shown on the tile back.

Returns: N/A

Description

With this function you can assign a message string to the back of the wide Flip Live Tile associated with your game. This message will only be shown if your tile is classed as being a "flip tile" with a "front" and a "back", in which case this message string will be shown when the tile flips to the "back", as shown in the following image:

Example:

if os_type = os_winphone
{
winphone_tile_title("Catch The Haggis");
winphone_tile_back_title("MacSweeney Games");
winphone_tile_back_content("You have played this game for " + string(time) + " minutes!");
winphone_tile_back_content_wide("You have played this game for " + string(time) + " minutes!");
}

The above code will set both the front and the back title for the games Live Tile to the given strings, as well as add a message to be displayed when the tile "flips" to the back, either as a normal tile or as a wide tile.

Back: Windows 8 Phone
Next: winphone_tile_back_image

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_back_image

Add an image to the games Flip Live Tile "front".

Syntax:

winphone_tile_back_image(img);

Argument | Description
type | The local path to the image to display.

Returns: N/A

Description

This function will take an image and show it on the "back" of the Flip type Live Tile. This image must be an included file and not a sprite or a background, and if it is too small or too big for the tile it will be stretched or cropped to fit.

Example:

var tile;
tile = choose("tile1.png", "tile2.png", "tile3.png");
winphone_tile_back_image(tile);

The above code will set the "back" Live Tile to be any one of three included files.

Back: Windows 8 Phone
Next: winphone_tile_back_image_wide

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_back_image_wide

Add an image to the games wide Flip Live Tile "front".

Syntax:

winphone_tile_back_image_wide(img);

Argument | Description
type | The local path to the image to display.

Returns: N/A

Description

This function will take an image and show it on the "back" of the wide version of the Flip type Live Tile. This image must be an included file and not a sprite or a background, and if it is too small or too big for the tile it will be stretched or cropped to fit.

Example:

var tile;
tile = choose("tile1.png", "tile2.png", "tile3.png");
winphone_tile_back_image_wide(tile);

The above code will set the "back" of the wide Live Tile to be any one of three included files.

Back: Windows 8 Phone
Next: winphone_tile_background_colour

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_back_title

Set the title for the Flip Live Tile back.

Syntax:

winphone_tile_back_title(title);

Argument | Description
title | The title of your game tile (a string).

Returns: N/A

Description

With this function you can assign a title string to the back of the Flip type Live Tile associated with your game. This title will only be shown if your tile is classed as being a "flip tile" with a "front" and a "back", in which case this title string will be shown when the tile flips to the "back".

Example:

if os_type = os_winphone
{
winphone_tile_title("Catch The Haggis");
winphone_tile_back_title("MacSweeney Games");
}

The above code will set both the front and the back title for the games Live Tile to the given strings.

Back: Windows 8 Phone
Next: winphone_tile_back_content

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_background_colour

Set the colour of the games Iconic Live Tile background.

Syntax:

winphone_tile_background_colour(colour);

Argument | Description
colour | the colour to use for the background.

Returns: N/A

Description

This function will change the background colour of the Iconic type Live Tile. The colour can be any one of the colour constants, a hex value or the return value for any of the colour functions.

Example:

winphone_tile_background_colour(make_colour_hsv(random(255), 255, 255));

The above code will set the Iconic Live tile background colour to a random hue.

Back: Windows 8 Phone
Next: winphone_tile_icon_image

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_count

Display a number on the games Live Tile.

Syntax:

winphone_tile_count(num);

Argument | Description
num | The value to display on the tile (real).

Returns: N/A

Description

With this function you can display a number on the Live Tile (this number can be any value, but it will only display values from 0 - 99, with anything larger being shown as "+99"), as illustrated by the image shown below:

Example:

winphone_tile_count(lives);

The above code will display the value of the global variable "lives" on the Live Tile for the game.

Back: Windows 8 Phone
Next: winphone_tile_back_title

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_cycle_images

Add an image to the games Cyclic Live Tile "front".

Syntax:

winphone_tile_cycle_images(fname0, fname1, ... fname8);

Argument | Description
fname0 ... 9 | The local path to the images to display. You can supply up to 9 arguments (one for each image).

Returns: N/A

Description

This function will add the images you supply into the Cyclic Live Tile list, and they will then be shown one after another when your game is in wide Live Tile. Note that you do not have to supply all nine arguments, you can supply four or two for example, as the tile will cycle between the ones you supply. However, if you have defined more tiles in the Global game Settings these will be omitted and only the new ones supplied by this function will be used.

The images supplied must be included files with your game and cannot be either a sprite or a background. If they are too small or too big for the tile they will be stretched or cropped to fit.

Example:

var image1 = choose("Screen_1.png", "Screen_2.png");
var image2 = choose("Screen_3.png", "Screen_4.png");
var image3 = choose("Screen_5.png", "Screen_6.png");
winphone_tile_cycle_images(image1, image2, image3);

The above code will choose three images from the included files and set the cyclic live tile to display them.

Back: Windows 8 Phone
Next: winphone_tile_small_background_image


winphone_tile_front_image

Add an image to the games Flip Live Tile "front".

Syntax:

winphone_tile_front_image(img);

Argument | Description
type | The local path to the image to display.

Returns: N/A

Description

This function will take an image and show it on the "front" of the Flip Live Tile. This image must be an included file and not a sprite or a background, and if it is too small or too big for the tile it will be stretched or cropped to fit.

Example:

var tile;
tile = choose("tile1.png", "tile2.png", "tile3.png");
winphone_tile_front_image(tile);

The above code will set the "front" Live Tile to be any one of three included files.

Back: Windows 8 Phone
Next: winphone_tile_front_image_small

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_front_image_small

Add an image to the games small Flip Live Tile "front".

Syntax:

winphone_tile_front_image_small(img);

Argument | Description
type | The local path to the image to display.

Returns: N/A

Description

This function will take an image and show it on the "front" of the smallest Flip Live Tile. This image must be an included file and not be a sprite or a background, and if it is too small or too big for the tile it will be stretched or cropped to fit.

Example:

var tile;
tile = choose("tile1.png", "tile2.png", "tile3.png");
winphone_tile_front_image_small(tile);

The above code will set the smallest "front" Live Tile to be any one of three included files.

Back: Windows 8 Phone
Next: winphone_tile_front_image_wide

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_front_image_wide

Add an image to the games wide Flip Live Tile "front".

Syntax:

winphone_tile_front_image_wide(img);

Argument | Description
type | The local path to the image to display.

Returns: N/A

Description

This function will take an image and show it on the "front" of the wide Flip Live Tile. This image must be an included file and not be a sprite or a background, and if it is too small or too big for the tile it will be stretched or cropped to fit.

Example:

var tile;
tile = choose("tile1.png", "tile2.png", "tile3.png");
winphone_tile_front_image_wide(tile);

The above code will set the "front" of the wide Live Tile to be any one of three included files.

Back: Windows 8 Phone
Next: winphone_tile_back_title

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_icon_image

Set the games Iconic Live Tile large icon.

Syntax:

winphone_tile_icon_image(fname);

Argument | Description
fname | The local path to the image to display.

Returns: N/A

Description

This function will take an image and make it the "large" icon of the Iconic type Live Tile. This image must be an included file and not a sprite or a background, and if it is too small or too big for the tile it will be stretched or cropped to fit.

Example:

var tile;
tile = choose("tile1.png", "tile2.png", "tile3.png");
winphone_tile_icon_image(tile);

The above code will set the large Iconic Live Tile to be any one of three included files.

Back: Windows 8 Phone
Next: winphone_tile_small_icon_image

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_small_background_image

Add an image to the games small Cyclic Live Tile.

Syntax:

winphone_tile_small_background_image(img);

Argument | Description
type | The local path to the image to display.

Returns: N/A

Description

This function will take an image and show it as the small Cyclic type Live Tile. This image must be an included file and not a sprite or a background, and if it is too small or too big for the tile it will be stretched or cropped to fit.

Example:

var tile;
tile = choose("tile1.png", "tile2.png", "tile3.png");
winphone_tile_small_background_image(tile);

The above code will set the small Cyclic Live Tile to be any one of three included files.

Back: Windows 8 Phone
Next: winphone_license_trial_version

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_small_icon_image

Set the games Iconic Live Tile small icon..

Syntax:

winphone_tile_small_icon_image(fname);

Argument | Description
fname | The local path to the image to display.

Returns: N/A

Description

This function will take an image and make it the "small" icon of the Iconic type Live Tile. This image must be an included file and not a sprite or a background, and if it is too small or too big for the tile it will be stretched or cropped to fit.

Example:

var tile;
tile = choose("tile1.png", "tile2.png", "tile3.png");
winphone_tile_small_icon_image(tile);

The above code will set the small Iconic Live Tile to be any one of three included files.

Back: Windows 8 Phone
Next: winphone_tile_wide_content

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_title

Set the title of your games Live Tile.

Syntax:

winphone_tile_title(title);

Argument | Description
title | The title of your game tile (a string).

Returns: N/A

Description

With this function you can assign a title string to the Live Tile associated with your game, as illustrated by the image shown below:

Example:

if os_type = os_winphone
{
winphone_tile_title("Catch The Haggis");
}

The above code will check the OS running the game, and if it is the Windows 8 Phone OS, it will set the title of the Live Tile of the game to the given string.

Back: Windows 8 Phone
Next: winphone_tile_count

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


winphone_tile_wide_content

Set any one of three content strings for the wide Iconic Live Tile.

Syntax:

winphone_tile_wide_content(string, index);

Argument | Description
string | The text for the content.
index | The content index (1, 2, or 3).

Returns: N/A

Description

This function will add content text to the wide Iconic tile for the game. You can have up to three lines of text, each one defined by the index number supplied when using this function.

Example:

var str;
str[0] = "Player: " + global.Name;
str[1] = "Score:" + score;
str[2] = "Health: " + health;
winphone_tile_wide_content(str[0], 1);
winphone_tile_wide_content(str[1], 2);
winphone_tile_wide_content(str[2], 3);

The above code will set the content strings for the Iconic wide Live Tile.

Back: Windows 8 Phone
Next: winphone_tile_cycle_images

© Copyright YoYo Games Ltd. 2018 All Rights Reserved


App settings flyout

Defaults

Toggle switch

Use toggle switches to let users set Boolean values.

Push button

With a push button, users initiate an immediate action.

Select control

Use the select control to allow users to select one item from a set of text-only items.

Hyperlink

Use a hyperlink when the associated action will take the user out of this flyout.

View privacy statement

Text input box

Use a text input box to allow users to enter text. Set the type of the text input box according to the type of text you’re capturing from the user (e.g. email or password).

Radio button group

Lets users choose one item from a small set of mutually exclusive, related options.

© Copyright YoYo Games Ltd. 2013 All Rights Reserved