As a consequence, though, it is integral to master fundamental coding principles with the system before jumping into bigger game projects. It’s also just as important to learn how to apply these principles to simple game projects to battle-test your knowledge.
In this tutorial, we’re going to show you how to create auto-stacking blocks of boxes with a simple for loop to get you going. You’re also going to learn how to add physics to the Actors in the scene, as well as alter other core properties to familiarize yourself with.
Let’s get started!
You can download a copy of the source code files for the project done in this tutorial here.
Note: This tutorial was made with Unreal Engine version 5.0, so if you have a higher version you might see some elements as deprecated although they still work. You’ll also need to set up the GameModeOverride to LoopsGameMode in the World Settings and select the Box as the Class in the SpawnActor Box node for the scene to run. Don’t forget to compile the project after you apply the changes!
First of all, let’s go to the Content folder and create a new Loops folder there:
Then, we’ll create a new Basic level. Let’s name it LoopsLevel and save it in the Content > Loops folder:
In this Loops mini-project, we want to create new Actor objects using loops, and not by dragging them by hand into the level. For that, we’ll need to create a couple of new blueprints first:
We’ll save those blueprints in the Content > Loops folder as well:
Now, let’s open the Box blueprint asset. First thing, we’ll add a new Cube component to our Box blueprint:
Then, in the Details panel, let’s set the Material of that Cube to M_CobbleStone_Smooth material for it to look a bit more interesting:
After that, in the Cube’s Physics component, we’ll enable the Simulate Physics property, so our cube would have physics working on it:
Then, you can Compile and Save the Box blueprint.
Now, let’s open the LoopsGameMode blueprint and go to the Event Graph. We’ll connect the BeginPlay event node to a new ForLoop node. Here’s what the ForLoop node does:
For the beginning, let’s run our loop ten times and print the index of the current iteration:
Then, we will return to the LoopsLevel level. In the World Settings panel, we need to set the GameMode Override property to reference the LoopsGameMode for our changes to the LoopsGameMode to take place in the LoopsLevel level:
If you start the game now, you should see the numbers going from 0 to 10 in the top-left corner of the screen:
That happens because our ForLoop node runs the Loop Body control flow for each value of the Index property from 0 to 10 inclusively:
If we’ll set the Last Index property to 1000, we’ll see numbers running from 0 to 1000 at the game start:
Using the loops allows us to save time and not copy-paste our code to be executed as many times as we want.
Next, let us make a hundred cubes spawn on top of each other.
First, we will delete the PrintString node from the LoopsGameMode blueprint’s EventGraph. You should have the ForLoop connected to the BeginPlay event node left:
Then, we’ll connect the ForLoop node’s Loop Body control flow pin to a new SpawnActorFromClass node. This way, we’ll spawn objects in our loop:
Next, in the SpawnActor node, we’ll set the Class property to Box, so it would spawn the Box blueprint we created earlier:
Also, we’ll change the ForLoop’s Last Index property from 1000 to 10, as we might want to start with a lesser amount of cubes:
Finally, we need to connect the SpawnActor’s Spawn Transform input pin to a new MakeTransform node, so our cubes would have information on where they should spawn:
If you start the game now, you’ll see cubes “exploding” in all directions. That happens because we spawn them in the same Location at the same time and their colliders push them away from each other:
If you set the ForLoop’s LastIndex to 100, you’ll have a hundred cubes flying around:
But how can we make the cubes spawn on top of each other? All we have to do is to iterate their Spawn Location like this:
This way, we multiply the (0, 0, 120) Vector by the current Index and the cubes will be spawned every 120 vertical units. The first cube will be spawned at 0 height, the second at 120, the third at 240, and so forth:
If you spawn a hundred cubes now, they will be aligned in a straight vertical line, forming a tower of sorts:
Though, that tower will crumble a second later, as soon as physics catches up with it:
We can also spawn our cubes at random rotations. All we have to do for it is to connect the MakeTransform node’s Rotation input pin to a new RandomRotator node. That node will generate a random Rotation for every cube we’re spawning:
If you start the game now, the cubes will start falling straight away, as each of them has a different rotation and they can’t stack on top of each other:
We can pass the control flow once the loop ends using the Completed pin of the ForLoop node. Let’s print a message when all cubes are spawned:
Now you’ll have the “All boxes have been spawned!” message shown once all the cubes have been spawned:
Before we finish up the tutorial, let’s have you solve a challenge! Your challenge is to create a tower of cubes that looks like a pyramid. Going from top to bottom, each cube should have a bigger scale than the previous one as seen below:
We suggest you use the Subtract and MakeVector nodes in that challenge. You should also remove the RandomRotator node from the LoopsGameMode Event Graph, as you don’t want those cubes to have random rotations in a pyramid:
Then, you should also iterate the For Loop from 0 to 10. This way your pyramid would be small and stable enough:
And that’s all the hints we have for you! Now you can go and try to solve the challenge.
Once you’ve made your best at this challenge, you can check yourself with our implementation. We’ll make our cube tower look like a pyramid by scaling the cubes on the X and Y axes.
First, as we want the cube at the bottom to be the biggest, we will “flip” our Index using the Subtract node:
This way, for the 0 Index, we’ll have 10, for the 1 Index, we’ll have 9, and so forth:
Then, we’ll create the scaling Vector from that flipped Index:
This way, for the 0 Index, we’ll have the (10, 10, 1) scale, for the 1 Index, we’ll have the (9, 9, 1) scale, and so on:
Finally, you should connect the Return Value output pin of the MakeVector node to the Scale input pin of the MakeTransform node. This way, the scale Vector we created will be applied to the cubes:
As the result, you should get a nice cube pyramid:
And if you look closely at the bottom levels of that pyramid, you’ll see that each level is just a stretched cube:
Well done on completing this tutorial!
See how easy it was to spawn whatever number of objects we want in the level scene with Unreal Engine? With this tutorial, not only did you get acquainted with the engine, but you also already coded with the Blueprints Visual Scripting System to create a pyramid of boxes! Getting confident about the simple steps within the engine will surely make your progress quicker and easier.
Moving forward, you can start tackling bigger and more complex projects, thus expanding the existing knowledge you just acquired. You can move on to adding in new features to your future scenes or dig deeper into the many features of the engine you’re interested in for your games. In any case, the foundations you’ve gathered here will provide you with a great starting point in your game-developing journey with Unreal Engine!
We wish you the best of luck in your learning path!
Want to learn more about Unreal Engine game logic? Try our complete Unreal Engine Mini-Projects course.
]]>
With the release of Godot 4, more developers than ever before are flocking to learn this free and open-source engine. However, many come in not knowing what programming language they need to use. While C# is an option (for those familiar with Unity), GDScript is by far the go-to when it comes to scripting in Godot.
What is GDScript, though, and how does it work? In this article, we’re going to cover the fundamentals of GDScript so you can start tackling your Godot game projects with finesse.
If you’re ready, let’s get started!
Welcome to the world of GDScript! In this section, you’ll learn what GDScript is, why you should use it, and how to set up your development environment so you can start writing code right away.
GDScript is a scripting language that was specifically designed for the game engine Godot. It’s a high-level language, which means it’s easy to read and write compared to lower-level languages like C++. And best of all, it’s designed with game development in mind, so it has features that make game development faster and easier.
Here are a few reasons why GDScript is a great choice for game development:
To start using GDScript, you’ll need to download and install the Godot game engine. You can download it for free from the Godot website. Once you have Godot installed, you’re ready to start writing GDScript code!
In the next section, we’ll dive into the basics of GDScript and start writing some code. Let’s get started!
In this section, you’ll learn how to store and manipulate data in GDScript. You’ll learn about variables and different data types, and how to declare and initialize them.
Variables are containers that store values in your code. Think of them like little containers that hold data that you can use and manipulate in your code. For example, you can store a player’s name in a variable so that you can use it throughout your game.
To use a variable, you first have to declare it. You do this by giving it a name and specifying what type of data it will store. Here’s an example of declaring a variable in GDScript:
var player_name: String
In this example, we declared a variable named “player_name” that will store a string value. To initialize a variable, you give it a value when you declare it like this:
var player_name: String = "John Doe"
In GDScript, there are several data types that you can use to store different types of data. Here are the most common data types in GDScript:
var score: int = 10
var price: float = 19.99
var player_name: String = "John Doe"
var game_over: bool = false
var players: Array = [ "John Doe", "Jane Doe", "Jim Doe" ]
var player_scores: Dictionary = { "John Doe": 10, "Jane Doe": 20, "Jim Doe": 30 }
In the next section, we’ll learn about operators and expressions, which are used to manipulate data in your code.
In this section, you’ll learn how to perform operations and manipulate data using operators and expressions in GDScript. We’ll cover different types of operators and how to use them in your code.
Arithmetic operators are used to perform basic arithmetic operations like addition, subtraction, multiplication, division, and more. Here are the most common arithmetic operators in GDScript:
var result = 2 + 2 # result will be 4
var result = 5 - 2 # result will be 3
var result = 2 * 2 # result will be 4
var result = 4 / 2 # result will be 2
var result = 7 % 3 # result will be 1
Assignment operators are used to assign values to variables. Here are the most common assignment operators in GDScript:
var score = 10
var score = 10 score += 5 # score will now be 15
var score = 10 score -= 5 # score will now be 5
var score = 10 score *= 2 # score will now be 20
var score = 10 score /= 2 # score will now be 5
Comparison operators are used to compare two values and return a boolean value based on the comparison result. Here are the most common comparison operators in GDScript:
var result = 2 == 2 # result will be true
var result = 2 != 2 # result will be false
var result = 2 < 3 # result will be true
var result = 2 > 3 # result will be false
var result = 2 <= 2 # result will be true
var result = 2 >= 3 # result will be false
Logical operators are used to perform operations on boolean values and return a boolean result. Here are the most common logical operators in GDScript:
var result = true and true # result will be true
var result = false or true # result will be true
var result = not false # result will be true
Control flow statements allow you to control the flow of execution of your code based on certain conditions. Here are the most common control flow statements in GDScript.
The if statement allows you to execute a block of code only if a certain condition is met. Here’s an example:
if 2 > 1: print("2 is greater than 1") # Output: 2 is greater than 1
The if-else statement allows you to execute a block of code if a certain condition is met, and another block of code if the condition is not met. Here’s an example:
if 2 < 1: print("2 is less than 1") else: print("2 is not less than 1") # Output: 2 is not less than 1
The for loop allows you to execute a block of code repeatedly for a specific number of times. Here’s an example:
for i in range(3): print(i) # Output: # 0 # 1 # 2
The while loop allows you to execute a block of code repeatedly as long as a certain condition is met. Here’s an example:
i = 0 while i < 3: print(i) i += 1 # Output: # 0 # 1 # 2
Functions allow you to group a set of related code together and reuse it whenever you need it. Functions make your code more organized and readable. Here’s how to define and use functions in GDScript.
You can define a function using the “func” keyword, followed by the function name, a list of parameters in parenthesis, and a block of code inside curly braces. Here’s an example:
func greet(name): print("Hello, " + name) greet("John") # Output: Hello, John
The return statement allows you to return a value from a function. Here’s an example:
func square(x): return x * x result = square(3) print(result) # Output: 9
You can specify default values for parameters in case they are not provided when the function is called. Here’s an example:
func greet(name, greeting="Hello"): print(greeting + ", " + name) greet("John") # Output: Hello, John greet("Jane", "Hi") # Output: Hi, Jane
You can accept a variable number of parameters by using the “*args” syntax. Here’s an example:
func sum(*numbers): result = 0 for number in numbers: result += number return result print(sum(1, 2, 3, 4)) # Output: 10
Classes and objects are fundamental concepts in object-oriented programming (OOP). They allow you to create complex data structures and provide a way to encapsulate data and behavior. Here’s how to use classes and objects in GDScript.
You can define a class using the “class” keyword, followed by the class name and a block of code inside curly braces. Here’s an example:
class Person: var name func greet(): print("Hello, my name is " + name) person = Person.new() person.name = "John" person.greet() # Output: Hello, my name is John
The constructor is a special method that is automatically called when an object is created from a class. You can use the constructor to initialize the object’s properties. Here’s an example:
class Person: var name func _init(name): self.name = name func greet(): print("Hello, my name is " + name) person = Person.new("John") person.greet() # Output: Hello, my name is John
Inheritance allows you to create a new class that is a derived version of an existing class. The derived class inherits all the properties and methods of the base class. Here’s an example:
class Employee(Person): var company func work(): print(name + " is working at " + company) employee = Employee.new("Jane") employee.name = "Jane" employee.company = "Acme Inc." employee.greet() employee.work() # Output: # Hello, my name is Jane # Jane is working at Acme Inc.
Polymorphism allows you to use an object of a derived class anywhere an object of the base class can be used, because the derived class is considered a subclass of the base class. Here’s an example:
func introduce(person): person.greet() introduce(person) introduce(employee) # Output: # Hello, my name is John # Hello, my name is Jane
Error handling is an important aspect of programming. It allows you to gracefully handle unexpected situations and prevent your program from crashing. Here’s how to handle errors in GDScript.
The try-except block allows you to wrap a block of code that might raise an exception, and handle the exception if it does. Here’s an example:
try: # code that might raise an exception print(1 / 0) except DivisionByZero: # code to handle the exception print("Cannot divide by zero.") # Output: Cannot divide by zero.
You can raise an exception explicitly using the “raise” keyword, followed by an exception object. This allows you to signal that something unexpected has happened and stop the execution of the current function. Here’s an example:
func divide(a, b): if b == 0: raise ValueError("Cannot divide by zero.") return a / b try: result = divide(10, 0) print(result) except ValueError as error: print(error) # Output: Cannot divide by zero.
You can create your own custom exception classes to signal specific error conditions. Here’s an example:
class DivisionByZeroError(Exception): pass func divide(a, b): if b == 0: raise DivisionByZeroError("Cannot divide by zero.") return a / b try: result = divide(10, 0) print(result) except DivisionByZeroError as error: print(error) # Output: Cannot divide by zero.
In this section, you’ll learn how to read from and write to files in GDScript. This is useful for storing data that you want to persist across multiple runs of your program.
You can write to files using the “File” class in GDScript. Here’s an example that writes a message to a file:
var file = File.new() file.open("message.txt", File.WRITE) file.store_string("Hello, world!") file.close()
In this example, we create a new “File” object, open a file named “message.txt” for writing, store the string “Hello, world!” in the file, and then close the file. If the file doesn’t exist, it will be created. If it does exist, its contents will be overwritten.
You can read from files using the “File” class in GDScript. Here’s an example that reads a message from a file:
var file = File.new() file.open("message.txt", File.READ) var message = file.get_as_text() file.close() print(message) # Output: Hello, world!
In this example, we create a new “File” object, open a file named “message.txt” for reading, retrieve the contents of the file as a string, and then close the file. We then print the contents of the file to the console.
When working with files, it’s important to handle errors that might occur, such as trying to open a file that doesn’t exist or trying to read from a file that hasn’t been opened for reading. Here’s an example that demonstrates error handling:
var file = File.new() try: file.open("nonexistent.txt", File.READ) except Error: print("Cannot open file.") finally: file.close() # Output: Cannot open file.
In this example, we create a new “File” object and attempt to open a file named “nonexistent.txt” for reading. If the file doesn’t exist, an “Error” exception will be raised and caught by the “except” block. We print an error message and then close the file in the “finally” block, which will be executed regardless of whether an exception was raised or not.
Congratulations, you’ve now learned the basics of GDScript! You can use this knowledge to create your own games and applications in Godot Engine.
However, there is more to learn than just GDScript. Godot offers a ton of fantastic features and tools – from simple tilemap painters to performant rendering options. Plus, these coding principles – while important – aren’t of any use unless you learn how to apply them practically to game projects.
To end this article, we’ve included a bunch of helpful resources below to help you get started on the next steps in your Godot journey. We hope this helps, and we’re looking forward to seeing what you do with Godot 4!
]]>
Regardless of where your skill levels lie, puzzle games are a great game genre to explore – not only are they a staple of games in general, but come with some unique coding challenges! In this article, we’re going to strive to showcase some of the best puzzle game tutorials available using famous game engines like Unity, Unreal Engine, and Godot.
Let’s dive into some tutorials on how to implement these puzzle games!
Right off the bat, you’ll learn how to make a minesweeper using Unity with a very detailed approach. Unity is a real-time development platform for game creation, being also used for interactive simulations, animation, and even films.
In this tutorial by Zigurous, he walks you through the creation of the game board and cells using sprites, how to keep track of the state of the game and winning condition, besides all the logic needed for flagging and revealing the cells (with the number of neighboring mines or blank) plus displaying the bombs for those cells corresponding to the mines of the game. And just like that, you’ll have implemented one of the most classic games yourself!
Topics Covered:
Duration: 1.5 hours of video training
Access now: How to Make Minesweeper in Unity
Based on the Breakout game, this tutorial by Imphenzia brings you a Unity complete implementation of a brick breaker game. Your goal in a brick breaker game is to destroy all the bricks on the screen by hitting them with a ball you bounce back and forth with a paddle.
In this detailed walkthrough especially thought out for beginners, the instructor describes the whole game creation process, explaining what variables and prefabs are, how to create the game objects and apply physics to them, how to go over a state machine for the game, and also how to design the menu screens aiming to make the transitions between states in the game as smooth and sensible as possible for the player.
Topics Covered:
Duration: 2 hours of video training
Access now: Make a Brick Breaker Game in Unity
This tutorial series by CodePlanStudio teaches you how to implement a block puzzle for mobile devices with Unity in a thorough step-by-step way. To earn points in a block puzzle game you need to clear lines both horizontally and vertically by filling them with shapes. The instructor shows you how to set up the project, import the needed assets, design the start screen, create the game screen with the shapes being randomly generated for the player to select and drop onto the grid, as well as line completion plus winning condition implementation.
Topics Covered:
Duration: 8.5 hours of video training
Access now: Block Puzzle Mobile Game – Unity Tutorial
Here’s another tutorial from Zigurous, where he shows you how to make a Tetris game using Unity. Tetris is a tile-matching puzzle game, where the player’s objective is to prevent the blocks from stacking up to the top of the screen by clearing lines for as long as possible. The completed lines will then disappear, giving room for the player to proceed with moving and placing the blocks around.
In this video, the presenter shows you all the setting up of the sprites and scenes, as well as the spawning of the blocks, and how to move them around and rotate them. As an extra feature, he implements what’s called ghost pieces which indicate where the blocks are going to land before they actually hit that spot, thus helping the player visualize the best place to lay each block down.
Topics Covered:
Duration: 2 hours of video training
Access now: How to Make Tetris in Unity
In this short tutorial series from Tarodev, you’ll implement a nice-looking 2048 game with Unity. 2048 is a sliding tile puzzle game where you combine tiles with the same number together to sum them up and try reaching number 2048. You can keep playing the game until there are no more blank tiles in the grid, therefore creating even larger numbers. The instructor shows in this 2-videos tutorial how to set up the grid, how to create the tiles, code the logic for shifting and merging the tiles, and also check if the player’s won after each move.
Topics Covered:
Duration: 1 hour of video training
Access now: Create 2048 in Unity
In this tutorial series, BenBonk presents to us how to make a sliding puzzle game in Unity. The game consists of finding your way to the black star while avoiding the red spikes. Over the 3 parts of this series, you’ll see how to set up the project, create the player, obstacles, and goal sprites, plus all the scripting for the player movement and collision with the walls or obstacles. Moreover, the instructor goes over adding an animation for when the player touches the spikes for a more shocking effect, then the game resets. He ends the tutorial by polishing the game up and testing it with you.
Topics Covered:
Duration: 1 hour of video training
Access now: Sliding Puzzle Game in Unity
This Unity tutorial by Zenva Academy walks you through the creation of a puzzle platformer game, where the player has to unlock the colored doors by taking the specified keys that are dispersed around the level scenes, steering clear of the spikes, blades, and acid pits all the while.
The instructor guides you through the creation of the levels, sprites, and collision logic necessary for the implementation of a more puzzle-oriented platformer game full of obstacles. You’re also going to learn how to save your current progress and how to load and move between the scenes of the level you’re in, not to mention that you’ll acquire a lot of game designing skills from this course!
Topics Covered:
Duration: 2 hours of video training
Access now: Develop a Puzzle Platformer Game – Unity
In this tutorial series, Mister Taft Creates implements a game like Candy Crush in Unity. He’s also got versions of it for two other game engines (Godot and Game Maker Studio 2), in case you want to test it out in a different environment. Candy Crush is a match-three puzzle game where you need to clear as many rows and/or columns as possible in but a few moves.
The instructor covers a lot of features in this comprehensive series, ranging from implementing an opening screen to having wrapped candies and icing tiles, diverse level structures and goals, level selection, a pause screen, a star classification system for each level, and much more!
Topics Covered:
Duration: 20.5 hours of video training
Access now: Make a Game like Candy Crush using Unity and C#
This brief tutorial series by Kee Gamedev shows you how to make a 15 puzzle game in Unity. The 15 puzzle is a sliding puzzle game having 14 numbered tiles in a 4×4 square where the goal is to arrange a shuffled initial set of the tiles in ascending order, by sliding the tiles around using the only vacant space available on the grid. The instructor goes over all the necessary setup and logic through the 2 videos of this series.
Topics Covered:
Duration: 30 minutes of video training
Access now: Unity 15 Puzzle Tutorial
With this tutorial, Zigurous guides you through the making of the 2D arcade game Snake in Unity. In this game, the player controls a snake which is basically a line on the screen that grows in length as it eats fruits and its own body is a primary obstacle.
The instructor builds the game scene, makes the snake a rigid body, adds the walls as colliders, implements the logic for eating the food, and he concludes the tutorial by automatically resetting the game each time the player touches either one of the walls or the own body of the snake as that means game over.
Topics Covered:
Duration: 45 minutes of video training
Access now: How to Make Snake in Unity
This tutorial series from CodePlanStudio teaches you how to implement Sudoku in Unity. Sudoku’s objective is to fill the 9×9 grid with digits from 1 to 9 in a way that there are no repeated numbers in each column, row, and each 3×3 subgrid as well.
In this series, you’ll be guided through the complete implementation of a Sudoku game, from creating and populating the grid to attributing numbers and notes to each cell. Further, he goes over adding the known features to the game, such as timer, pause menu, and difficulty level selection, plus win and game over screens as well as how to place ads in your game and release it on Google Play Store.
Topics Covered:
Duration: 9 hours of video training
Access now: Sudoku Unity Tutorial
In this tutorial series, Ryan Laley creates a jigsaw puzzle game with Unreal Engine 4. Over the 8 videos of the series, Ryan shows you how to separate each piece from the material pattern he starts with in order to control every individual piece by itself, then how to generate the logic behind the game and set the puzzle screen.
On the left-hand side, he puts all the pieces of the jigsaw in a scrambled order, while on the right the player will be able to place the squares in a grid until they complete the game. Additionally, he tests the game with 3 different images to demonstrate how to switch between the puzzles and restart the game.
Topics Covered:
Duration: 1.5 hours of video training
Access now: Jigsaw Puzzle – Unreal Engine 4 Tutorial
Here’s a tutorial from Zenva Academy featuring the process of making a puzzle game in Unreal Engine. In this course, the instructor will show you how to design a turn-based game where the player can collect followers while having to avoid obstacles to reach the end goal. As whenever the player moves all other objects move as well, you have to figure out where to go to steer clear of the red blade obstacle as you go around the room assembling followers.
By implementing this project, you’ll learn about blueprint parenting so to facilitate implementation when moving the player and the other elements of the game. You’ll also go through displaying texts to the player, besides adding the options of restarting and quitting the game.
Topics Covered:
Duration: 2 hours of video training
Access now: Make a Puzzle Game in Unreal Engine
This tutorial series from Emilio teaches you how to make a 2D grid-based game with Godot, a versatile open-source 2D and 3D game engine. The purpose of this game is to drag the blue boxes onto the red spaces.
You’ll learn how to set up the sprites and camera along with how to make the player, walls, and boxes nodes aside from setting up collisions between them. Emilio explains in detail his choices on the design of the game and continuously tests his progress with you throughout the videos. In the second video of the series, the instructor shows you how to add an animation for the player movement to be smoother and improves upon the UI displays to have a more polished version of the game.
Topics Covered:
Duration: 48 minutes of video training
Access now: Make Your First 2D Grid-based Game from Scratch in Godot
To close this article, go check Akshay Goel‘s journey in making his version of Baba is You with Unity within 48 hours as an extra motivation to implement a game you like in your own way. Baba Is You is a game where you can change the rules by which you play, as they are blocks you can interact with. By manipulating the rules, you can alter how the game works and thus reach the flag or whatever object you set as goal.
In this video, you’ll see Akshay creating his own assets and sprites, going through the logic of the grid and collision setting, plus the editing of the game levels. You will also accompany him while he’s compiling the rules for the game and making them affect the game world!
Duration: 12 minutes
Access now: I Made Baba Is You in Unity
And there you have some of the best puzzle game tutorials available. Whether you’re a beginner or an experienced developer, puzzle games are a fantastic genre, and one that requires some interesting coding techniques to achieve. These tutorials should help you take those first steps, and let you discover new ways to make your players think.
However, there are an ludicrous amounts of the kinds of puzzles you can have in your games – so by no means is this list exhaustive. Don’t forget to continue to explore further learning resources – and good luck with your future games!
]]>
As well as being able to play games, though, you can also create your own with Roblox’s versatile game engine known as Roblox Studio. Roblox game making is not only fun for all ages, but allows you to easily create pretty much anything that comes to mind – and multiplayer support is built-in already. With its vibrant community and many opportunities, jumping into Roblox game making has never been easier.
Roblox Studio offers a ton of features to help you in the Roblox game making process including:
Well, if you want to create a multiplayer game to play with friends and don’t want to tinker around with networking code and servers – then Roblox Studio is for you. It’s also a great introduction into game development as it strips away all the daunting complexity of other engines.
If you already have experience in other game engines such as Unity, Godot, or Unreal – then Roblox should have a fairly easy onboarding process as well. The structure of the engine is similar to those mentioned, and learning Lua should be easy if you already have experience in C#, C++, GDScript, etc.
Another benefit of Roblox is that the whole experience of creating and playing games is self-contained. You don’t need to host servers, manage distribution platforms, etc. You hit the publish button and your game is out there for potentially millions of people to play. Roblox also facilitates monetization, so if your game becomes popular you could earn some money. So if you are just starting out with game development, or just want less complicated multiplayer development – then definitely give Roblox Studio a go!
There are millions of different games for you to play on Roblox. Here’s a few of the most popular ones.
Here’s the trailer for Arsenal. A multiplayer FPS game in Roblox.
Alright, so you want to make Roblox games – how do you begin? Well, let’s start by downloading the game engine here. Click on the Start Creating button and you can download the software.
Once you’ve logged into Roblox Studio, you should have the program open. Go to the New page and double-click the Baseplate template.
The engine should then open up.
The only thing we have in our game right now is a baseplate (floor) and a spawn location (this is where the players spawn). To move things around, you can click on them to select (you should see a blue outline). Then you can hold down the left mouse button and drag around to move the part.
Now as you create your games, you’ll want to test them out. At the top of the window, you’ll see a row of different tabs. Click on the TEST tab and click on the Play button.
You’re now playing the game! But there’s not much to do here. When you want to stop playing the game and get back to creating, click on the Stop button.
Ok, so you’ve got the game engine open and you know how to play the game. But how about adding in some content? An obstacle course? Combat? Below is a list of tutorials to get you started!
Lua is the programming language we use to script our Roblox games. These tutorials will help you out if you’re totally new to coding.
]]>
If you’ve never coded before, finding the right place to start can be difficult. However, no matter the age, a good first tool/language to explore is Scratch.
Scratch is a visual coding language that allows for the creation of digital stories, games, and animations by anyone who’s interested – including kids. Scratch is also the world’s largest coding community for children and is available for free in more than 70 different languages.
In this tutorial, you’ll learn the basics of coding through the implementation of a mini-project that animates the movement of a cat sprite in Scratch.
If you’re ready to dig in, let’s get started!
The code for our final cat animation can be downloaded here: Cat Animation in Scratch. Although we will guide you along every step of the way, it’s good to also have the complete code so that you can compare it to your version at any time!
We also recommend you check out our Jr Coder Mini-Degree (for learners) or Zenva Schools (for teachers) to explore more topics pertaining to coding with Scratch.
To start this tutorial off, we’ll first explore how to create Scratch projects and explore the interface!
First off, head over to the Scratch homepage then click on ‘Create‘:
This will initiate a new project as seen below:
At the top-right corner, we have the game stage where we can see our animation running:
We can click on the green flag icon above the game stage to start our animation and on the red button to terminate it. Note that as we don’t have any code to run just yet, it only shows its default cat sprite for the moment. By clicking on the rightmost icon above the game stage, you can also put it in fullscreen mode:
To alter the cat’s position inside the game stage area, just drag it around as you wish. You’ll see that its x and y coordinates in the sprite properties panel vary according to its current location:
Here in the properties, we can also rename the sprite to ‘Cat’ and change its size and direction too. To hide or display your sprite, click on the eye icons next to ‘Show’.
At the bottom of the right-hand side of the screen, the sprite area shows us all the sprites we have in our project (only the cat, in our case). To add more sprites, click on the plus button:
From there, you’ll have a huge variety of options to choose from. When you add a new sprite to the project, it will appear next to the previous ones you already had:
To delete a sprite, just click on the trash bin icon that’s on top of its thumbnail:
Next to the sprites, there’s the backdrop area, where you can select a different background for your animation:
Changing our default white background to ‘Room 2‘ (under the ‘Indoors‘ filter), we’d have:
On the left side of our screen, on the other hand, we have all possible blocks of code that we’ll be using in our code. Each block contains a single instruction for the computer to execute and is assigned to one of the various categories shown below:
And finally, to the very center of the screen is the workspace, where we’ll be placing all our code blocks:
Now that we’ve grasped the Scratch tool, it’s time to move on to the main part of making a Scratch project: block-based coding.
To start our project, let’s delete the cat sprite and add a chick character (or feel free to add the sprite of your choice):
In Scratch, we build our program using blocks that we can select from the block palette on the left side of the screen. Let’s begin by clicking and dragging the first block from the Motion category (the one that says “move 10 steps“) to the workspace:
Now, every time you click on this block the chick sprite moves 10 steps in the game stage. You can check its new position by the updates on its x coordinate in the sprite properties panel.
Note that you can also change the number of steps the chick will move each time by entering a new number directly in the block itself:
Although we already have a line of code, when we click on the green flag to start the program nothing happens. This is so because we need to add a starting event in order for our character to move when the green flag is clicked. To do it, go to the blocks under the Events category:
Then, drag the “when green flag clicked” block to the workspace and place it on top of the move block that is already there:
With this, whenever we click on the green flag our character moves 10 steps to its right.
On the blocks palette, go to Looks and drag the “say Hello! for 2 seconds” block to the workspace, connecting it under the move block as follows:
Note that the blocks fit together perfectly. We can change both text and duration if we want:
Clicking on the green flag, we see it is working correctly:
Go on and add the “think Hmm… for 2 seconds” block to our code as well:
It’s important to notice how all these commands are always executed in order, from top to bottom:
First, we are moving the sprite 10 steps, then we make it say ‘Hi’, and at last we make it think ‘Hmm’.
If we were to place the think block before the say one, we’d see that the character would think ‘Hmm’ first and only then would say ‘Hi’:
Remember that if you want to stop the program at any time, you need only press the red icon next to the green flag.
Let’s add a sound to our program. Bring the “play sound until done” block from the Sound category to the workspace:
The suggested sound ‘Chirp’ is matching the sprite we’ve chosen, so it may differ for you.
At last, let’s move the chick again by 20 steps:
Play the animation one more time to see the whole execution take place.
Bear in mind that our code is only being applied to the chick sprite. If you add a new sprite, the workspace will appear blank for that sprite while our code remains there normally for the chick:
And just like that, our first computer interactive program is done, and it already responds to user input by moving our character on the stage!
We’ve covered a lot of ground in how the block-based coding of Scratch works. However, you might be asking, “Why” and “How” we knew what blocks to use. For that, let’s take a step back and discuss one of the most fundamental aspects of coding.
You may not realize it, but you have just created and executed an algorithm! Algorithms are everywhere and are not only related to computer science stuff. An algorithm is merely a sequence of steps that solves a real-world problem. In this sense, coding or programming is simply the process of making algorithms for a computer to execute.
An example of an algorithm from our daily lives can be something as common as making a piece of toast. It could be represented by the following steps:
As you can see, an algorithm lists all of the steps that are needed in order to achieve the desired outcome. In other others, an algorithm is nothing but a set of instructions that need to be followed in a specific order!
Algorithms can be visually described by a flowchart. Our toast example above would produce this flowchart here:
We specify the start of our algorithm with a ‘Begin‘ block (in blue) then proceed to place statement blocks (green rectangles), each containing one of the steps of our algorithm. We finish it by adding an ‘End‘ block (also in blue) to point out where the algorithm ends. Note that although we’re using specific colors in this tutorial, they are not part of the flowchart convention. Flowcharts don’t need to have any particular colors.
Flowcharts are useful for code documentation and to allow us to check that we’ve implemented everything correctly, and have not skipped any of the necessary steps of our algorithm. With all this in mind, let’s now create a brand new project so we can move on to making our first animation in Scratch!
You may have noticed in the above section, we also mentioned the “x coordinate”. Before we proceed to our final first project, let’s talk about this concept so you understand why it’s important to moving sprites.
We’re going to use coordinates to move and position our sprite on the screen. For every spot on the game stage, we have a corresponding value for x and y that form the coordinate for that particular point in the grid. Coordinate (0, 0), also known as origin, is right at the very center of the game stage:
To help us better visualize how coordinates work, let’s choose a new background. Click on the ‘Choose a Backdrop’ button and search for “coordinates“, then select ‘Xy-grid‘:
This background allows us to see the values of x and y for the entire stage area:
The X-axis values increase as we move to the right and decrease to the left, so if you move left past zero you’ll have negative values for x. Similarly, values of y increase as we move the sprite up and decrease as we bring it down the game stage past the X-axis.
You can also enter specific values for one axis or both axes and the cat will be repositioned automatically:
Now that we have a good understanding of Scratch, we’ll put everything to the test by making a Scratch animation involving simple sprite movement.
Before we step into the actual code for our new project, let’s rename it to ‘Cat Animation’ at the top bar:
For this project, let’s change the background once more to ‘Bedroom 2‘:
We’re choosing a new backdrop because we want to make our cat sprite move to the drawer, later to the computer desk, then to the window, and lastly to the bottom right corner of the carpet of the bedroom.
For our animation to start when the player clicks on the green flag button, let’s initiate our code by adding the event block for when the green flag is clicked:
As we want to have our cat positioned by the bed once the animation is started, we can use the “go to” block (from the Motion category):
To know which values for x and y to enter, we can place the cat where we want it to be at the start of our animation (in this case, on top of the bed) and then use the same coordinates shown in the sprite properties panel in the motion block in question. That is so because if you manually move the sprite around in the stage and then proceed to use any block that has the sprite’s coordinates, the block will already have the sprite’s updated location on it. Also, note that each category has a color, so, when you see a block you can automatically identify from which category that block is.
Now if we click the green flag icon, the cat is moved to the bed straight away:
Next, we want to move the cat to the drawers next to the bed. Here, we’re going to use the “glide” block instead:
The glide block takes the amount of time indicated in seconds to move the sprite, thus it’s not immediate as the go to block.
Now that we’ve shown you the basic process, try the rest yourself first! Update the coordinates and complete the remaining steps:
All moves should take 2 seconds each. Don’t worry if you get stuck – we’ll cover the final code next.
The solution to the challenge is as follows.
Let’s add another glide block to our code, and move the cat to the computer:
Note that we’ve changed the duration of our first glide block to 2 seconds as well just so it matches the following glide blocks we’ll have.
Repeat this process for the window and carpet:
Our code is now complete! Running the code we see that everything goes as expected:
In the end, the cat is standing on the carpet by the bottom right corner of the bedroom.
If you have solved the challenge in a different manner, that’s fine! Quite often there is more than one way to do the same thing in programming. In case you couldn’t solve it, don’t worry as you can always keep practicing now that you’ve seen how the challenge was solved!
You can run our cat animation project by heading over to the public project page at https://scratch.mit.edu/projects/667377329/
Finally, let’s check the flowchart for our animation project:
For this flowchart, we’re using a new type of block (the one in orange) which can be used for user input/output, such as waiting for the user to press a button (as is the case above) or displaying a message to the user.
Congratulations on reaching the end of this tutorial! By now you not only have coded your first program in Scratch, but have also already created your first animation! You also have learned about algorithms and how to create flowcharts to better visualize the steps being taken.
Coding is an important skill that can be developed at any age and is being included more and more in schools in general. It improves creativity & problem-solving, and can offer a wide range of careers worldwide for those who take it professionally. Likewise, Scratch is used throughout the globe across many different age groups. With its intuitive drag-and-drop interface, it’s easy to learn the basics of programming and practice coding by trying out the various types of blocks from all the available categories in the block palette.
If you want to build more interactive projects in Scratch, you can check out the Jr Coder Mini-Degree offered by Zenva. This curriculum covers a slew of different Scratch projects and programming principles to help expand your skills and give you a solid understanding of programming in general.
On the flip side, for teachers who want to use Scratch as a tool for their classroom, Zenva Schools can help you out. Zenva Schools is an online platform that offers coding courses for use in the classroom on a variety of subjects, including Scratch, Python, HTML & CSS, and Unity. With other features such as pre-mapped course plans and reporting, it can be a fast and easy way to introduce students to a myriad of important digital topics.
In any case, we hope that you continue to explore and create real-world programs and games – and most of all that you have fun while doing it!
]]>
In this tutorial, we’re going to be building an app in Unity that will connect to an API, send a query, and return a JSON file of results to display on the screen. For this case, we’re going to be making an app that will display upcoming fireworks displays.
If you’re ready to learn a new skill for making apps in Unity, let’s dive in.
This project will feature a prefab that is already pre-made. Along with that, you can download the included project files here.
Note that this tutorial does assume you have a solid understanding of working with Unity. If you’re just starting out on your Unity journey, we recommend first finding some beginner tutorials or courses to help you along with the fundamentals.
Alternatively, if you’re a teacher, you can also try out the Zenva Schools platform to find great resources on not only using Unity, but incorporating it into classroom environments.
With our app, we’re going to be displaying data on our screen. This data is going to be a list of upcoming firework displays. The Queensland Government has a good website with a lot of different data sets to connect to.
Upcoming fireworks displays dataset.
When on the website, click on the Data API button. This is a list of example queries. What we want is the query which returns results containing a certain string.
https://data.qld.gov.au/api/action/datastore_search?resource_id=346d58fc-b7c1-4c38-bf4d-c9d5fb43ce7b&q=
Create a new 2D Unity project. The first thing we need to do is change our aspect ratio. Since we’re designing a mobile app, let’s go to the Game tab and add a new aspect ratio of 9:16. It will be scalable for any aspect ratio, we’re just going to design is for portrait displays.
Let’s also change the background color. Select the camera and set the Background to a dark blue – I used the color 32323C.
For accessing and converting the data, we’re going to be using an asset called SimpleJSON. You can download it from GitHub here.
Right click the Hierarchy and select UI > Canvas. Now we can begin with our UI!
Create two empty GameObjects (right click Canvas > Empty GameObject) and call them Header and FireworkList. The header will hold our search bar and filter buttons.
For the firework list, just make that fill in the rest of the space and anchor to stretch-stretch. This is where we’ll be listing out our data.
For the search bar, create a new TextMeshPro – Input Field as a child of the header (you might need to import a few assets). Call it SearchSuburb.
Let’s now work on our filter buttons. Create an empty GameObject and call it FilterButtons. Set the anchor and positions to the same as the search bar but below it.
Then add a Horizontal Layout Group component. Enable all of the tick boxes and set the Spacing to 5. This is used to evenly position and scale our buttons automatically.
As a child of the FilterButtons, create a new button, remove the text child and set the color to the same as the search bar.
Now, create a new TextMeshPro – Text object as a child of the button.
Duplicate the button 3 times for a total of 4 buttons: Today, Week, Month and All.
Let’s now work on the list of fireworks. First, create an empty GameObject as the child of FireworkList and call it Container.
On the FireworkList object, add Scroll Rect and Rect Mask 2D components. This will allow us to scroll up and down the list. Make sure you copy the properties as seen below:
Create a new button (call it FireworkSegment), like with the others – remove the text child and add a TextMeshPro one (two in this case).
To finish this off, create a folder called Prefabs and drag the firework segment into it. Delete the one in the scene as we’ll be spawning them in later.
To make the app a little more interesting, we’re going to add in some firework visuals to the UI. Create a new Render Texture right click Project window > Create > Render Texture and call it FireworkRenderTexture. All we need to do here, is set the Size to 500 x 500.
Then go to the Tags & Layers screen (Edit > Project Settings > Tags & Layers) and add a new layer called Firework. This is for the camera to render only the fireworks.
Next, create a new camera and drag it away from the other. Attach the render texture to it and the other properties as seen below:
Now in the Prefabs folder, there should be two particle prefabs. Drag those in and position them in-front of the camera. We’ll be adjusting these later.
The last part of the UI is the drop down info box. This will display more information about an event when you select it. Create a new Image object as the child of the container (call it InfoDropdown).
Then add two TextMeshPro texts for the info and address, and a Raw Image for the render texture of the fireworks.
In the Game view, you should be able to see the fireworks on the UI!
Now it’s time to start scripting. Create a new folder called Scripts and create a new C# script called AppManager. To hold this script, create a new GameObject called _AppManager and attach the script to it.
Inside of our script, we’ll first add the namespaces we’re going to use.
using UnityEngine.Networking; using System.Text; using System; using System.Linq; using SimpleJSON;
Inside of our class, let’s first define the Duration enumerator. This is a list of all the types of duration filters we can use.
public enum Duration { Today = 0, Week = 1, Month = 2, All = 3 }
Our first two variables are the url, which is what’s going to connect to the API, and the jsonResult which will be a list of the data.
// API url public string url; // resulting JSON from an API request public JSONNode jsonResult;
Finally, let’s create a singleton / instance for the script. This will allow us to easily access it whenever we want.
// instance public static AppManager instance; void Awake () { // set the instance to be this script instance = this; }
So how are we going to get the data? Let’s create a co-routine called GetData. This will take in a string for the location and add that to the query. If the location string is empty, it will request for all the data. We’re using a co-routine because we need to pause the function midway to send/receive the data.
// sends an API request - returns a JSON file IEnumerator GetData (string location) { }
First up, let’s create the web request and download handler, building the url also, including the query.
// create the web request and download handler UnityWebRequest webReq = new UnityWebRequest(); webReq.downloadHandler = new DownloadHandlerBuffer(); // build the url and query webReq.url = string.Format("{0}&q={1}", url, location);
Next, we’ll send the web request. This will pause the function and wait for a result before continuing.
// send the web request and wait for a returning result yield return webReq.SendWebRequest();
With our result, let’s convert it from a byte array to a string, then parse that into a JSONNode object.
// convert the byte array and wait for a returning result string rawJson = Encoding.Default.GetString(webReq.downloadHandler.data); // parse the raw string into a json result we can easily read jsonResult = JSON.Parse(rawJson);
We haven’t made the UI script yet, but this is what we’re going to call. We’re sending over the records of the JSON file to make them appear on-screen.
// display the results on screen UI.instance.SetSegments(jsonResult["result"]["records"]);
Now let’s work on the FilterByDuration function. This gets called when one of the filter buttons gets pressed.
// called when a duration button is pressed // filters the list based on the max time length given public void FilterByDuration (int durIndex) { }
First, let’s convert the durIndex to a selection of the Duration enumerator. Then we’ll get an array of the records so we can sort through them.
// get the duration enum from the index Duration dur = (Duration)durIndex; // get an array of the records JSONArray records = jsonResult["result"]["records"].AsArray;
Next, we’ll get the max date depending on the filter duration.
// create the max date DateTime maxDate = new DateTime(); // set the max date depending on the duration switch(dur) { case Duration.Today: maxDate = DateTime.Now.AddDays(1); break; case Duration.Week: maxDate = DateTime.Now.AddDays(7); break; case Duration.Month: maxDate = DateTime.Now.AddMonths(1); break; case Duration.All: maxDate = DateTime.MaxValue; break; }
Then we’ll loop through all the records and add the ones before the max date to filteredRecords.
// create a new JSONArray to hold all the filtered records JSONArray filteredRecords = new JSONArray(); // loop through all the records and add the ones within the duration, to the filtered records for(int x = 0; x < records.Count; ++x) { // get the record's display date DateTime recordDate = DateTime.Parse(records[x]["Display Date"]); // if the record's display date is before the max date, add it to the filtered records if(recordDate.Ticks < maxDate.Ticks) filteredRecords.Add(records[x]); }
Finally, like in the last function, we’ll call the UI function.
// display the results on screen UI.instance.SetSegments(filteredRecords);
Create a new C# script called UI and attach it to the _AppManager object.
We’re going to need these namespaces.
using UnityEngine.UI; using TMPro; using SimpleJSON; using System;
First, we have our variables to hold our container, segment prefab and list of all segments.
// holds all the segments in a vertical layout public RectTransform container; // segment prefab to instantiate public GameObject segmentPrefab; // list of all available segments private List<GameObject> segments = new List<GameObject>();
Then we have the variables for the drop down.
[Header("Info Dropdown")] // info dropdown object public RectTransform infoDropdown; // text showing time, event type, etc public TextMeshProUGUI infoDropdownText; // text showing the event address public TextMeshProUGUI infoDropdownAddressText;
And finally an instance for this script.
// instance public static UI instance; void Awake () { // set the instance to this script instance = this; }
The CreateNewSegment function, creates a new segment and returns it.
// creates a new segment and returns it GameObject CreateNewSegment () { // instantiate and setup the segment GameObject segment = Instantiate(segmentPrefab); segment.transform.parent = container.transform; segments.Add(segment); // add OnClick event listener to the button segment.GetComponent<Button>().onClick.AddListener(() => { OnShowMoreInfo(segment); }); // deactivate it by default segment.SetActive(false); return segment; }
The PreLoadSegments function pre-loads / spawns a set number of segments.
// instantiates a set number of segments to use later on void PreLoadSegments (int amount) { // instantiate 'amount' number of new segments for(int x = 0; x < amount; ++x) CreateNewSegment(); }
We’ll call this in the Start function.
void Start () { // preload 10 segments PreLoadSegments(10); }
The SetSegments function gets called when we either search for a suburb or filter the results. This takes in the records and displays them on screen.
// gets the JSON result and displays them on the screen with their respective segments public void SetSegments (JSONNode records) { DeactivateAllSegments(); // loop through all records for(int x = 0; x < records.Count; ++x) { // create a new segment if we don't have enough GameObject segment = x < segments.Count ? segments[x] : CreateNewSegment(); segment.SetActive(true); // get the location and date texts TextMeshProUGUI locationText = segment.transform.Find("LocationText").GetComponent<TextMeshProUGUI>(); TextMeshProUGUI dateText = segment.transform.Find("DateText").GetComponent<TextMeshProUGUI>(); // set them locationText.text = records[x]["Suburb"]; dateText.text = GetFormattedDate(records[x]["Display Date"]); } // set the container size to clamp to the segments container.sizeDelta = new Vector2(container.sizeDelta.x, GetContainerHeight(records.Count)); }
DeactivateAllSegments deactivates all of the segments. This gets called at the start of SetSegments.
// deactivate all of the segment objects void DeactivateAllSegments () { // loop through all segments and deactivate them foreach(GameObject segment in segments) segment.SetActive(false); }
GetFormattedDate returns a date in the day / month / year format from a raw date.
// returns a date that is formatted from the raw json data string GetFormattedDate (string rawDate) { // convert the raw date to a DateTime object DateTime date = DateTime.Parse(rawDate); // build a "[day]/[month]/[year]" formatted date and return it return string.Format("{0}/{1}/{2}", date.Day, date.Month, date.Year); }
GetContainerHeight returns a height to set the container to. This makes it so the container clamps to the active segments.
// returns a height to make the container so it clamps to the size of all segments float GetContainerHeight (int count) { float height = 0.0f; // include all segment heights height += count * (segmentPrefabs.GetComponent<RectTransform>().sizeDelta.y + 1); // include the spacing between segments height += count * container.GetComponent<VerticalLayoutGroup>().spacing; // include the info dropdown height height += infoDropdown.sizeDelta.y; return height; }
OnShowMoreInfo gets called when the user clicks on a segment button. This opens up the drop down with more info about the event.
// called when the user selects a segment - toggles the dropdown public void OnShowMoreInfo (GameObject segmentObject) { // get the index of the segment int index = segments.IndexOf(segmentObject); // if we're pressing the segment that's already open, close the dropdown if(infoDropdown.transform.GetSiblingIndex() == index + 1 && infoDropdown.gameObject.activeInHierarchy) { infoDropdown.gameObject.SetActive(false); return; } infoDropdown.gameObject.SetActive(true); // get only the records JSONNode records = AppManager.instance.jsonResult["result"]["records"]; // set the dropdown to appear below the selected segment infoDropdown.transform.SetSiblingIndex(index + 1); // set dropdown info text infoDropdownText.text += "Starts at " + GetFormattedTime(records[index]["Times(s)"]); infoDropdownText.text += "\n" + records[index]["Event Type"] + " Event"; infoDropdownText.text += "\n" + records[index]["Display Type"]; // set dropdown address text if(records[index]["Display Address"].ToString().Length > 2) infoDropdownAddressText.text = records[index]["Display Address"]; else infoDropdownAddressText.text = "Address not specified"; }
GetFormattedTime returns a time as a string from a raw time.
// converts 24 hour time to 12 hour time // e.g. 19:30 = 7:30 PM string GetFormattedTime (string rawTime) { // get the hours and minutes from the raw time string[] split = rawTime.Split(":"[0]); int hours = int.Parse(split[0]); // converts it to "[hours]:[mins] (AM / PM)" return string.Format("{0}:{1} {2}", hours > 12 ? hours - 12 : hours, split[1], hours > 12 ? "PM" : "AM"); }
OnSearchBySuburb gets called when the user finished typing in the suburb input field. This calls the GetData function in the AppManager script.
// called when the input field has been submitted public void OnSearchBySuburb (TextMeshProUGUI input) { // get and set the data AppManager.instance.StartCoroutine("GetData", input.text); // disable the info dropdown infoDropdown.gameObject.SetActive(false); }
Back in the editor, let’s fill in both scripts. The url is: https://data.qld.gov.au/api/action/datastore_search?resource_id=346d58fc-b7c1-4c38-bf4d-c9d5fb43ce7b
Let’s connect the filter buttons up to the AppManager script.
For the SearchSuburb input field, let’s add the OnSearchBySuburb event to On End Edit. This will get the data when we finish typing.
Right now, our app works! Let’s add another script so the fireworks can change to a random color each time they emit. Create a new C# script called FireworkRandomizer and attach it to both firework particles.
We just need one namespace for this script.
using System.Linq;
Our variables are just an array of available colors and the particle system. We get that in the Start function and start invoke repeating the SetRandomColors function every time the particle emits.
// array of all available colors for the particles public Color[] particleColors; // particle system of the firework private ParticleSystem particle; void Start () { // get the particle system component particle = GetComponent<ParticleSystem>(); // call the 'SetRandomColors' everytime the particle emits InvokeRepeating("SetRandomColors", 0.0f, particle.main.duration); }
SetRandomColors sets the particle’s color gradient to 2 random colors.
// sets the particle to be a random color gradient public void SetRandomColors () { // create a list to keep track of colors we've got left to use List<Color> availableColors = particleColors.ToList(); Color[] colors = new Color[2]; for(int x = 0; x < colors.Length; ++x) { // get a random color colors[x] = availableColors[Random.Range(0, availableColors.Count)]; availableColors.Remove(colors[x]); } // get the particle's main module and set the start color ParticleSystem.MainModule main = particle.main; main.startColor = new ParticleSystem.MinMaxGradient(colors[0], colors[1]); }
In the editor, let’s add some colors.
The app’s now finished! Give it a go and see if you can even more features. Try connecting to a different API or displaying the information in a different way.
Even though we designed it for a portrait display, it can easily work for landscape due to us setting up the right UI anchors.
Once again, you can download the project files here.
That’s it for this tutorial!
If you’re looking to expand your Unity skills further, the Unity Game Development Mini-Degree is a fantastic resource for building games and projects delivered in a completely beginner-friendly way. Educators can also try out the Zenva sister platform, Zenva Schools, for more school-oriented content with classroom management and reporting tools, pre-made course plans, and more.
Regardless of where you go next, we hope these new API skills help!
]]>With this tutorial, you’ll learn the basics of animating with code using Scratch by building a fish animation. While some familiarity with Scratch will help, this tutorial is perfect for any age since it doesn’t require much knowledge!
If you’re ready to learn how to make coding fun, let’s dive in.
Scratch is a free visual coding tool developed by the Massachusetts Institute of Technology (MIT) for creating games and interactive media. As it uses code blocks instead of text-based coding, it’s very easy for even kids to use as they practice basic computer algorithms.
If this is your first time using Scratch, head over to the Scratch homepage and create a new project (or use one you already have if you wish). Although we’re not going over how to switch sprites or add a background, it all is pretty intuitive to get done.
All the contents of this tutorial can be downloaded here.
For this tutorial, we have a fish sprite on an underwater backdrop in Scratch – and we want our fish sprite to move every time we press the green flag above the game stage:
First, drag the ‘when green flag clicked‘ block from the ‘Events‘ category to the workspace:
By having this block in our code, we’re saying that everything that comes below it is going to be executed whenever the green flag is clicked.
Next, we can add a bubble sound to our sprite. Over the ‘Sound‘ category, bring the ‘start sound‘ block to your code and pin it under the block we have already there:
Click on the arrow to replace the ‘ocean waves’ sound with ‘bubbles‘. If you press the green flag now, you’ll hear the bubbles sound already.
To move the fish, we use the ‘Motion‘ block that says ‘glide 1 secs to random position‘:
Glide takes the sprite to a new position over a period of time. That is, it’s going to move the fish to any position within the background area where the entire movement will only take 1 second. If you click on the green flag, you’ll see it moving:
Note that you can alter the duration (numbers of seconds) the movement is taking by typing a new value on top of the current one.
At the moment, our fish sprite is moving only once when we click the green flag. Go to the ‘Control‘ category, where we have blocks that allow us to repeat a block of code. You’ll see the ‘repeat’ block, where you can enter the number of times you want your code to repeat, and also the ‘forever’ block – the one we want for this project.
Place the ‘forever‘ block below the green flag starting event, with the 2 blocks of code we had added inside it for them to get repeated:
Repetition blocks run the code that’s within them until a given condition is met. In our case, until we hit the stop button (the red button next to the green flag).
Running our program, we see the fish keeps changing its position on the screen while making bubbles sounds, as intended!
Surprisingly, that’s all there is to it! You now have a simple animation at your fingertips, as well as an understanding of a basic coding algorithm.
However, you don’t have to stop here and can expand this project in numerous ways. Perhaps you’ll want to add more fish to your “tank” that all have different animation behavior. You could also give each fish a unique behavior, such as rotating or flipping direction, whenever they reach the target position. Of course, these principles apply to any kind of animation you might want to try out. Perhaps you want to make a jungle where monkeys move from vine to vine.
The point here is that only your imagination is the limit! Either way, we hope these Scratch fundamentals have set you on the right path to expressing yourself in new ways!
Want to learn more about Scratch animating? Try our complete Scratch Projects – Fish Animation course.
]]>Master the fundamentals of how to code and project management for games by learning Python Turtle! You’ll cover important topics related to algorithms, and even create a game for your portfolio! You can also explore more about Python Turtle in the full course below!
In this presentation brought to you by Pablo Farias, you’ll explore how by using Python Turtle and the concepts of computer instructions, you can create a practical game project featuring a turtle that can be moved with key presses. Through these skills, you’ll come to understand computer science principles for programming, learn how projects go from idea to digital solution, and build strong foundations for building games and more! Perfectly suited for beginners, this course will make sure you’re prepared for the technological future of tomorrow!
]]>Start creating Python applications with the Python Turtle library. Not only will you learn the Python Turtle library – which allows us to create digital art and interactive programs – but also learn and apply concepts such as coding and algorithms. You can explore a variety of applications by checking out the full course below!
Intro to Coding with Python Turtle
In this course taught by instructor Daniel Buckley, you’ll explore the Python Turtle library to understand what programming is, how to use a turtle to draw and change shapes, define & design algorithms, and implement algorithms with programming. Regardless of the applications you wish to build, the skills you’ll learn will form strong foundations for any project that you’ll create.
]]>In this tutorial, we’ll be taking an introductory look at Python by learning turtle graphics. Turtle, allows us to use commands in order to draw to the screen. It’s a great way of learning programming since, at its core, it’s all about commands and order of execution. It also provides instant, visual results, so you don’t have to guess what your code is doing.
If you’re ready for this Python turtle tutorial, let’s dive in.
While this project doesn’t require any assets, you can download the finished project files below. We recommend finishing the tutorial first, but you can cross-check our code against yours at any time to verify your answers: Download the completed files here
We also want to recommend you check out our Python Mini-Degree (for learners) or Zenva Schools (for teachers) after this tutorial, to learn more about Python.
When it comes to writing Python code, we need an IDE (integrated development environment), also known as a code editor. This is a text editor which can format, compile, and run our code. While most IDE’s are downloadable programs, some of them, such as Replit, are hosted in the cloud and can only be used using a web browser.
Common features of an IDE include:
In addition, in order to run or execute Python code, you will need access to a Python runtime. That being, a program that can take your Python code (which is just text), translate it into executable commands, and have your machine run it.
Python can be downloaded for all operating systems (Windows, Mac, Linux) on the official Python website.
For this tutorial, I recommend you use Replit as your IDE. Replit, is a cloud-based online code editor which requires no downloading or installation.
To begin, let’s go to the replit.com and click on the Log in button.
The easiest and quickest way would be to log in with your Google account or Facebook, so go ahead and do that.
Once logged in, you’ll be taken to the dashboard. Here is where you can create and manage your projects. Let’s start by clicking on the blue Create button at the top left.
A window will pop up.
Once created, we can begin to code! But first, let’s have a look at our IDE. There are three different windows, each serving a specific purpose.
In this tutorial, we’re going to be learning Turtle graphics in Python. The “turtle” is basically an entity that we can move around the screen. It starts at one point and we can command it to move up 20 pixels for example. The turtle will move up 20 pixels, drawing a line as it does. We can provide a range of different commands which can result in different shapes and colors.
Here’s an example of what we can make the turtle do with a little bit of code.
The turtle only does what it is told to do. So when we create a turtle script, we need to provide all of the commands in order. Let’s say we want to create a cube with a size of 50×50 pixels, here are the commands that we’d need to enter in:
In your head, picture a turtle moving across a flat plane, forwards 50 pixels, then turning 90 degrees to the right and repeating. This will form a cube and is the basis of not just programming the turtle, but computer programming as a whole.
This is also the basis of what an algorithm is – a set of instructions that return to us a result. Using turtle, the instructions are the commands we enter in and the result is the rendered drawing.
First thing’s first, let’s go over to our main.py file in the center of our Repl project and add in the following line of code:
from turtle import *
This will tell the program that we want to use the turtle library, giving us the tools to draw.
So how do we draw? Well, basically we need to provide a list of commands. Let’s start with the forward command. This will move the turtle in its forward direction (right by default).
from turtle import * forward(50)
If you are using Replit, there should be a green Run button at the top of the page. Press that to run the program. The console should now shift over and a window will appear, showing your turtle in action! If you’re using another IDE, press the respective compile or run button.
Let’s now turn the turtle with the right command, 90 degrees. Then move forward 50 pixels again.
from turtle import * forward(50) right(90) forward(50)
This is what the output result should look like when you click Run.
For this example, let’s try and draw a cube. Here’s a diagram showing what we’ll need in order to accomplish that.
Now to finish off our cube, let’s turn right and move forwards twice more.
from turtle import * forward(50) right(90) forward(50) right(90) forward(50) right(90) forward(50)
So we’ve got a cube, but how do we change the color? For that, we can call the color command, and instead of giving it a number, we can give it a color as a string.
In programming, a string is text contained in quotation marks.
It’s important to note, that the color command needs to be the first command executed. The program reads the code from top to bottom, so changing the color at the end won’t do anything since we’ve already drawn the cube.
from turtle import * color("red") forward(50) right(90) forward(50) right(90) forward(50) right(90) forward(50)
Now we have a red cube!
How about circles? Well to draw a circle, we can give the circle command. We can then give it a radius and it will draw a circle to its left.
circle(50)
Here’s what it should look like:
Let’s now look at a few other turtle commands.
Right now we just have wireframe shapes with no filling. To fill in the shape, we can use the begin_fill and end_fill commands.
When you call the begin_fill command, everything after that will be filled in with the color up until you call end_fill. Here’s how we can fill in a red circle:
from turtle import * color("red") begin_fill() circle(100) end_fill()
We can even stack shapes on top of each other, changing the color before doing so.
from turtle import * # set the color to red color("red") # draw and fill a 100px circle begin_fill() circle(100) end_fill() # set the color to blue color("blue") # draw and fill a 50px circle begin_fill() circle(50) end_fill()
You may have noticed the lines of code beginning with #. These are known as comments and are only there for us to easily see what different parts of the code are doing. When the program is compiled and run by the computer, the comments are removed. They are only there for us humans to view and document our own code (very useful for when you come back to it after a long time).
So if you’re ever creating a large block of code, you can leave a comment for yourself or anyone else who views your code.
Also, if you’re wanting to learn more turtle commands, check out the official documentation here.
For the rest of the tutorial, let’s create ourselves a project. This is going to be a visualization of our solar system. So to follow along, you can clear the file of all code, or create a new one.
Before we jump in and begin to code, let’s plan out our project. This will help us with defining what exactly we want and give us an idea on what type of turtle commands we’ll be needing.
First, let’s define our project.
Next, the designing phase. This is where we basically create the project, without writing any code. We need to know what we’re going to do, how large the planets will be, the distance between them and their color. Below is a diagram of what we’re going to create.
It shows the planets, along with their respective pixel radius’ (right column) and distance (left column).
So we’ve got our diagram – we know the planet sizes, colors, and distances. But before we start to code, let’s create a flowchart. This will help us understand the flow of code. How do we go from drawing one planet to another?
Finally, a good step in the design phase is to write out your project in pseudo-code. This is writing out the lines of code without any specific programming language in mind. Basically, writing it out in English. Pseudocode is good because you don’t need to know the syntax or libraries of any specific language in order to write it. There’s also no universal format for it. As long as your pseudo-code can convey the commands and processes of your program, then it should be good.
So for us, we have four circles we need to draw, each with a different color and radius. We’ve already listed out the numbers and colors, so let’s get to writing the pseudo-code!
Set the background color to BLACK Set color to ORANGE Draw circle (60px radius) Turn right (90 degrees) Move forwards (70 pixels) Turn left (90 degrees) Set color to GRAY Draw circle (20px radius) Turn right (90 degrees) Move forwards (100 pixels) Turn left (90 degrees) Set color to RED Draw circle (40px radius) Turn right (90 degrees) Move forwards (100 pixels) Turn left (90 degrees) Set color to GREEN Draw circle (30px radius) Turn right (90 degrees) Move forwards (100 pixels) Turn left (90 degrees)
I’m sure that reading the pseudo code, you can already start to see how we could translate some of that to turtle. Moving forwards would be the turtle.forward() command and setting the color would be the turtle.color() command.
First, let’s import turtle and set the background color to black. This is how we do that:
from turtle import * # paint screen black bgcolor("black")
We access the turtle, then the screen, then the background color.
First up, let’s draw the sun. How are we going to do this? Let’s list out commands we’re going to need in order to get the result we’re looking for before. This is a good step to do before coding, since it will allow you to plan ahead and have a better understanding of what needs to be done.
Now let’s translate that into Python code:
# draw sun color("orange") begin_fill() circle(60) end_fill()
Before we start to draw the planets, we need to move the turtle down as we do want some gap between the shapes. At the moment the turtle’s forward direction is right. So let’s list out the commands needed to move.
Let’s code that now.
# turn and move down right(90) forward(70)
But hold on! There’s a problem here. We are able to see the path of the turtle so there are going to be these annoying lines all over the place. How can we fix that? Well with turtle, we can think of it like a pen moving across a piece of paper. If you want to draw one thing, then another without drawing a line between them… you can simply lift your pen up – and that’s exactly what we can do with turtle.
The penup command will make it so the turtle is no longer drawing, and pendown will return the drawing functionality.
So let’s update that code we just entered in.
# turn and move down right(90) penup() forward(70)
Much better! Now to draw the first planet. Since turtle creates circles towards its left-hand side, we need to rotate the turtle left.
left(90)
Then to begin drawing again, we need to put our pen down.
pendown()
And then we can draw the planet:
color("gray") begin_fill() circle(20) end_fill()
From here, the process is pretty much the same.
As a bit of a challenge, I want you to create 2 more planets with these properties:
Here’s what it should look like:
Look away now, and then come back here to find the answer.
Alright, so I hope you had a go at that challenge. Here’s the code required for the red planet.
# move to next planet position right(90) penup() forward(100) # draw planet left(90) pendown() color("red") begin_fill() circle(40) end_fill()
And finally for the green planet.
# move to next planet position right(90) penup() forward(100) left(90) pendown() color("green") begin_fill() circle(30) end_fill()
You may notice that the time it takes to draw all of the planets can be a while. This isn’t a limitation of the software though. In fact, we can choose to speed up, slow down or skip entirely the animation.
So let’s go right to the top of our script, just below where we import turtle. The speed command allows us to specify the speed, between 0 and 10.
speed(0)
So if we set the speed to 0, you’ll notice that it’s almost instantly drawn when we press run.
So there we have it, an introductory look at the Python programming language using turtle.
Turtle is a fantastic way to start learning to program. It teaches many great fundamentals of programming such as order of execution and giving commands. It also allows us to instantly see the results of our code visually. However, it avoids many other programming concepts that might otherwise trip beginners up. Instead, you can focus on algorithms and learn, regardless of syntax or data, how computers use instructions to perform operations.
If you want to learn the full extent of turtle, then check out the Turtle graphics documentation here.
If you want to learn more Python programming, you can also check out the Python Mini-Degree offered by Zenva, which covers the full extent of using Python to create real-world programs for games, apps, data science, machine learning, and more.
Or, if you’re a teacher, you may be interested in Zenva Schools, which offers coding courses suitable for the classroom. Not only can you explore Python with your students further, but also explore many other different programming languages. Zenva Schools comes with a variety of tools for teachers – including reporting and pre-made course plans – and has courses made in collaboration with both teachers and industry professionals.
Thank you very much for following along, and good luck with your future Python turtle projects!
]]>