Explore Free Educational Game Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Wed, 19 Apr 2023 05:30:47 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free Educational Game Tutorials – GameDev Academy https://gamedevacademy.org 32 32 Beginner’s Unreal Engine Tutorial: Make Auto-Stacking Blocks https://gamedevacademy.org/stacking-blocks-unreal-tutorial/ Fri, 07 Apr 2023 06:26:08 +0000 https://gamedevacademy.org/?p=20161 Read more]]> Unreal Engine’s Blueprint Visual Scripting system vastly simplifies coding – making it easier for developers of any skill level to develop their games.

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!

Project Files

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!

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Setting Up our Project

First of all, let’s go to the Content folder and create a new Loops folder there:

Creating a folder called "Loops" in Unreal Engine

Then, we’ll create a new Basic level. Let’s name it LoopsLevel and save it in the Content > Loops folder:

Adding a new Basic level to the 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:

  • The Actor blueprint named Box
  • The GameMode blueprint named LoopsGameMode

We’ll save those blueprints in the Content > Loops folder as well:

Actor and GameMode blueprints added to the Loops folder

Box Blueprint

Now, let’s open the Box blueprint asset. First thing, we’ll add a new Cube component to our Box blueprint:

Adding a Cube to our Box blueprint

Cube added to the Box blueprint in Unreal Engine

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:

Setting the Material of the Cube to "M_CobbleStone_Smooth"

Cube with the 'M_CobbleStone_Smooth' texture in Unreal Engine

After that, in the Cube’s Physics component, we’ll enable the Simulate Physics property, so our cube would have physics working on it:

Enabling the Simulate Physics property for the Cube object

Then, you can Compile and Save the Box blueprint.

LoopsGameMode 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:

  1. Sets the Index property to the First Index’s value
  2. If the Index is less or equal to the Last Index, this node triggers the Loop Body control flow output pin. Otherwise, the cycle is ended and the control flow goes to the Completed pin
  3. Increments the Index
  4. Goes back to step “2

Connecting the BeginPlay event to the ForLoop node in Unreal Engine

For the beginning, let’s run our loop ten times and print the index of the current iteration:

  • Set the Last Index property of the ForLoop node to 10
  • Connect the ForLoop’s Loop Body control flow to a new PrintString node
  • Connect the ForLoop’s Index pin to the In pin of the PrintString node

Printing out the index of the current iteration of our loop

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:

Making the 'GameMode Override' reference the LoopsGameMode

If you start the game now, you should see the numbers going from 0 to 10 in the top-left corner of the screen:

Numbers from 0 to 10 printed out 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:

LoopsGameMode Blueprint so far in Unreal Engine

If we’ll set the Last Index property to 1000, we’ll see numbers running from 0 to 1000 at the game start:

Setting up "Last Index" to 1000

Numbers from 0 to 1000 printed out to the screen

Using the loops allows us to save time and not copy-paste our code to be executed as many times as we want.

Spawning A Hundred Boxes

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:

Deleting the PrintString node from our LoopsGameMode blueprint

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:

Connecting the 'Loop Body' pin to a new SpawnActorFromClass node in Unreal Engine

Next, in the SpawnActor node, we’ll set the Class property to Box, so it would spawn the Box blueprint we created earlier:

Setting "Class" to Box in the SpawnActor

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:

Changing "Last Index" back to 10

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:

Connecting a Make Transform node to the Actor's 'Spawn Transform' input pin

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:

Spawning 10 cubes in Unreal Engine

If you set the ForLoop’s LastIndex to 100, you’ll have a hundred cubes flying around:

Making "Last Index" equal to 100 and spawning a 100 cubes in the level

Spawning A Tower

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:

  • Connect the MakeTransform node’s Location input pin to a new Multiply node. You have to connect the Multiply node to the Location pin first, so the Multiply node would return the Vector type
  • Connect the ForLoop node’s Index output pin to the first input pin of the Multiply node
  • Set the second input pin of the Multiply node to (0, 0, 120)

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:

Making the cubes spawn on top of each other

If you spawn a hundred cubes now, they will be aligned in a straight vertical line, forming a tower of sorts:

Spawning a tower of cubes in Unreal Engine

Though, that tower will crumble a second later, as soon as physics catches up with it:

Tower of cubes crumbling due to physics

Giving Boxes A Random Rotation

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:

Connecting a Random Rotator node to the Make Transform's 'Rotation' input

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:

The cubes fall down as soon as spawned because they no longer stack upon one another

After The Loop Ends

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:

  • Connect the ForLoop node’s Completed output control flow pin to a new PrintString node
  • Set the In property of the PrintString node to “All boxes have been spawned!

Printing out a message after all cubes have been spawned

Now you’ll have the “All boxes have been spawned!” message shown once all the cubes have been spawned:

Message printed to the screen in Unreal Engine

Loops Challenge

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:

Pyramid of cubes in Unreal Engine

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:

Removing the Random Rotator node from the blueprint

Then, you should also iterate the For Loop from 0 to 10. This way your pyramid would be small and stable enough:

For Loop iteration from 0 to 10

And that’s all the hints we have for you! Now you can go and try to solve the challenge.

Challenge Solution

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:

  • Create a new Subtract node
  • Connect the ForLoop’s Index pin to the second input pin of the Subtract node, as we want to subtract the Index from the first value
  • Set the first input pin of the Subtract node to 10. It should have the same value as the Last Index pin of the ForLoop node

This way, for the 0 Index, we’ll have 10, for the 1 Index, we’ll have 9, and so forth:

Flipping the Index to construct the base of the pyramid

Then, we’ll create the scaling Vector from that flipped Index:

  • Create a new Make Vector node
  • Connect the output pin of the Subtract node to the X and Y input pins of the MakeVector node
  • Set the Z pin of the MakeVector node to 1, so the cubes would have 100% height

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:

Using a Vector to make the levels of the pyramid

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:

Connecting the Make Vector to the Make Transform node

As the result, you should get a nice cube pyramid:

Final pyramid all set in the level

And if you look closely at the bottom levels of that pyramid, you’ll see that each level is just a stretched cube:

Each level of the base is formed of a single stretched cube

Conclusion

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.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Complete Guide to GDScript – Godot’s Scripting Language https://gamedevacademy.org/complete-gdscript-godot-tutorial/ Thu, 06 Apr 2023 06:21:05 +0000 https://gamedevacademy.org/?p=20233 Read more]]> What is the best programming language for Godot?

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!

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Introduction to GDScript

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.

What is GDScript?

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.

Benefits of using GDScript

Here are a few reasons why GDScript is a great choice for game development:

  • It’s easy to learn and use, even for those who are new to programming
  • It’s optimized for game development, so you can write code faster and more efficiently
  • It integrates well with the Godot engine, making it a great choice for game development with Godot

Setting up the development environment

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!

2D Platformer made with Godot 4

Variables and Data Types

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.

Introduction to Variables

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.

Declaring and Initializing Variables

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"

Data Types in GDScript

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:

    • Integer: Whole numbers, such as 1, 2, 3, etc.
var score: int = 10
    • Float: Numbers with decimal places, such as 1.5, 2.7, etc.
var price: float = 19.99
    • String: Text values, such as “hello”, “goodbye”, etc.
var player_name: String = "John Doe"
    • Boolean: A value that can either be “true” or “false”.
var game_over: bool = false
    • Array: A collection of values that can be of any data type.
var players: Array = [ "John Doe", "Jane Doe", "Jim Doe" ]
    • Dictionary: A collection of key-value pairs where each key is unique.
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.

Real-time strategy game made with Godot 4

Operators and Expressions

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

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:

    • +: Addition operator, used to add two values together.
var result = 2 + 2 # result will be 4
    • -: Subtraction operator, used to subtract one value from another.
var result = 5 - 2 # result will be 3
    • *: Multiplication operator, used to multiply two values.
var result = 2 * 2 # result will be 4
    • /: Division operator, used to divide one value by another.
var result = 4 / 2 # result will be 2
    • %: Modulus operator, used to find the remainder of a division operation.
var result = 7 % 3 # result will be 1

Assignment Operators

Assignment operators are used to assign values to variables. Here are the most common assignment operators in GDScript:

    • =: Simple assignment operator, used to assign a value to a variable.
var score = 10
    • +=: Addition assignment operator, used to add a value to a variable and then assign the result back to the same variable.
var score = 10
score += 5 # score will now be 15
    • -=: Subtraction assignment operator, used to subtract a value from a variable and then assign the result back to the same variable.
var score = 10
score -= 5 # score will now be 5
    • *=: Multiplication assignment operator, used to multiply a value with a variable and then assign the result back to the same variable.
var score = 10
score *= 2 # score will now be 20
    • /=: Division assignment operator, used to divide a value with a variable and then assign the result back to the same variable.
var score = 10
score /= 2 # score will now be 5

Comparison Operators

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:

    • ==: Equality operator, used to check if two values are equal.
var result = 2 == 2 # result will be true
    • !=: Inequality operator, used to check if two values are not equal.
var result = 2 != 2 # result will be false
    • <: Less than operator, used to check if one value is less than another.
var result = 2 < 3 # result will be true
    • >: Greater than operator, used to check if one value is greater than another.
var result = 2 > 3 # result will be false
    • <=: Less than or equal to operator, used to check if one value is less than or equal to another.
var result = 2 <= 2 # result will be true
    • >=: Greater than or equal to operator, used to check if one value is greater than or equal to another.
var result = 2 >= 3 # result will be false

Logical Operators

Logical operators are used to perform operations on boolean values and return a boolean result. Here are the most common logical operators in GDScript:

    • and: Logical and operator, used to combine two boolean values and returns true only if both values are true.
var result = true and true # result will be true
    • or: Logical or operator, used to combine two boolean values and returns true if at least one value is true.
var result = false or true # result will be true
    • not: Logical not operator, used to negate a boolean value and returns the opposite value.
var result = not false # result will be true

3D Platformer made with Godot 4

Control Flow Statements

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.

If Statement

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

If-Else Statement

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

For Loop

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

While Loop

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

Survival game made with Godot 4

Functions

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.

Defining Functions

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

Return Statement

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

Optional Parameters

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

Variable Number of Parameters

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

Skiing mini-game made with Godot 4

Classes and Objects

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.

Defining Classes

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

Constructor

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

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

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

Turn-based RPG made with Godot 4

Error Handling

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.

Try-Except Blocks

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.

Raising Exceptions

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.

Custom Exceptions

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.

Physics sandbox game made with Godot 4

File Input and Output

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.

Writing to Files

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.

Reading from Files

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.

Error Handling

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.

Conclusion

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!

Primary Resources

Premium Godot Tutorials

Free Godot Tutorials

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Best Puzzle Game Tutorials – Building Games to Test the Mind https://gamedevacademy.org/best-puzzle-game-tutorials/ Wed, 25 Jan 2023 09:41:48 +0000 https://gamedevacademy.org/?p=15510 Read more]]> Who’s not familiar with classic puzzle games like Tetris, Breakout, Snake, Minesweeper, Sudoku, or even recent ones such as Candy Crush and Baba Is You? Now imagine you coding your own version of these games. Wouldn’t that be awesome?

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!

How to Make Minesweeper in Unity

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:

  • Project creation
  • Importing sprites
  • Scene setup
  • Cells and game board
  • Flag, reveal, and mine exploding scripting
  • Win state

Duration: 1.5 hours of video training

Access now: How to Make Minesweeper in Unity

Make a Brick Breaker Game 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:

  • Creating the ball object
  • Bouncing the ball
  • Ball velocity and collision logic
  • Paddle movement
  • Positioning bricks
  • Game states
  • UI panels
  • Score and game over
  • Resetting the game

Duration: 2 hours of video training

Access now: Make a Brick Breaker Game in Unity

Block Puzzle Mobile Game – Unity Tutorial

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:

  • Importing the game assets into Unity
  • UI/menu screens
  • Displaying the grids and the shapes
  • Random shape creation logic
  • Dragging and dropping the shapes onto the grid
  • Line completion checking to update the score
  • Winning and game over logic

Duration: 8.5 hours of video training

Access now: Block Puzzle Mobile Game – Unity Tutorial

How to Make Tetris in Unity

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:

  • Project creation
  • Importing sprites
  • Scene and tilemap setup
  • Spawning, movement, and rotation of the blocks
  • Locking the blocks on the grid
  • Line clearing
  • Game over restart
  • Ghost pieces

Duration: 2 hours of video training

Access now: How to Make Tetris in Unity

Create 2048 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:

  • Creating the grid
  • Dynamic background
  • Spawning tiles
  • Adding a game manager
  • Shifting and merging the tiles
  • Win condition

Duration:hour of video training

Access now: Create 2048 in Unity

Sliding Puzzle Game 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:

  • Setting up the project
  • Game objects and sprites
  • Player movement
  • Creating the walls
  • Colliders
  • Obstacles and goal
  • Level logic implementation
  • Animations
  • Win state

Duration: 1 hour of video training

Access now: Sliding Puzzle Game in Unity

Develop a Puzzle Platformer Game – 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:

  • Designing the levels
  • Player controllers
  • Tilemap collisions
  • Adding ladders
  • Collecting keys
  • Unlocking doors
  • Scene transitions
  • Saving and loading

Duration: 2 hours of video training

Access now: Develop a Puzzle Platformer Game – Unity

Make a Game like Candy Crush using Unity and C#

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:

  • Setting up the board
  • Moving the pieces
  • Finding a match
  • Generating bombs
  • Detecting deadlock
  • Scoring system
  • Score bar and goals
  • Level goals
  • End game conditions
  • Animating the sprites
  • Adding icing tiles and chocolate pieces
  • Level selection

Duration: 20.5 hours of video training

Access now: Make a Game like Candy Crush using Unity and C#

Unity 15 Puzzle Tutorial

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:

  • Grid and sprites setup
  • Logic scripting
  • Moving the tiles
  • Shuffling the tiles

Duration: 30 minutes of video training

Access now: Unity 15 Puzzle Tutorial

How to Make Snake in Unity

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:

  • Scene setup
  • Snake movement
  • Placing the food
  • Growing the snake
  • Game over reset

Duration: 45 minutes of video training

Access now: How to Make Snake in Unity

Sudoku Unity Tutorial

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:

  • Creating and populating the grid
  • Difficulty level selection
  • Assigning numbers to the cells
  • Game over screen
  • Timer
  • Pause menu
  • Adding notes to the cells
  • Win popup window
  • Ads integration

Duration: 9 hours of video training

Access now: Sudoku Unity Tutorial

Jigsaw Puzzle – Unreal Engine 4 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:

  • Initial setup in Unreal Engine
  • Controlling each individual piece
  • Creating the jigsaw blueprint
  • Setting up the puzzle screen
  • Clicking and dragging the pieces around the screen
  • Winning logic
  • Reset and progress labels
  • Puzzle selection

Duration: 1.5 hours of video training

Access now: Jigsaw Puzzle – Unreal Engine 4 Tutorial

Make a Puzzle Game in Unreal Engine

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:

  • Project setup
  • Player blueprint
  • Moving the player
  • Creating obstacles
  • Collecting multiple followers
  • Lighting manipulation
  • End goal

Duration: 2 hours of video training

Access now: Make a Puzzle Game in Unreal Engine

Make Your First 2D Grid-based Game from Scratch in Godot

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:

  • Setting up sprites
  • Camera and zoom
  • Making the player
  • Boxes and walls
  • Setting up collisions
  • Win condition
  • UI labels and dialog
  • Testing

Duration: 48 minutes of video training

Access now: Make Your First 2D Grid-based Game from Scratch in Godot

I Made Baba Is You in Unity

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

Summary

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!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Roblox Game Making Tutorials – Complete Guide https://gamedevacademy.org/roblox-game-making-tutorials/ Sat, 14 Jan 2023 08:19:57 +0000 https://gamedevacademy.org/?p=13831 Read more]]> Roblox is an online game platform that has been very popular since its release in 2006, and is largely driven by its enthusiastic community. There are thousands of custom-made games that are open for the public to play in a multiplayer setting, ranging from simulations to battle royales.

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.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Roblox Studio Features

Roblox Studio offers a ton of features to help you in the Roblox game making process including:

  • A large online library of 3D models, textures, images, etc.
  • Use of the Lua programming language to script game logic.
  • Well-documented API information.
  • The ability to instantly publish games online which are immediately ready to be played with friends.

roblox studio editor

Who is this For?

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!

Popular Roblox Games

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.

How to Start with Roblox Studio

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.

roblox create page

Once you’ve logged into Roblox Studio, you should have the program open. Go to the New page and double-click the Baseplate template.

roblox studio template page

The engine should then open up.

roblox studio editor

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.

roblox studio test tab 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.

roblox studio stop playing the game

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!

Roblox Tutorials

Lua Tutorials

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.

Roblox Community Links

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
The Complete Guide to Scratch and Coding for Beginners https://gamedevacademy.org/scratch-tutorial/ Mon, 19 Dec 2022 09:37:07 +0000 https://gamedevacademy.org/?p=19299 Read more]]> Are you or someone you know a first-time coder?

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!

Projects Files

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.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

A Closer Look at Scratch’s Interface

To start this tutorial off, we’ll first explore how to create Scratch projects and explore the interface!

Creating a new Project

First off, head over to the Scratch homepage then click on ‘Create‘:

Scratch homepage interface

This will initiate a new project as seen below:

New project in Scratch

Game Stage

At the top-right corner, we have the game stage where we can see our animation running:

Game stage in Scratch

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:

Fullscreen mode in Scratch

Sprite Properties

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:

Sprite properties panel in Scratch

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:

Adding a sprite in Scratch

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:

Multiple sprites in Scratch

To delete a sprite, just click on the trash bin icon that’s on top of its thumbnail:

Deleting a sprite in Scratch

Changing the Background

Next to the sprites, there’s the backdrop area, where you can select a different background for your animation:

Changing the background in Scratch

Changing our default white background to ‘Room 2‘ (under the ‘Indoors‘ filter), we’d have:

'Room 2' background in Scratch

Block Palette

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:

Block palette in Scratch

Workspace

And finally, to the very center of the screen is the workspace, where we’ll be placing all our code blocks:

Workspace in Scratch

Making our First Code

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

A chick sprite in Scratch

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:

Adding a code block to the workspace in Scratch

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:

Altering the code inside the block in Scratch

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:

Adding events to the code in Scratch

Then, drag the “when green flag clicked” block to the workspace and place it on top of the move block that is already there:

Adding 'when green flag is clicked' event in Scratch

With this, whenever we click on the green flag our character moves 10 steps to its right.

Adding More Blocks

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:

Making the sprite say Hello! in Scratch

Note that the blocks fit together perfectly. We can change both text and duration if we want:

Altering contents of the block command in Scratch

Clicking on the green flag, we see it is working correctly:

Running our code in Scratch

Go on and add the “think Hmm… for 2 seconds” block to our code as well:

Adding more Looks blocks to our code in Scratch

Order of Execution

It’s important to notice how all these commands are always executed in order, from top to bottom:

Order of execution of the commands in Scratch

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’:

Inverting the order of two blocks in the code in Scratch

Remember that if you want to stop the program at any time, you need only press the red icon next to the green flag.

Adding Sounds

Let’s add a sound to our program. Bring the “play sound until done” block from the Sound category to the workspace:

Adding Sound blocks in Scratch

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:

Our first program complete in Scratch

Play the animation one more time to see the whole execution take place.

One Script for Each Sprite

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:

Different sprites have different codes associated to them in Scratch

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!

Algorithms and Flowcharts

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.

What is an Algorithm?

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:

  1. Put a slice of bread into the toaster
  2. Set the toasting level
  3. Lower the lever
  4. Wait until the toast is ready
  5. Safely remove the bread from the toaster

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!

Flowcharts

Algorithms can be visually described by a flowchart. Our toast example above would produce this flowchart here:

Flowchart on how to make a toast

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!

Using Coordinates

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:

Cat sprite located at origin in Scratch

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‘:

'Xy-grid' background in Scratch

This background allows us to see the values of x and y for the entire stage area:

X and y axes in Scratch

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:

Updating the sprite's coordinates in Scratch

Cat Animation Project

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:

Renaming our project in Scratch

For this project, let’s change the background once more to ‘Bedroom 2‘:

'Bedroom 2' background in Scratch

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:

'when green flag clicked' event in Scratch

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

'go to' block in Scratch

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:

Sprite moved to bed in Scratch

Next, we want to move the cat to the drawers next to the bed. Here, we’re going to use the “glide” block instead:

Using a 'glide' block in Scratch

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.

Challenge

Now that we’ve shown you the basic process, try the rest yourself first! Update the coordinates and complete the remaining steps:

  1. Glide the cat to the computer
  2. Glide the cat to the window
  3. Glide the cat onto the carpet

All moves should take 2 seconds each. Don’t worry if you get stuck – we’ll cover the final code next.

Challenge to move the cat to target locations in Scratch

Final Code

The solution to the challenge is as follows.

Let’s add another glide block to our code, and move the cat to the computer:

Moving the sprite to the desk in Scratch

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:

Final code for our cat animation in Scratch

Our code is now complete! Running the code we see that everything goes as expected:

Running our code in Scratch

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/

Cat Animation Flowchart

Finally, let’s check the flowchart for our animation project:

Flowchart of our cat animation Scratch 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.

Conclusion

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!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
How to Connect to an API with Unity – Unity Apps Tutorial https://gamedevacademy.org/how-to-connect-to-an-api-with-unity/ Mon, 19 Dec 2022 01:00:41 +0000 https://gamedevacademy.org/?p=9422 Read more]]> Did you know that Unity is capable of pulling data from the web?

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.

Firework displays app made with Unity

Project Files & Requirements

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.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

The API

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.

Queensland Government data website page

 

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=

CKAN Data API Query examples strings

Setting up the Project

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.

Unity Game screen aspect ratio options

Let’s also change the background color. Select the camera and set the Background to a dark blue – I used the color 32323C.

Unity color wheel with blue chosen

For accessing and converting the data, we’re going to be using an asset called SimpleJSON. You can download it from GitHub here.

Creating the UI

Right click the Hierarchy and select UI > Canvas. Now we can begin with our UI!

Unity UI Canvas object

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.

    • Set the Height to 100
    • Set the Anchor to top-stretch
    • Position this on the top of the canvas like below

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.

Unity Transform Component for Header

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.

    • Set the Sprite to none (makes it a colored rectangle)
    • Set the Anchor to stretch-stretch
    • Set the Offsets to 5, 5, 5, 52.5
      • We’ll be giving everything a padding of 5

Unity input object settings

    • Set the search bar’s color to black with the opacity at half
    • For the placeholder and text…
      • Set the Color to white (half opacity for the placeholder)
      • Set the Font Size to 20
      • Set the Alignment to Middle

Unity text object settings for fireworks app

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.

Unity text component with Horizontal Layout Group added

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.

Unity Button component settings

Now, create a new TextMeshPro – Text object as a child of the button.

    • Set the anchor to be the bounds of the button
    • Set the Font Size to 20
    • For our first button, let’s set the text to Today

Unity text object with Today written

Duplicate the button 3 times for a total of 4 buttons: Today, Week, Month and All.

Unity UI with day selection options

Let’s now work on the list of fireworks. First, create an empty GameObject as the child of FireworkList and call it Container.

    • Set the Anchor to top-stretch
    • Set the Offsets to 5, 0, 5, anything
    • Set the Pivot to 0.5, 1
      • This will allow us to increase the height of the container to clamp to the data easily
    • Finally, add a Vertical Layout Group component
      • Set the Spacing to 5
      • Enable Child Controls Size – Width
      • * Disable Child Force Expand – Height (not seen in image)

Vertical Layout Group and Transform Components in Unity

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:

FireworkList object as seen in Unity Inspector

Create a new button (call it FireworkSegment), like with the others – remove the text child and add a TextMeshPro one (two in this case).

    • Set the Height of the segment to 50

Template for fireworks display app in Unity

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.

Object added to Prefabs folder in Unity

Firework Visuals

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.

FireworkRenderTexture options with Size adjusted

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.

Tags & Layers window in Unity

 

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:

Unity Camera options with setting adjusted

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.

Firework particle setup made with Unity

Last Part of the UI

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

    • Set the Height to 160
    • Set the Color to a dark blue with half opacity

Unity UI Panel object for Firework Display app

Then add two TextMeshPro texts for the info and address, and a Raw Image for the render texture of the fireworks.

Text information for Unity Fireworks Display app

In the Game view, you should be able to see the fireworks on the UI!

App Manager Script

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.

AppManager object in the Unity Hierarchy

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

UI Script

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

AppManager Inspector window within Unity

Let’s connect the filter buttons up to the AppManager script.

Highlighting of the On Click options for Unity buttons

For the SearchSuburb input field, let’s add the OnSearchBySuburb event to On End Edit. This will get the data when we finish typing.

SearchSuburb object added to On End Edit function in Unity

Firework Randomizer

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.

Firework Randomizer Script component in Unity

Conclusion

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.

Full Fireworks Display App made with Unity

Even though we designed it for a portrait display, it can easily work for landscape due to us setting up the right UI anchors.

Widescreen version of fireworks display app made with Unity

Once again, you can download the project files here.

Conclusion

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!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
An Introduction to Animating with Scratch https://gamedevacademy.org/scratch-animation-tutorial/ Tue, 09 Aug 2022 10:28:21 +0000 https://gamedevacademy.org/?p=16480 Read more]]> Coding is one of the most important skills that you can learn to improve your creativity and logical thinking – hence preparing you for a wide range of careers worldwide. However, coding doesn’t have to be all numbers and boredom, and instead, you can do something fun with it: animate.

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.

What is Scratch?

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.

Projects Files

All the contents of this tutorial can be downloaded here

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Animating a Fish Sprite

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:

Green Flag on Top of Game Stage in Scratch

First, drag the ‘when green flag clicked‘ block from the ‘Events‘ category to the workspace:

Adding 'when green flag is clicked' Block to the Code

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.

Adding Bubbles Sound

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:

Changing the Sound to 'Bubbles'

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.

Moving the Fish Around

To move the fish, we use the ‘Motion‘ block that says ‘glide 1 secs to random position‘:

Adding Glide Block to the Code

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:

Moving the Fish Sprite

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.

Repeating the Animation

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:

Adding Forever Block to the Code

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!

Conclusion

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.

]]>
Free Course – Create a Mini Game with Python https://gamedevacademy.org/python-digitrek-game-tutorial/ Wed, 01 Jun 2022 10:49:25 +0000 https://gamedevacademy.org/?p=16388 Read more]]>

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!

Python Turtle Mini-Projects

About

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!

]]>
Free Course – Beginner’s Guide to Python Turtle https://gamedevacademy.org/python-turtle-free-course/ Fri, 08 Apr 2022 01:00:38 +0000 https://gamedevacademy.org/?p=15582 Read more]]>

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

About

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.

]]>
Intro to Python Programming – Python Turtle Tutorial https://gamedevacademy.org/python-turtle-tutorial/ Wed, 16 Feb 2022 01:00:34 +0000 https://gamedevacademy.org/?p=15096 Read more]]> Are you looking to learn coding, only with information that is actually suitable for someone who has never programmed (including kids)?

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.

Project Files

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.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Python Development Environment

About Code Editors & 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:

  • Syntax highlighting (coloring different parts of the code to make it more readable)
  • Auto-complete
  • File management
  • Ability to compile and run code
  • Support for different programming languages

Visual Studio Code

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.

Screenshot of the Python website with Downloads highlighted

Setting up Replit

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.

Screenshot of replit home page with Log In button circled.

The easiest and quickest way would be to log in with your Google account or Facebook, so go ahead and do that.

Login screen for Replit

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.

Replit dashboard with Create button circled

A window will pop up.

  1. Set the Template to Python.
  2. Give your repl a name.
  3. Click the Create Repl button.

Create a repl screen with Python settings selected

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.

  1. First, we have the Files window. Here, we can create and manage the files we need for our project. Right now we have main.py – which is all we need for this tutorial.
  2. In the middle, we have our actual Python script in the center, which is where we’ll be entering all of the code.
  3. On the right, we have the Console. This is where we can see log messages, errors, etc.

Screenshot of empty Python repl on Replit

What is a Turtle?

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.

Star made with Python turtle

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:

  1. Move forwards 50 pixels.
  2. Turn right 90 degrees.
  3. Move forwards 50 pixels.
  4. Turn right 90 degrees.
  5. Move forwards 50 pixels.
  6. Turn right 90 degrees.
  7. Move forwards 50 pixels.

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.

Let’s Begin Coding

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.

Python turtle project going forward for 50 pixels

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.

Right angle created using Python turtle commands

For this example, let’s try and draw a cube. Here’s a diagram showing what we’ll need in order to accomplish that.

  1. Move forwards 50 pixels.
  2. Rotate right 90 degrees.
  3. Repeat three more times until we return to our start position.

Graphical showcase of turtle commands needed to make a square

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!

Screenshot of red cube made with Python turtle

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:

Screenshot of circle created with Python turtle

Turtle Commands

Let’s now look at a few other turtle commands.

  • As well as the forward command, we also have backward which moves the turtle backwards.
  • Same goes for the right command, and we also have left which turns the turtle towards the left.

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

Filled in circle for Python Turtle project

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

Python Turtle project with a smaller blue circle in a bigger red circle

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.

Let’s Make a Project

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.

Project Planning

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.

  1. We’re going to be creating a solar system using Python Turtle.
  2. It will have a black background and different colored planets.
  3. We will develop it using the tools we have learned so far.
  4. This will be an example of how we can use Python to create digital art.

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

Solar system visual design plan for Python turtle project

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?

Pseudo code flowchart for Python turtle solar system project

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.

Creating the Project

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.

  1. Set the turtle’s color to orange.
  2. Call the begin_fill command, since we want the shape to be solid.
  3. Create the circle.
  4. End the fill (end_fill) so that the shape can be finalized and filled in with orange.

Now let’s translate that into Python code:

# draw sun
color("orange")
begin_fill()
circle(60)
end_fill()

Screenshot of sun object made with Python turtle

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.

  1. Turn right 90 degrees.
  2. Move forwards 70 pixels.

Let’s code that now.

# turn and move down
right(90)
forward(70)

Screenshot of Python turtle moving forward from sun but with path on

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)

Screenshot of Python solar system project after penup and pendown commands

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:

  1. Set the color to whatever you wish.
  2. Begin fill.
  3. Draw the circle of your desired radius.
  4. End fill.
color("gray")
begin_fill()
circle(20)
end_fill()

Solar system Python turtle project with first planet drawn

From here, the process is pretty much the same.

  1. Turn right 90 degrees.
  2. Pen up.
  3. Move forwards.
  4. Turn left 90 degrees.
  5. Pen down.
  6. Draw the planet.

Challenge!

Task

As a bit of a challenge, I want you to create 2 more planets with these properties:

  1. red planet with a radius of 40 pixels.
  2. green planet with a radius of 30 pixels.

Here’s what it should look like:

Finished Python turtle solar system with challenge elements

Look away now, and then come back here to find the answer.

Solution

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

Bonus: About Animation Speed

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.

  • 10 is the fastest.
  • 1 is the slowest.
  • 0 is instant.
speed(0)

So if we set the speed to 0, you’ll notice that it’s almost instantly drawn when we press run.

Conclusion

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!

]]>