Gml Can I Break a Loop and Start It Again
GameMaker Language – Beginner's Guide
Contents:
- Introduction
- Events
- Variables
- Functions
- Weather condition – if Statements
- Conditions and Functions
- Conditions – switch Statements
- The repeat function
- The while Loop
- The practise…while Loop
- The practise…until Loop
- The for Loop
- Arrays
- Conclusion
Introduction
Welcome! This tutorial is aimed at beginners who have little to no experience in GML or programming in general. It will innovate you to the basics of programming and how GML works. After this tutorial, you'll be able to utilize GML to build your ain games effectively!
Bookmark this folio at present (Press CTRL + D) as this guide is quite long and you will need to close it and come up back after. Kudos if you lot tin can read it all in one go!
Click here to read the Russian translation of this guide, past Artem Darkov.
Events
You put code within an event, and when that lawmaking runs depends on the blazon of issue you put it in. There are a lot of events to choose from in GameMaker.
Here'due south a quick introduction to the events we'll be using the about:
Create
Code inside the Create consequence is executed only once: when the instance running the code is kickoff created. Hither yous can initialize most of the stuff related to your example.
Pace
The most of import and the most used consequence – the Pace event runs every stride – if your game/room speed is gear up to 30, a Footstep upshot will run thirty times in a second. This is used for things you want to keep on happening.
Draw
This consequence is used to execute the describe codes. For example, functions similar draw_sprite, which is used to draw a sprite at a location, or draw_rectangle, which is used to describe a rectangle, only work in the Draw upshot. The Draw effect overrides the default describe of the instance, meaning your instance won't be drawn unless you use draw_self().
Alarms
Alarm events run afterward y'all set them. So if I fix Alarm 0 to lx in the Create issue, the code within the Alarm 0 event will run after lx steps.
Collision
While calculation a collision event, you can select an object to create the result. That event will but run when the instance running the code collides with any instance of the object specified while creating the collision result.
Read more about events
Variables
Variables are containers that incorporate some value/data. They have a name. For case, a variable named player_health may contain 100, or a variable named player_name may contain the player's proper noun ("Peter", "Lindsey", etc.). It's up to you what you want to name your variables and what yous want to store inside them.
A variable in GML can store:
- Numerical values – 100, 45.534, -42.2
- Cord values – "Teacher", "Peter"
- Boolean values – truthful or false
Example:
Initialization:
price = twenty;
Here we have initialized a variable named toll which contains 20 every bit a value. If the variable has already been initialized earlier, this serves to change its value to 20.
Side note: It is not required in GML to put a semicolon (;) after each statement. And then experience free to skip it and focus on the chief code.
There are many ways of assigning a value…
price = 4 * 5; price = 40 / 2;
To increase the value…
price += 20;
To decrease the value…
toll -= 20;
To multiply, or to divide…
price *= 2; toll /= ii;
Use:
You tin can likewise use variables in mathematical expressions…
a = 4; b = 5; c = a + b;
Here, c would store nine because of the expression a + b (which means 4 + 5 as a is 4 and b is v).
Different Types of Variables
Local Variables
These variables are the ones initialized with the var keyword. They are discarded when the event they were initialized in ends. They can just exist used inside that effect only, unless initialized again.
var price = 2;
This initializes a local variable chosen price. Suppose the event this code was in were the Step issue; then the variable could only be used within the Step result. If y'all try to use it without initializing it in another outcome, it would return an error as it doesn't exist there.
Instance Variables
These are normal variables which are initialized by assigning a value.
price = 20;
These kinds of variables can be accessed inside all the events of the object/instance it was initialized in afterwards it has been initialized.
Global Variables
These are variables which tin be accessed past all the objects in your game – hence the name "global". There are two ways of creating such variables:
Initializing with the globalvar keyword…
globalvar cost; price = 2;
Once the variable has been initialized with the globalvar keyword, it can be used by any instance nowadays in the room.
or use with global. prefix…
global.price = 2;
This mode y'all don't take to initialize information technology with the globalvar keyword but have to utilise the global. prefix every fourth dimension yous want to use this variable.
Built-In Variables
There are also some congenital-in variables which mean something special in GameMaker. Here are a few examples…
Built-in Instance Variables
These are the built-in variables which are unique to each instance. They can as well be known as properties of an instance. Here are a few important examples…
x: horizontal location of the example within the room (in pixels) y: vertical location of the example inside the room (in pixels) speed: speed of the example (in pixels per stride) direction: the direction the instance moves towards (in degrees), default: 0 hspeed: horizontal speed (in pixels/footstep) vspeed: vertical speed (in pixels/step) image_angle: the rotation of the sprite (in degrees), default: 0 image_xscale: horizontal scaling of the sprite, default: 1 image_yscale: vertical scaling of the sprite, default: 1 image_index: the sub-prototype of the sprite the case is showing image_speed: the speed at which the sprite animates through its sub-images sprite_index: the sprite used by the instance
You can change or use these variables just like ordinary ones.
//change location to 200, 150 x = 200; y = 150; //brand sprite 2x bigger image_xscale = 2; image_yscale = 2; //rotate sprite half-way around image_angle = 180;
Text that comes after // is a comment. It has no effect on lawmaking; it's there so that you tin explain what your lawmaking does or write important things you lot'd like to remember when looking at your code.
You tin can write multi-line comments also – just start them with /* and terminate with */.
Built-in Global Variables
These are the built-in variables which are global in scope and same for each instance.
Here are a few examples…
room_speed: the number of steps run past a room in one second, default: xxx score: the score in your game, can store whatsoever numerical value though health: your role player's health, tin can shop whatsoever numerical value likewise lives: number of lives, can store whatever numerical value as well
Hither is a list of all the built-in variables in GameMaker.
Functions
Functions perform an activity and/or render a value based on the arguments provided in the parentheses that come subsequently the function name. If the role is supposed to just perform an action, it is written like…
office(arg0, arg1, arg2...);
…but if information technology likewise returns something after performing the action and you desire to store it in a variable, you exercise it like…
variable = function(arg0, arg1, arg2...);
A function may or may non require arguments.
Here are a few examples…
instance_create_layer(x, y, layer, object); What it does: Creates an example of object at position ten,y inside layer instance_create_layer(48, 48, "Instances", obj_enemy); What information technology returns: The instance id of the instance created enemy_id = instance_create_layer(48, 48, "Instances", obj_enemy); draw_sprite(sprite, sub-paradigm, x, y); What it does: Draws sprite 's sub-epitome at position x,y draw_sprite(spr_ball, 0, x+5, y+v); Returns goose egg. random(number); Does cipher. What it returns: Returns a random existent number between 0 and number . speed = random(5);
Weather condition – if Statements
Conditions are used to command the execution of some lawmaking. Using atmospheric condition y'all can control whether or not a piece of lawmaking runs based on weather. if statements are the about commonly used conditions. Using if you tin can ensure that a piece of lawmaking runs only when a condition or a gear up of weather is true.
Case
Say you're making a game, and y'all make a shop. Here, the role player has to buy some upgrades. The outset upgrade is a weapon upgrade. Information technology costs 200 coins. So the player can simply buy it if that condition is satisfied – that is, if they take at least 200 coins. For such a example, we can use the if condition:
if (coins>=200){ //buy upgrade }
The > sign opens upwards to the side that is greater, and of course = ways equal. So, past checking if coins>=200, we're checking if the coins are greater than or equal to 200.
So, the thespian can simply purchase the upgrade if they have enough coins. Simply what if they don't? Nosotros demand to notify them that they demand to get more coins. But that should just be specified when the status is not satisfied. For that, nosotros use else.
if (coins>=200){ //buy upgrade } else{ //notify, non enough coins }
The code subsequently else runs but when the preceding if condition has returned false. So if the player has less than 200 coins, they will be notified.
You tin can also put a condition after the else part, so that fifty-fifty later the quondam condition has returned false, it would require another condition for the lawmaking after else to execute.
This way you tin can add together more than else keywords and add different lawmaking for different conditions:
if (condition0){ //code0 } else if (condition1){ //code1 } else if (condition2){ //code2 } else{ //code3 }
If condition0 is true, code0 volition run, and the rest of the if statement will be skipped. But if condition0 is false, it will move on to condition1. If it'southward true, it'll execute code1 and stop. Merely if it'south false too, then it'll move to condition2. If information technology's truthful, code2 will run, only if non, the if statement will finally move on to the last else role and seeing that there'due south no condition, execute code3.
Usage
In the previous example we checked if the coins were greater than or equal to 200. Merely the conditions can be used in many more ways.
Checking an equal value: if (money==400) For this status to be true, money has to be exactly 400. Checking a smaller value: if (money<50) For this condition to be true, money has to smaller than fifty (at nigh 49.99..) Checking if something is not equal: if (proper noun!="Expletive") If the player's name is CURSE, this status volition return false. And so for this condition to piece of work, something should not be equal to a value. Some other example: if (lives!=iii) True only if lives are not iii. Checking a boolean is true: if (paused==true) OR if (paused) True only when a variable is true, hither "paused". You tin skip the "==truthful" role and just type the variable name to check if it's true. Checking a boolean is false: if (paused==false) OR if (!paused) True when the variable specified is imitation. Exclamation mark (!) tin be used every bit a prefix for a condition to flip it. So if the condition is false, it would return true.
Conditions and Functions
Functions can exist used inside conditions besides. They can either be checked for equally booleans (returning true or false) or returning some specific value (number/string).
Hither are a few examples to demonstrate how functions can exist used within conditions.
place_meeting()
The office place_meeting() can exist used to check if there is a collision between the instance running the code and a specified object/instance at a position. For example,
lawmaking inside obj_player: place_meeting(x, y, obj_wall);
This function would return truthful if obj_wall was colliding with obj_player at the latter'south position. So to bank check for collisions and execute some code, you would put this function into a status:
obj_player Step event: if (place_meeting(x, y, obj_wall)){ speed = 0; }
When there'southward a collision detected between obj_wall and obj_player at the histrion's location, information technology sets information technology's speed to 0.
instance_exists()
Information technology returns true if an instance of a specified object is present inside the room.
Step event: if (instance_exists(obj_player)){ score += 1; }
The to a higher place code checks if an instance of obj_player exists in the room, and if information technology does, adds i to the score.
floor()
It floors a number specified inside its parentheses and returns the result. For instance, 4.94 would become four, 1.13 would become i, and so on.
if (floor(image_index)==ii){ image_index = ten; }
image_index stores the index of the sub-epitome the sprite is currently on. Sub-images are in integers, but the variable image_index is not. So before checking what sub-epitome the instance is on, you demand to floor the variable.
Weather – switch Statements
As a beginner, switch statements probably won't be of much use to you, but nonetheless, you should know about them.
In a switch argument, you lot first specify a variable, a part or a combination of those inside a mathematical expression. Then you list all the possible results. The switch statement evaluates the expression specified and moves to the example that matches with the outcome. It executes the lawmaking following the case until a break is found.
Here's an example:
switch(level){ example 1: level_name = "Overworld"; suspension; case 2: level_name = "Clandestine"; break; case 3: level_name = "Water World"; pause; case 4: level_name = "Castle"; break; default: level_name = "Unknown"; }
In this example, level is a variable that contains the level number the actor is currently on. When level is ane, the switch volition move to case 1. Information technology will run the lawmaking, where it sets level_name to "Overworld". Then it encounters a break and stops the code.
If you don't use a suspension before starting some other case, information technology will proceed executing all the cases until a break is found.
Similarly, when level is 2, case 2 will run. Same for case 3 and 4.
Just what if level matches none of these cases? In such a situation, the switch volition motility over to the default function, and run the code after it.
The repeat function
The echo() function can repeat a set of statements a specified number of times and is used in the same way as an if statement. Here's an example:
repeat(5){ coins += 1; }
You know what coins += 1 does: it adds 1 to the variable coins. Merely since we're using repeat(v) before information technology, the statement volition be executed five times, ultimately calculation 5 to the variable coins(1 * 5 = 5).
The echo() part is a kind of loop, because it keeps looping until it meets an end. Continue reading to know more than well-nigh loops.
The while Loop
So to kickoff off – there are different kinds of loops and the while loop is just 1 of them. Since it's the simplest one, I'll be explaining it offset.
Loops are called so because they take the ability to loop. Loops are just like the if statement, as in they have a condition that needs to be fulfilled for the code following the condition to be executed. Here, have a await at an if argument compared to a similarwhile loop:
if (money > 40){ //code } while (money > forty){ //lawmaking }
The if argument checks if money is greater than twoscore, then executes the post-obit code. The while loop too checks the same thing, only the departure is in how loops work.
When the condition specified for a loop becomes true, the lawmaking following it is executed, and when that code block ends, information technology goes back to the status and checks information technology over again. If it's true, so it over again executes the lawmaking. Then dorsum again and if it's true, once more executes the code. Information technology keeps on doing so and looping through the condition and so the code until the condition turns false.
Let's take the case higher up. Say the value of money becomes greater than xl. The while loop volition execute the lawmaking post-obit it, and continue on doing so until it turns fake. So for the condition to plow false, the value of coin needs to become below or equal to forty.
while (money > 40){ //code money -= i; }
Now that'due south right. If we're reducing the value of money by one each loop, at one signal it's bound to go beneath twoscore and stop the loop.
So, it's required that you lot implement a way of eventually making the condition false and brand the loop stop. If yous don't, it'll get an space loop that'll never stop, and will crash your game.
The do…while Loop
This is some other loop and a variant of the while loop. Take a expect at how information technology looks before I can explain it:
do{ //code } while (condition);
No no, don't be dislocated. Information technology's actually simple.
Remember how in the while loop we used to check for a condition before executing the code?
while (status){ //code }
In the do…while loop, the while (condition) part has but moved to the bottom, later the lawmaking cake has ended, and has been replaced by the keyword practise:
while (condition)do{ //lawmaking } while (condition);
This is washed because the do..while loop first executes all the code that is in the code block, and and so checks for the status to see if it's true and if it should loop over again. If it is, it goes back to the superlative and executes the lawmaking block. Then again comes to the condition. This mode it keeps looping until the status turns false, the difference existence that it offset executes the code cake without even checking for a condition.
There should be a semicolon (;) at the end of a practice…while loop because without 1, the ending while (condition) part can get confused for the starting of another while loop.
The do…until Loop
The do…until loop is the aforementioned equally the exercise…while loop, the divergence existence that the condition check in do…until is flipped. So in do…while, the loop would run again if the condition were true, simply in exercise…until, the loop would merely run if the status were false.
Hither's an case:
coins = 5; do{ coins++; }until (coins==10);
It'southward equally simple as saying it: "keep adding one to coins until they are equal to 10". So this would keep on adding 1 to coins and when the condition given becomes truthful, which ways the coins become equal to 10, the loop would pause.
In GameMaker, you tin can only use do…until and not practice…while.
The for Loop
The for loop is just like the while loop, as information technology checks for a condition first then keeps looping the code until the condition turns faux. But it has some more than features. Have a look at its syntax:
for(init; condition; increment){ //code }
In that location, you tin spot the condition in the centre. Merely what'southward all that other stuff?
Information technology's basically for a loop variable. A loop variable in a for loop is a variable that determines how many times the loop will run. More caption coming up.
init is where y'all initialize your loop variable, as in give it a name and a value. Runs only on the showtime loop.
condition is the status that will determine if the loop is run.
increment is where you set the loop variable to exist increased or decreased past a certain value each loop. Runs at the end of the loop.
for(i=0; i<3; i++){ //lawmaking }
Here's a detailed explanation of how this loop will go:
So get-go I'grand initializing the loop variable i at 0 value. Then there's this condition checking if i is smaller than 3. Because information technology is, which ways the condition is true, the code will run. In one case the code cake has completed execution, the increment part will run: meaning that i volition be increase by i (i++).
At present, the code block has completed its run and i has been increased by i, which means information technology's 1 at present (0 + one). The initialization part will be left because it only runs on the beginning loop. So it will move on to the status and bank check if i is smaller than 3. Because 1 is smaller than three, the status will become true and the code volition be executed.
Once again, after executing the code cake, 1 will exist added to i, making it ii. And so information technology'll move on to the condition, and considering two is smaller than 3, the condition volition become truthful and the code will exist executed again. Then i will become iii (ii + 1), and and so the status will become false considering i is not smaller than 3, information technology's equal to it. So the loop will stop.
And so, the loop will run 3 times:
1st loop: i is 0. i<three = true, runs. i++. 2nd loop: i is 1. i<3 = true, runs. i++. tertiary loop: i is ii. i<three = true, runs. i++. fourth loop: i is iii. i<3 = simulated, doesn't run.
If you didn't grasp all of this, reading information technology a second time might assistance.
Hither's another example of a for loop:
for(i=3; i>0; i--){ //lawmaking }
This one starts at 3 and keeps decreasing by ane until it'southward no more than greater than 0. Can you lot summate how many times it will run? Do so and post your answer in the comments!
Arrays
Remember how variables worked? You lot could give them a name and store some value…
coins = 10;
That'southward the amount of coins for 1 role player. Simply what if there are 4 players and you lot have store the corporeality of coins they each accept? How would yous practice it?
coins0 = 10; coins1 = v; coins2 = 12; coins3 = seven;
Like that, right? Storing all those values in different variables? That would work right, but there is another, ameliorate style of doing this: using arrays.
coins[0] = 10; coins[ane] = five; coins[2] = 12; coins[3] = seven;
Arrays are just like variables, as in they have a name and store some value, but dissimilar variables, they tin actually shop more than one variables (elements) under the same proper name.
To assign or access an element inside an array, you put the element id (a number) inside square brackets subsequently the array name. Like this:
array[id] = value; variable = array[id];
So in the previous case, I added iv elements (0, 1, ii, 3) to the array coins. If I want to shop the 2d element (with the value 5) in a variable called player_2, I'll do this:
player_2 = coins[1];
You lot can also utilise a variable in identify of the chemical element id inside the foursquare brackets, because what matters is the value, not the keyword. And so I can likewise do this like:
i = 1; player_2 = coins[i];
This way, you lot can also use arrays inside a loop:
for(i=0; i<3; i++){ money[i] = coins[i]; }
The above lawmaking performs the aforementioned office as the following one:
money[0] = coins[0]; money[ane] = coins[1]; money[2] = coins[two];
Considering the loop will only run three times when the loop variable i is 0, 1 and 2 respectively, the first three elements of the assortment money volition become equal to the offset three elements of the assortment coins.
Decision
That's all for the nuts. To learn more amazing things that you can do in GML, look at all the tutorials I have on this website.
If y'all desire to larn making your own games in GameMaker Studio 2 through a video grade, check out my new course on Udemy.
Got annihilation to ask, or any suggestions to give? Feel gratis to annotate beneath. I'll respond to your comment as soon every bit I tin can!
For more than help, join our Discord server here (no sign-up required). Nosotros tin assist you with annihilation and teach you GML if you couldn't grasp something.
Come across you, and happy dev'ing!
Source: https://gdpalace.wordpress.com/learn-gml/