Explore Free Platformer Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Mon, 17 Apr 2023 08:21:45 +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 Platformer Tutorials – GameDev Academy https://gamedevacademy.org 32 32 How to Create Game Over State in Unity in 10 Minutes https://gamedevacademy.org/unity-game-over-tutorial/ Fri, 21 Apr 2023 01:00:04 +0000 https://gamedevacademy.org/?p=22034 Read more]]>

You can access the full course here: CREATE YOUR FIRST 2D GAME IN UNITY

Game Over – Part 1

In this lesson, we’ll set up the Game Over state for our game. In our game, the Game Over state will happen either when the Player hits an Enemy, or when the Player falls from the level.

The Game Over Function

To implement the Game Over state, we’ll go to the PlayerController script and do the following changes:

  • Add the SceneManagement library at the top of the script
  • Add the GameOver function to the PlayerController script
  • In the GameOver function, use the LoadScene function to reload the current scene
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; // Add me!!

public class PlayerController : MonoBehaviour
{
    // Older code omitted for brevity
    // Called when we get hit by an enemy or if we fall below the level.
    public void GameOver ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

And here’s what the PlayerController script looks like at the moment:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    public Rigidbody2D rig;
    public float jumpForce;
    public SpriteRenderer sr;

    private bool isGrounded;

    void FixedUpdate ()
    {
        float moveInput = Input.GetAxisRaw("Horizontal");
        rig.velocity = new Vector2(moveInput * moveSpeed, rig.velocity.y);

        if(rig.velocity.x > 0)
        {
            sr.flipX = true;
        }
        else if(rig.velocity.x < 0)
        {
            sr.flipX = false;
        }
    }

    void Update ()
    {
    // If we press the jump button and we are grounded, then jump.
        if(Input.GetKeyDown(KeyCode.UpArrow) && isGrounded)
        {
            isGrounded = false;
            rig.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }
    }

    private void OnCollisionEnter2D (Collision2D collision)
    {
        if(collision.GetContact(0).normal == Vector2.up)
        {
            isGrounded = true;
        }
    }

    // Called when we get hit by an enemy or if we fall below the level.
    public void GameOver ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

The Fall Game Over Challenge

As a bit of a challenge, we want you to implement one of the game-over cases yourself. In this challenge, you should make the fall-from-the-level scenario work as a game-over.

One of the ways to do so is to check whether the Player’s vertical position is below some level. Checking could be done in the Update function.

In this lesson, we implemented the Game Over function. In the next lesson, we’ll implement the game-over scenarios.

Game Over – Part 2

In this lesson, we’ll implement the Game Over scenarios.

The Fall Game Over

To make the Game Over happen when the Player falls from the level, we should make the following changes to the Player Controller > Update function:

  • In the Update function, check whether the vertical position of the Player is less than -4
  • If so, call the GameOver function
// Using directives omitted for brevity

public class PlayerController : MonoBehaviour
{
    // Older code omitted for brevity


    void Update ()
    {
    // Older code omitted for brevity


    // If we fall below -4 on the Y, then game over.
    if(transform.position.y < -4)
    {
    GameOver();
    }
}

    // Older code omitted for brevity
}

If you start the game now and jump from the level, in a couple of seconds, the level will reload from the beginning.

game level

game level

Here’s what the PlayerController script looks like now:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    public Rigidbody2D rig;
    public float jumpForce;
    public SpriteRenderer sr;

    private bool isGrounded;

    void FixedUpdate ()
    {
        // Get the horizontal move input.
        float moveInput = Input.GetAxisRaw("Horizontal");

        // Set our velocity.
        rig.velocity = new Vector2(moveInput * moveSpeed, rig.velocity.y);

        // Flip the sprite to face our moving direction.
        if(rig.velocity.x > 0)
        {
            sr.flipX = true;
        }
        else if(rig.velocity.x < 0)
        {
            sr.flipX = false;
        }
    }

    void Update ()
    {
        // If we press the jump button and we are grounded, then jump.
        if(Input.GetKeyDown(KeyCode.UpArrow) && isGrounded)
        {
            isGrounded = false;
            rig.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }

        // If we fall below -4 on the Y, then game over.
        if(transform.position.y < -4)
        {
            GameOver();
        }
    }

    private void OnCollisionEnter2D (Collision2D collision)
    {
        if(collision.GetContact(0).normal == Vector2.up)
        {
            isGrounded = true;
        }
    }

    // Called when we get hit by an enemy or if we fall below the level.
    public void GameOver ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

The Enemy Hit Game Over

We should also go to the Game Over state once the Player hits an Enemy. We’ll do this from the Enemy script.

But first, we need to add a way for an Enemy to know that it hits the Player, and not something else. Here’s what we’ll do:

  • Select the Player game object
  • Go to the Inspector window
  • Set the Tag property at the top of the Inspector window to the Player value

Now our Player is tagged as a Player. Well done!

Player game object

And here’s what we’ll do in the Enemy script:

  • Add the OnTriggerEnter2D function. This function is called when something enters the trigger collider
  • In this function, check whether we have a collision with an object tagged as a Player
  • If so, get the PlayerController component from that object and call the GameOver function on it
// Using directives omitted for brevity
public class Enemy : MonoBehaviour
{
    // Older code omitted for brevity
    private void OnTriggerEnter2D (Collider2D collision)
    {
        // Did the player hit us?
        if(collision.CompareTag("Player"))
        {
            // Trigger the game over state on the player.
            collision.GetComponent<PlayerController>().GameOver();
        }
    }
}

Now, if you jump into an Enemy, the game will reload as well. Here’s what the full Enemy script looks like:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float moveSpeed;
    public Vector3 moveOffset;
    private Vector3 startPos;
    private Vector3 targetPos;
    // Start is called before the first frame update
    void Start()
    {
        startPos = transform.position;
        targetPos = startPos;
    }
    // Update is called once per frame
    void Update()
    {
        // Move towards the target position.
        transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
        // Are we at the target position?
        if(transform.position == targetPos)
        {
            // Is our target pos our start pos? If so, set it to be the other one.
            if(targetPos == startPos)
            {
                targetPos = startPos + moveOffset;
            }
            // Otherwise, do the opposite.
            else
            {
                targetPos = startPos;
            }
        }
    }
    private void OnDrawGizmos()
    {
        Vector3 from;
        Vector3 to;
        if (Application.isPlaying)
        {
            from = startPos;
        }
        else
        {
            from = transform.position;
        }
        
        to = from + moveOffset;
        
        Gizmos.color = Color.red;
        Gizmos.DrawLine(from, to);
        Gizmos.DrawWireSphere(to, 0.2f);
        Gizmos.DrawWireSphere(from, 0.2f);
    }
    private void OnTriggerEnter2D (Collider2D collision)
    {
        // Did the player hit us?
        if(collision.CompareTag("Player"))
        {
            // Trigger the game over state on the player.
            collision.GetComponent<PlayerController>().GameOver();
        }
    }
}

In this lesson, we implemented the Game Over scenarios. In the next lesson, we’ll work on the collectible Coins.

BUILD GAMES

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

Transcript – Game Over – Part 1

Welcome back everyone. In this lesson we are going to be working on setting up our game overstate for our 2D platform here.

So the way the game over state is gonna work is pretty much whenever our player gets hit by an enemy or if they fall off the edge and down below our level, they are going to basically reset, okay?

The level is gonna restart and the player will spawn back up here. Okay, so how do we do this? Well, let’s go over and open up our player controller script right here.

Now inside of the player controller script, we are gonna go down and create a brand new function. And this function is gonna be a public void called GameOver. Okay? Like so.

Now the reason we are making this function a public function is because we need to be able to call this from outside of the script. For example, our enemy script here is going to be able to call that function.

So in order to do that, we need to make it public. Now, inside of this function, what we are going to do is basically reload our current scene.

So in order to do that, we first of all need to tell the script that we want to be able to access Unity’s scene manager. And to do that we need to go to the top and you’ll see here we have these three lines of code, okay?

They’re basically using, and then we have a library here. Now, the way code and C Sharp especially works is that you don’t have everything at your disposal right at the start, okay?

So for certain things you may need to access a library. In our case, we are accessing the Unity engine library which allows us to access things such as mono behavior, rigid body, sprite renderer, the fixed update function, the update function, okay?

These are all things that are built into the Unity engine itself. Now, the Unity engine doesn’t always give us everything we need since there are a lot of different code libraries that we can access.

So if we wanna get specific, we do need to actually add them here. So for example, in order to access our scene manager, we need to be using the scene management library.

Now to do that, we can go to a new line here and just go using Unity engine dot scene management like so, and now we have access to our scene manager. So let’s go back down to our GameOver function.

And inside of here what we are going to do is go scene manager dot load scene, okay? And this function right here, basically we need to give it either a scene name, so we can just go level one like so, which is the name of our scene, or we can give it a build index.

And our build index for level one is zero. Basically, the levels go 0, 1, 2, 3, 4, 5, et cetera. But what if we’re on level five, for example? We don’t wanna have to hardcode every single level we have.

So, instead what we can do is we can just get whatever our current scene is and reload that. So to do this, I’m gonna go SceneManager dot GetActiveScene.

Now this is a function call, so make sure to add the two empty brackets like so, and then dot buildIndex. So this here is basically getting the index for the current scene and loading that.

So this line of code essentially reloads our current scene. So we have our game over function, but at the moment it’s not hooked up to anything just yet. So if we were to play our game, nothing would happen.

So in order to make something happen, we are first of all gonna make it so that if our player is jumping along the level here and they fall off the platform we don’t want them to keep on falling down forever.

Let’s say once they reach below, we’ll say below negative four, okay? Once they go below negative four on the Y axis that is when we will basically call the game over function.

So to do this, we are gonna go up to our update function right here. And as a bit of a challenge, I want you to have a go at implementing this.

Here’s a hint. Basically, we are gonna have an if statement that checks to see if our Y position is below negative three or negative four, I’m pretty sure we said, and if that’s the case call the game over function. So have a go at that and I’ll be right back to see how you’re done.

Transcript – Game Over – Part 2

Pretty much what we want to do is inside of our PlayerController’s update function we want to check every single frame if our player’s y position is below a certain number.

So what we’re gonna do is we’re gonna create an IF statement here. We’re gonna go, if transform.position.y is less than, let’s just say negative four then what we are going to do is we are going to call the GameOver function like so, okay?

So that is what we need to do here and make sure it is inside of the update function since we do want to check this every single frame. So we can save that, we can then go back inside of Unity now.

And if we press play, we should be able to test this out. So let us go over to the side right here and jump off the edge. And as you can see, once we go below negative four our scene basically gets to reset.

So we are back at the start and there we go. Now one more thing and that is our enemy. As you can see right now our enemy is just passing directly through us.

So we need a way of making it so that when the enemy hits us the GameOver function gets called. So how do we do that? Well, let us go over to our enemy script right here, and inside of the enemy script we need to create ourselves a brand new function.

Now this is going to be the OnTriggerEenter2D function. So we’re gonna go void OnTriggerEenter2D. Now OnTriggerEenter works very similar to OnCollisionEnter yet they both differ in a certain way.

Collision is basically a solid hit, so you can think of when our player lands on the ground their feet are being planted on the ground’s collider, whereas a trigger is passing through something, okay?

So maybe you might want to have some sort of trigger when a player walks through a door that would be a trigger, okay? The player isn’t blocked, they can pass through it, yet we can detect when that pass through happens.

And that is what a trigger is. So what we need to do is we basically need to make it so that when the player is hit by the enemy we call the GameOver function. But how do we do that?

Well, we’ve got the function here that detects when a trigger has happened, but how do we know if it was a player or not? How do we know that what the enemy hit is a player and not a wall, or a coin, or another enemy?

Well, the way we can do this is by checking to see what the player’s tag is. And before we continue writing code, let’s go back inside a Unity and we need to give our player a tag.

So I’m gonna select our player here and if we go over to the inspector, you’ll see underneath their name they have this little tag dropdown. Now tag is basically a label that we can attach to a game object.

So I’m gonna click on where it says untagged and you’ll see there are a few preset ones here. We can click add tag to add a new one. But we’ve got player, sorry, I’m just gonna select that.

And now our player game object is tagged as player. And you can of course, create tags for other things as well if that’s needed.

But we’re just gonna tag our player for now. So back inside of our script, what we’re gonna do is we are going to check to see if the collision.CompareTag is Player. So the parameter here is collision.

This is basically going to be our player’s collider when the enemy hits us and we are checking to see if that game object’s tag is player, and if so then the condition is true and we can call the GameOver function.

Now, in order to call the players GameOver function, we need to access their player controller component. So to access another game objects component or get any component in general, we need to do a certain function call.

So I’m gonna go collision.GetComponent, and then inside of these two angled brackets we need to define the type of component we are searching for which is gonna be PlayerController, and then two empty brackets like so.

And then we can go .GameOver. Whoops, not GameObject, GameOver, like so. So basically what we have done here is we have accessed the collision component that we have hit.

In this case it will be the player after we do this IF statement. Then we are getting another component on that GameObject we are searching for the PlayerController and then we are calling the GameOver function on the PlayerController.

So we can save that, go back inside of Unity and let’s test it out to see if it works. So I’m going to press play right here and if we jump up into our enemy, we should see that when it hits us the scene gets reset and we can even jump into the enemy here to make sure it works.

There we go. So we’re able to reset the scene by having our enemy run into us. So we need to avoid them on this jump here. And if we jump off our level and fall down below that will also reset the level as well.

So yeah, that is a look at our GameOver state inside of Unity. Now, in the next lesson, we are gonna be looking at setting up our coins, okay? These are basically going to be the collectibles that our player will collect and that will increase their score over time. So thanks for watching, and I’ll see you then in the next lesson.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
How to Create Your First Player Character in Godot https://gamedevacademy.org/player-character-godot-tutorial/ Thu, 06 Apr 2023 09:14:51 +0000 https://gamedevacademy.org/?p=19693 Read more]]> Every game has its unique, core mechanics, but one thing they all share in common is the player character.

Whether first-person or third-person, designing the movement and behavior of the player is one of the first processes that we need to go through when creating games. This is important as it’s what characterizes how the players are expected to interact with the objects and obstacles of the game. Thus, knowing how to create players is a core skill for game development that cannot be skipped!

In this tutorial, we’ll cover the creation of a player character in Godot from the start – ranging from how to create the player node and add it to the game scene to how to configure the player’s sprite and set up the properties of its collider component.

All that said, let’s dive in!

Project Files

You can download a copy of the final source code files for the project done in this tutorial here.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Creating the Player Sprite

Importing assets

After having created a new project in Godot, you first have to download the project assets available here to your computer.

Next, select and right-click the root folder in FileSystem, then go to ‘Open in File Manager‘:

Right-click on the root folder of the project in Godot and go to Open in File Manager option

This will open up a window with the files of our project. Now, with another window open with the assets you’ve downloaded from the link above, drag and drop the Sprites folder into the project folder:

Drag and drop the assets into the project folder

Or simply copy and paste them over so that they appear amongst the files of our project:

Importing assets to our project in Godot

Creating a Node to be our Player

To create our player, let’s click on ‘Scene’ and then ‘New Scene‘:

Click on Scene then 'New scene' to create our player in Godot

Select the ‘Other Node‘ option and search for “KinematicBody2D” in the ‘Create New Node’ window:

Search for KinematicBody2D when creating a new scene in Godot

Choose the ‘KinematicBody2D’ node and hit ‘Create’. The new node is now visible in the Scene window. Rename it to ‘Player‘ by double-clicking on it:

Rename the scene to Player

Adding a Sprite to the Player Node

Following, double-click the Sprites folder in the FileSystem to open it. Select the ‘Player_Idle‘ file and drag it into the viewport:

Drag the Player_Idle image to the viewport in Godot

This creates a new node as a child of the Player node:

Player_Idle is now a child node of the Player scene

In the inspector, go to Transform then click on ‘Position’. Set both x and y to 0:

Setting the position of the sprite to be the origin

The sprite is now centered in the origin (0, 0). Hit Ctrl+S to save the scene:

Sprite in origin position in Godot

Let’s also rename the sprite from ‘Player_Idle’ to ‘Sprite‘.

Adding a Collider to our Player

You’ll note that we’re having a node configuration warning next to our Player scene icon. It says that we need to add a collision child to define the shape of our KinematicBody node. To do that, right-click on the Player, and go ‘Add Child Node‘:

Adding a child node to our Player scene in Godot

Double-click on ‘CollisionShape2D‘ to create it:

Double-click on CollisionShape2D to create a new collision node

Go to Inspector and click on the arrow next to ‘Shape‘. Then select ‘New RectangleShape2D‘ as follows:

Setting up the collider node in Godot

To change the size of the collider, drag the red dots around to adjust the size so that it aligns with the whole sprite:

Adjusting the size of the collider shape in GodotCollider shape correctly adjusted to include the whole sprite size in Godot

Bringing the Player to the MainScene

At last, click on ‘MainScene‘. Go to FileSystem and drag the ‘Player.tscn‘ into the main scene:

Drag the Player.tscn into the main scene in Godot

Save the scene and click on the ‘Play‘ button:

Click on Play to run our scene in Godot

You’ll see that our player shows up in the game window:

Running our player scene in Godot

Scripting our Player in Godot

Let us now start scripting our player sprite.

Go to Project then click on ‘Project Settings…‘, and go over to the Input Map tab:

Project settings menu in Godot

Creating New Actions

We can create new actions for our sprite by adding in some new keys.

Write ‘move_left‘, ‘move_right‘ and ‘jump‘ then click on ‘Add‘ after each addition to include them to the list:

Adding action keys in Godot

We now need to assign each action a unique key. Simply click on the ‘+‘ button next to each action and press the relevant key on your keyboard:

Assigning a key to the added actions in Godot

In this tutorial, we’re going to use the left and right keys to move to the left and to the right, and the up key to jump. After confirming your choices, you can close the project settings window.

With the Player node selected, go to the Script tab in the Inspector panel. Expand it and click on ‘[empty]’. Then select ‘New Script‘ in the dropdown:

Creating a new script for our Player node in Godot

Hit the ‘Create‘ button:

Creating a new script in Godot

This will automatically open up a Scripting Interface as follows:

Script interface in Godot

Declaring Variables

A variable is basically a container that can hold data. The value may change depending on conditions or on commands passed to the program. To create our first variable, type ‘var‘ and then enter a variable name. After that, we can give it an initial value of zero by entering ‘ = 0‘:

extends KinematicBody2D

var score = 0

So now the score variable has a data type of int. You can also add a type hint with a colon (:) after the name to keep it as an integer, which is a whole number:

extends KinematicBody2D

var score : int = 0

You can also set a different data type, such as Vector2 or Sprite. Vector2 holds two numeric values that represent the x, and y coordinates of a point:

extends KinematicBody2D

var score : int = 0

var speed : int = 200
var jumpForce : int = 600
var gravity : int = 800

var vel : Vector2 = Vector2()

var sprite : Sprite = $Sprite

Note that the dollar sign ($) operator is used in front of Sprite. This basically tells the script to look through all of the children nodes and find the node of whatever type is defined after the $, which is Sprite in this case.

The alternate syntax to the dollar sign ($) operator is to use the get_node function. Simply replace $Sprite with get_node(“Sprite”):

var sprite : Sprite = get_node("Sprite")

We can also add a keyword called ‘onready‘ before ‘var’ to make sure the asset is ready when the scene loads:

onready var sprite : Sprite = get_node("Sprite")

This delays the initialization of the variable until the node of Sprite is found.

Moving the Player

Next, we will implement the ability for the player to move around and jump. First, we need to apply gravity. This is going to be done inside of a function called _physics_process():

func _physics_process(delta):

This is a built-in function of Godot, which gets called 60 times a second to process physics. First, we want to set out velocity on the x value to 0 as follows:

func _physics_process(delta):

  vel.x = 0

Then we will check our movement inputs, that is, if the Input system detects ‘move_left’ action:

func _physics_process(delta):

  vel.x = 0

  #movement inputs
  if Input.is_action_pressed("move_left"):

Our velocity on the x should be equal to negative ‘speed’ when we press the “move_left” button, and positive ‘speed’ when we press “move_right”:

func _physics_process(delta):

  vel.x = 0

  #movement inputs
  if Input.is_action_pressed("move_left"):
     vel.x -= speed
  if Input.is_action_pressed("move_right"):
     vel.x += speed

When moving a KinematicBody2D, you should not set its position property directly. Rather you should use the move_and_collide() or move_and_slide() methods. (*Note that these methods should be used within the _physics_process() callback.)

The move_and_slide() method moves the body along a given vector, and if the body collides with another, it will slide along the other body. This is especially useful in platformers or top-down games.

To use the move_and_slide(), we need first to send over the velocity and the direction in which the floor is pointing. Since the ground will be below us, this would be Vector2.Up:

func _physics_process(delta):

  vel.x = 0

  #movement inputs
  if Input.is_action_pressed("move_left"):
     vel.x -= speed
  if Input.is_action_pressed("move_right"):
     vel.x += speed

  #applying the velocity
  move_and_slide(vel, Vector2.UP)

Flipping the Sprite

Now, we can assign it to our velocity and check which direction our player sprite should be facing:

func _physics_process(delta):

  vel.x = 0

  #movement inputs
  if Input.is_action_pressed("move_left"):
     vel.x -= speed
  if Input.is_action_pressed("move_right"):
     vel.x += speed

  #applying the velocity
  vel = move_and_slide(vel, Vector2.UP)

  #sprite direction
  if vel.x < 0:
     sprite.flip_h = true
  elif vel.x > 0:
     sprite.flip_h = false

Save the script and press Play:

Moving the sprite to the right in GodotMoving the sprite to the left in Godot

You can now move the Player horizontally with arrow keys. The sprite will flip as the moving direction changes.

Applying Gravity

To implement gravity is pretty straightforward, we can simply add it directly onto our y velocity:

func _physics_process(delta):

  vel.x = 0

  #movement inputs
  if Input.is_action_pressed("move_left"):
     vel.x -= speed
  if Input.is_action_pressed("move_right"):
     vel.x += speed

  #applying the velocity
  vel = move_and_slide(vel, Vector2.UP)

  #gravity
  vel.y += gravity * delta

  #sprite direction
  if vel.x < 0:
     sprite.flip_h = true
  elif vel.x > 0:
     sprite.flip_h = false

When you add/subtract from the velocity, it needs to be multiplied by delta so that it accelerates at the correct speed:

#gravity

vel.y += gravity * delta

Jump Input

We need to check if the ‘jump’ key is detected, and we also need to check if the player is on the floor:

#jump input
if Input.is_action_just_pressed("jump") and is_on_floor():

We then want to apply the jump force in the opposite direction of gravity:

#jump input
if Input.is_action_just_pressed("jump") and is_on_floor():
  vel.y -= jumpForce

Make sure you have saved the script:

extends KinematicBody2D 
 
var score : int = 0 
 
var speed : int = 200 
var jumpForce : int = 600 
var gravity : int = 800 
 
var vel : Vector2 = Vector2()
 
onready var sprite : Sprite = get_node("Sprite")

func _physics_process(delta):
  
  vel.x = 0
  
  #movement inputs
  if Input.is_action_pressed("move_left"):
    vel.x -= speed
  if Input.is_action_pressed("move_right"):
    vel.x += speed
  
  #applying the velocity
  vel = move_and_slide(vel, Vector2.UP)
  
  #gravity
  vel.y += gravity * delta
  
  #jump input
  if Input.is_action_just_pressed("jump") and is_on_floor():
    vel.y -= jumpForce
    
  #sprite direction
  if vel.x < 0:
    sprite.flip_h = true
  elif vel.x > 0:
    sprite.flip_h = false

* Note that if you press the play button now, the character will simply fall. That happens because there’s no ground for the player to interact with, as we’re not implementing it in this tutorial. You can think of this as a challenge for yourself!

Conclusion

Well done on completing this tutorial on how to create a player with Godot!

Although there’s much to expand here, you’ve already learned how to script your player in Godot and how to set up the player’s sprite and kinematic properties so it behaves as desired! You can now move on to coming up with your game’s level style and structure, besides some enemy logic or coin collection to make your game exciting.

Godot is also a great choice for beginners – as its node-based user interface makes it easy to create games while also facilitating access and project organization. Plus, the engine is open source and has a strong community backing the project, so there are constant updates and new features being released all the time.

We wish you all the best of luck with your game projects, and that you continue learning more each day!

Further Resources

Would you like to see more on Godot? Check out our recommendations to help you on your journey below:

Want to learn more about developing in Godot? Try our complete Godot 3 Game Development for Beginners course.

BUILD GAMES

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

]]>
Best Platformer Tutorials – Master a Game Dev Staple https://gamedevacademy.org/best-platformer-tutorials/ Wed, 25 Jan 2023 08:46:02 +0000 https://gamedevacademy.org/?p=15567 Read more]]> Out of the many different genres and subgenres within the world of videogames, platformers are perhaps the best known and most iconic. Made popular by classics like the Super Mario series and recently revitalized by the booming indie development industry, platformers are a staple of the videogame landscape – so it makes sense that aspiring game developers often want to try and make their own. Platformers are also an ideal entry point for new developers thanks to their simple premise.

To help out new developers on their path to creating their very own platformer games, we’ve compiled a list of some of the best platformer tutorials available online. Using these, you’ll build up all the skills you need to create fun and exciting platformers to add to your portfolio!

Why Should You Learn To Make A Platformer?

Platformers are one of the most iconic genres in the history of videogames. Iconic series like Mario, Sonic and Crash Bandicoot are probably some of the first games that someone would think of if you asked them to name a videogame. 

They also happen to be one of the simplest types of game to make for beginners. In terms of level design, it’s as simple as creating a journey from point A to point B with some obstacles for players to overcome on their way. This format makes for an ideal proving ground for beginner game devs to get to grips with fundamental coding skills and core aspects of game design.

Platformers also offer the chance to try out a variety of different formats and subgenres. Platformers can be set in 2D, 3D or even virtual reality environments, and can cross over with other genres like puzzlers, action games and RPGs for even more variety.

Essentially, platformers are a great starting point no matter where you eventually see your game development journey heading. Their simplicity makes them great for practicing your game design skills and using them as a foundation to experiment with new mechanics. 

They also offer plenty of opportunities for imaginative and innovative new challenges for players, so more experienced game developers can find platformer design a rewarding challenge too.

Learn To Make A Platformer

We’ve put together a list of some of the best platformer game tutorials currently available online in order to help you on your way to becoming a platformer expert. These tutorials provide detailed instructions on every stage of creating a platformer, from player movement and level design to more complex systems like enemies and powerups.

The majority of these tutorials are designed specifically for beginners, so even if you don’t have much prior experience with platformers or game development in general, don’t worry – you should be able to easily follow along with these accessible tutorials!

Create Your First 2D Game In Unity

If you’re a beginner game dev with some knowledge of Unity and C# looking for your very first game project to get sucked into, this tutorial from Zenva Academy is the ideal starting point. The Create Your First 2D Game In Unity tutorial helps you to build a 2D platformer to add your first completed project to your soon-to-be-growing portfolio.

It covers everything you’ll need to learn to start making platformer games including player character setup, collectibles, enemies, level design and more. The tutorial is laid out as a series of videos giving step-by-step instructions for implementing the key elements of a platformer, so it’s extremely easy for beginners to follow along with.

By taking on your first proper game project, you’ll also learn a variety of transferable game design skills that will be essential in taking on future projects regardless of genre.

Key Topics Covered:

  • Implementing player and enemy objects
  • Scripting platformer-style movements
  • Building levels with 2D tiles
  • Setting up collectibles and scoring
  • Controlling gameplay flow with goals
  • Creating UIs for scores and menus

Duration: Just under 2 hours of video tutorials split across key elements of 2D platformers.

Build a 2D Platformer Game in Unity

Another great place to start if you’d like to build your first 2D platformer game is the Build a 2D Platformer Game in Unity tutorial series from Coding in Flow. This series of video tutorials shows you how to code a simple 2D platformer from the ground up in Unity, complete with collectibles, obstacles, moving platforms and more.

Since it’s designed for absolute beginners with no prior programming experience, it’s extremely easy to follow the instructions and build your first platformer in Unity. Along the way, you’ll pick up some core skills for coding in C# and working with Unity, which will help you to tackle more complex projects in the future.

Key Topics Covered: 

  • Tilemaps and tile palettes
  • Player movement and animation
  • Grounding checks using boxcast
  • Collectible items and item counters
  • Static and moving obstacles
  • Adding sound effects and background music 
  • Adding multiple levels
  • Menus for the start and game over screens

Duration: Around 4 hours, 30 minutes of video tutorials covering each step of creating a platformer in Unity.

Create Your First 3D Game In Unity

If you’re more interested in working in 3D game environments than 2D ones, then this alternative Zenva course is a great option for creating your first 3D platformer and learning some foundational 3D game design skills.

Similar to the 2D platformer course, the Create Your First 3D Game In Unity tutorial provides you with a series of videos containing step-by-step instructions for building your own 3D platformer from the ground up. You’ll learn how to set up a player character, create a series of levels, program enemies, and more.

As with the 2D tutorial, the process of creating your first 3D platformer will help you to learn some essential game design, C# and Unity skills that will be highly useful in any future project. All you need to get started is a basic knowledge of Unity and C# – the tutorial’s detailed instructions will guide you through the rest.

Key Topics Covered: 

  • Creating player and enemy objects
  • Constructing a level with 3D models
  • Scripting the camera to follow the player
  • Setting up game over and win conditions
  • Adding collectible coins
  • Building UI elements and menus

Duration: Roughly 2 hours, 20 minutes of video tutorials split across different elements of the 3D platformer.

Unity 3D Platformer – Learn To Make A 3D Action Platformer!

Another option for aspiring game developers who are more interested in 3D games than 2D ones is the “Unity 3D Platformer – Learn To Make A 3D Action Platformer!” series from gamesplusjames. It’s a perfect place to start for Unity beginners, and even includes an introductory session looking at some of the very basics of working with 3D environments in Unity for those who haven’t used the platform before.

The series covers everything you’ll need to know to craft a 3D action platformer of your own, including player movement, camera controls, collectible items, power-up effects, knockback and more. By the end of the series you’ll be able to create your own 3D platformer in Unity and use the skills you’ve picked up to work on a variety of 3D Unity projects in the future.

Key Topics Covered: 

  • Basic concepts for manipulating 3D environments in Unity
  • Player movement and animation
  • Camera controls 
  • Collectible items
  • Power-up effects such as invincibility
  • Health systems
  • Knockback
  • Respawning after a death
  • Respawn effects

Duration: Roughly 6 hours, 20 minutes of video tutorials covering each stage of building a 3D platformer in Unity

VR Projects – Third-Person Platformer Game

If you’ve built a few platformers already and you’re looking for a new challenge to expand your skillset, then the VR Projects – Third-Person Platformer Game tutorial is an excellent next step. The tutorial teaches you how to adapt an existing 3D platformer into VR using Unity, providing you with an opportunity to move into an exciting new game environment.

This involves a number of challenges like modifying game screens to make them suitable for VR and re-mapping buttons in an external gamepad. By the end of the tutorial, you’ll have successfully adapted a 3D platformer into a VR game, expanding your portfolio with an exciting and interesting new project .

You’ll need some familiarity with Unity, C# and the Unity VR Standard Assets package before taking on the tutorial, but as long as you have this existing knowledge, the detailed instructions will make it simple to follow along and complete your first VR project.

Key Topics Covered: 

  • Adapting an existing 3D platformer game to VR
  • Adaptation of UI screens and HUD
  • Changes to the platformer mechanics and “cursor key” type of movement
  • Mapping buttons for the Xbox 360 controller and other gamepads
  • Manually triggering events in the VR Input class so that we can utilize it with any external device, future-proofing your game and your new skills

Duration: Roughly 50 minutes of video tutorials laying out each stage of adapting your 3D platformer for VR.

Godot 3 2D Platform Game

If Unity isn’t your engine of choice, there are still plenty of other platformer tutorials out there for alternative game engines. For example, if you’re more familiar with the open-source, indie-focused Godot engine, then you could try the Godot 3 2D Platform Game series from HeartBeast.

This tutorial miniseries is an ideal starting point for aspiring devs who have some familiarity with Godot and want to make their first real project with it. The series covers a variety of essential platformer development topics like tiles and sprites, character movement, level transitions and more.

It also includes a segment in the introduction that shows you exactly how to set up the project, so if you’re still finding your feet with Godot, this is a very accessible entry point regardless of your prior experience.

Key Topics Covered: 

  • Setting up a 2D platformer project in Godot
  • Tilemaps and animated sprites
  • Character movement and control
  • Level transitions
  • Autotiling
  • Parallax backgrounds 
  • Designing a UI and menus

Duration: About 2 hours, 15 minutes of video tutorials on different stages of creating a 2D platformer with Godot.

Develop A Puzzle Platformer Game

If you have slightly more experience with game development and you want to take on a project that introduces additional game elements to increase the challenge, then why not give Develop A Puzzle Platformer Game a try?

This tutorial is another Unity-based project that tasks you with creating a simple platformer, then adding new elements like keys, locked doors and more varied obstacles to introduce some light puzzling to the mix.

It’s a great way to further practice your platformer development skills while also learning new gameplay mechanics and exploring how platformers can be blended with other genres for more varied gameplay experiences.

It’s recommended that you have intermediate C# skills and some familiarity with Unity if you take on this tutorial, so it’s aimed at slightly more experienced coders rather than absolute beginners. However, the detailed instructions in each stage of the tutorial make it super easy to follow along, making it a very accessible course despite the slightly higher entry requirements.

Key Topics Covered:

  • Setup player controllers (walking, jumping, collecting items, etc.)
  • Utilizing Tilemaps and Tilemap collisions to create interesting levels
  • Implementing hazards, ladders, keys, and more to encourage player exploration
  • Developing a system to unlock doors based on colored keys
  • Managing saving, loading, and scene transitions for a connected gameplay experience
  • Making a UI system to record a player’s number of keys and more

Duration: Roughly 2 hours, 20 minutes of video tutorials split across the various elements of the puzzle-platformer project.

Conclusion

Given both the simplicity and the iconic status of the platformer genre, it provides a natural starting point for anyone looking to use their coding skills to move into game development. Using the tutorials above, you’ll be able to gain all the skills and knowledge you need to quickly start making platformers of your own, making your own mark on this iconic genre and expanding your portfolio at the same time!

Of course, there is a lot more to the platformer genre, as you can even incorporate action gameplay as a core feature. So don’t stop exploring your options, and we can’t wait to see the games you make.

BUILD GAMES

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

]]>
Best Unity Visual Scripting Tutorials – Making a Game https://gamedevacademy.org/best-unity-visual-scripting-tutorials/ Sun, 22 Jan 2023 08:06:11 +0000 https://gamedevacademy.org/?p=15377 Read more]]> Coding from scratch is hard, and frankly, just not for everyone. However, this should not stop you from making the games of your dreams!

This is where we come to the topic of visual scripting. As the name suggests, visual scripting allows you to add game functionalities visually in various ways – usually without the necessity to code at all. As such, as long as you know how to structure an algorithm, you can build just about any kind of game you might want. Many visual scripting tools also have full access to their engine’s API, so you don’t have to worry about missing out on useful engine tools either.

In this article, we’re going to take a look at some of the best visual scripting tutorials for Unity. Not only will these tutorials help you get started with visual scripting in general, but also show you how to tackle specific projects with it.

If you’re ready to start building games without code, let’s get on with it.

About Visual Scripting and Unity

Just as a brief pause for complete newbies out there, we want to talk about the topic of visual scripting itself and how it presents in Unity. This way, if you’ve never used visual scripting or Unity before, you won’t be lost.

What is Visual Scripting?

As described above, visual scripting is all about “programming” visually. In the case of Unity, this is presented in the form of draggable blocks or nodes that can be added to a canvas/graph. Each node/block has a specific functionality tied to it, such as adjusting an object’s transform, changing variable values, and so forth. By attaching this functionality to an object, you can apply those functions to the object via the block, instead of needing to code it by scratch.

Additionally, and what makes visual scripting powerful, is that you can easily connect blocks together. Say for a character “dying” you want to deduct one life from them and move them to a designated starting position from them. In this case, you’d simply take a block that is set to subtract the life score and connect it to a block that moves the character’s position. Then, you simply trigger this sequence when the character dies – no coding required at all.

Visual Scripting in Unity

When it comes to the popular engine Unity, there are two ways in which we can utilize visual scripting. Note that while accessing the visual scripting tool is different, both still can utilize the same tutorials with some minor differences. As such, you don’t need to get too hung up on which tutorial applies to you.

Unity Bolt

Bolt is a Unity-developed package you can download for any Unity project on version 2018.4.15 or later – up until version 2021.1. This asset gives you a simple graph to work with that comes with visual scripting capabilities. Until recently, this has been long-established as the primary way to use visual scripting in Unity, and is tried and tested through the years.

Unity 2021.1 and Later

Given the success of Bolt, since Unity 2021.1, Unity has packaged visual scripting with the editor by default. While there have been some minor bug fixes and improvements, it operates much the same as Bolt does. However, because it’s bundled with the editor, there’s nothing extra to download. Thus, this is slated to become the new default standard for games made in Unity now.

Make games without Code? Visual Scripting! (Unity, Bolt)

Duration: 13 minutes

For those brand new to visual scripting and interested in Bolt for older versions of Unity, this beginner’s tutorial by Code Monkey has you covered.

This tutorial first shows you how to get Bolt set up for your project – including some useful settings that may come up during this setup process. You’ll also get some tips on how to use Bolt depending on your interest in C# coding from scratch.

After that, the tutorial covers many useful basics, from adding nodes to your visual scripting canvas, to working with regular coding features such as variables. You’ll even learn how to access Unity components such as the Rigidbody component. Thus, regardless of what you want to work on next, this tutorial will at least get your foot in the door.

LEARN NOW

Unity Visual Scripting Getting Started

Duration: 6 minutes

While the above tutorial covers Bolt, this short tutorial by Dave Carrigg covers visual scripting foundations for Unity versions 2021.1 and later.

The main focus of this tutorial is showing you how to access the built-in visual scripting system that comes with your Unity installation. This includes just the set up process itself, as well as how to add nodes to your graph. You’ll of course also learn a tiny bit about how to connect the various mechanic nodes together.

Though this tutorial is probably used best in combination with the tutorial above (as Bolt isn’t dissimilar for the node process itself), it will definitely get you started with visual scripting – especially if you’re coming from an older version of Unity.

LEARN NOW

How to Make a Game with Unity 2021 Visual Scripting (Bolt)

Duration: 57 minutes

In this Bolt tutorial series by Smart Penguins – GameDev, you’ll move past just getting your visual scripting set up and actually build a functioning game.

The project focus of this series is a simple ski slope like game where the player needs to dodge obstacles as they move forward and collect coins down a predefined, straight path. Through this, you’ll learn several aspects required for almost all games. This includes applying physics, detecting input, setting up levels, managing objects, creating UIs, and more – all with visual scripting, of course.

Though the game probably won’t win you any awards, its simplicity makes it perfect for beginners. Not only do you get to learn how to use visual scripting, but also explore the game development fundamentals needed to make Unity games in general.

LEARN NOW

3D Movement Animation w/ Bolt

Duration: 20 minutes

Created by Playing games faster – Mr. Johnny Roo, this Bolt tutorial focuses exclusively on 3D player movement.

This topic comes with two specific components. Of course, the tutorial absolutely covers visual scripting. So, you will learn how to set up inputs and all around affect your player’s transform properties to simulate movement.

However, the second component of this tutorial is a focus on animation. In general, most developers want there player object’s to animate signs of their movement. For Unity, this is achieved with its Animator system, which allows you to set up animations to be played, when they should play, and how they should transition between each other. This tutorial covers not only this set up for your 3D character, but how to access your animations with a visual scripting set up. Thus, you’ll get to move past primitives and create more dynamic characters.

LEARN NOW

How To Use Bolt State Machines In Unity

Duration: 12 minutes

For those who are interested in how state machines work with visual scripting this tutorial by Dapper Dino is a fantastic resource to get a jump start on them.

State machines, for those who don’t know, are models used to control object behavior. Essentially, with a state machine, you define a particular set of states an object can be in, such as chasing the player vs. idle. With these states, you then add specific behaviors the object should exhibit, and define how those states are triggered. This is useful for everything from Unity’s Animator to enemy AI.

This tutorial covers the basics of setting a state machine up with Bolt. You’ll learn to add nodes for the states themselves, attach the behaviors to them, and even various ways you can trigger your states. This is also covered at a very practical but theoretical level, so its simple to adapt this material to whatever you need your state machine for.

LEARN NOW

Input in Unity Visual Scripting

Duration: 7 minutes

Games are nothing without input, and this tutorial by NotSlot will help you with input via the visual scripting method.

There are various ways through which we can interact with games, from touch mechanics to simple mouse clicks. As such, visual scripting offers you many different nodes for detecting these inputs. This tutorial covers a few sets of those nodes, particularly focusing on keyboard input, mouse clicks, and how you can use them to move characters and similar.

However, this tutorial also makes sure to cover Unity’s old Input Manager, which lets you define your key bindings essentially. Thus, you’ll also gain the knowledge you’ll need to personalize your input setup for your project.

LEARN NOW

Easy Way to Make 2D Games with Unity – Unity Visual Scripting

Duration: 6 minutes

If you’re more into the prospect of making 2D games, or want to have a new game for your portfolio fast, this tutorial by Smart Penguins has you covered.

The idea behind this tutorial is to strip back all the complicated mechanics you might see in other genres and focus mainly on movement, item collection, and obstacles. In the case of this tutorial, you’ll make an arcade-like space shooting game where you can move your ship around, shoot randomly spawning asteroids, and collect the coins that they drop.

While not as focused on visual scripting itself, this simplistic tutorial does serve to help you with game development fundamentals and actually using your visual scripting skills to make complete game projects.

LEARN NOW

Bolt FPS Tutorial

Duration: 36 minutes

Created by 1909Games, this short tutorial playlist will do exactly as it’s titled: show you how to make an FPS using only visual scripting.

The series featured is divided into three parts. In the first part, you’ll learn how to set up your level and player. The second part covers shooting mechanics, and the third part covers making enemies that patrol. The end result is a nifty FPS prototype that didn’t require a shred of manual C# coding.

Though there are many types of games one can learn to make with visual scripting, learning to make FPS games come with a few advantages. First, it teaches you the mechanics of first-person cameras, which come with a lot of quirks and are good to know how to make – regardless of whether you’re using visual scripting or not. Second, it also forces you to learn things such as object spawning, AI, and more – all which are aspects used throughout other genres.

LEARN NOW

Unity Visual Scripting Recommended Practices

Duration: 22 minutes

This tutorial by Gorilla Tactics is a bit unique for tutorials on this list, as this one actually expects you to also want to use C# coding.

Although first impressions may lead you to think that you can ONLY use visual scripting in your project or ONLY use C# scripting, this is false. In fact, because they are completely compatible with each other, you can mix and match visual scripting setups with other aspects you code manually. As such, even if you are a C# coder, you can take advantage some benefits visual scripting can provide.

The video focuses on this exact subject and tries to convey two things about this topic. The first, and less obvious, is the advantages and disadvantages between these two methods of “coding” your game. The second, and more implied by the title, is the best way to combine visual scripting and C# so you’re making clean code and keeping your game running effeciently.

LEARN NOW

Unity Visual Scripting Tutorials

Duration: 1 hour, 20 minutes

This playlist by munchmo is perhaps the best one for those who are looking to dive deep into visual scripting, even with some more intermediate concepts.

In the first part of this series, you’ll simply get a short introduction into the most important nodes, such as On Start, On Update, and so forth. This way, you can jump into the second part of the series understanding some of Unity’s most important triggers.

The second part of the series is where the deep dive begins. You’ll learn a variety of things, from the basics of using visual scripting itself (including subgraphs), to implementing complicated structures for singletons or coroutines. It even covers concepts related to data management. So if you’re ready for some intermediate level stuff, this tutorial will help you take that plunge.

LEARN NOW

How To Make Local Multiplayer Games W/ Unity Visual Scripting + New Input System

Duration: 39 minutes

Last but not least, this tutorial by Megahertzs will teach you how visual scripting works within the confines of Unity’s new Input System.

While there have always been ways to access input data – as was even covered in a tutorial above – Unity’s new Input System takes this to the next level. With this Input System, the idea was to create a level of abstraction between the inputs and the actions in game. In so doing, this would offer developers more freedom in how they mapped their controls – and came with the added bonus that local multiplayer games would be easier to create as well.

As the title probably clued you in, this particular tutorial focuses on the local multiplayer aspect of this Input System in particular. You’ll learn primarily how to set up moveable characters that can be accessed at the same time with different control sets – with, of course, an emphasis on visual scripting to get the job done.

LEARN NOW

Parting Words

We’ve reached the end of our list, and now you have some of the best Unity visual scripting tutorials at your fingertips. While visual scripting is often considered an easier entry point than coding, don’t think there isn’t any hard work involved. However, with visual scripting, you can focus even more so on the exact mechanics you want for your game – and worry less about pesky C# syntax.

Of course, learning how to code in Unity is always an option later – as there are just as many tutorials on that topic. Nevertheless, visual scripting is a great option for those who just aren’t interested in that part. So, find what works best for you in that regard!

Regardless of your choice, we hope you explore even more visual scripting topics, and we wish you the best of luck.

BUILD GAMES

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

]]>
Kaboom.js Tutorials – Complete Guide for Easy Game Dev https://gamedevacademy.org/kaboom-js-tutorials/ Sat, 21 Jan 2023 05:11:59 +0000 https://gamedevacademy.org/?p=14977 Read more]]> Do you want an easy-to-use game framework to build your dream projects?

Kaboom.js is a relative newcomer to the game development scene, but it is already making a big splash – especially among indie creators. This JavaScript-based library was made specifically with games in mind, in the same vein of frameworks such as Phaser or Pixi.js. However, there are many aspects that have made it stand above its competitors and worth your time checking out.

In this article, we’re going to introduce you to Kaboom.js and show you how you can get started learning this new tool.

Let’s get started!

What is Kaboom.js?

As mentioned, Kaboom.js is a JavaScript library in the vein of HTML5 games, which use the browser to render games made with it. The library was made with the idea of simplicity, but comes with many important game development features – such as layering, collision detection, input handling, and more. Regardless, though, the goal is to allow novice developers to create game scenes as quickly as possible.

Game objects in Kaboom.js are conveniently rendered with a component-based system. This means they’re extremely easy to manipulate and apply behaviors too. The behaviors can include everything from simple game mechanics like health to basic movement-based animations – so each game object essentially suits object oriented programming principles.

Beyond this, it is worth noting Kaboom.js is also an available template for Replit – a popular, in-browser coding environment. This means its well-suited for developers who aren’t interested in setting up local development environments or just want to play around with the library.

Key Pros of Kaboom.js

Why should you use Kaboom.js? Below, we’re going to explore what makes Kaboom.js stand out and how, as a developer, you can benefit from the advantages Kaboom.js offers.

Screenshot of the Kaboom.js playground

Fast and lightweight

Unfortunately, not everyone has a computer that can run game engines such as Unity or Unreal Engine – which both are pretty process intensive programs. However, Kaboom.js does not require a great computer and can be used even with low-end laptops. In fact, due to its incorporation with Replit, as mentioned above, you really only need a browser if you’re intent on using it – not even a code editor is required.

Likewise, because of how lightweight it is, games made with Kaboom.js run very smoothly as well. This means you don’t have to get hung up too much on optimization. Instead, your games will likely run quickly right out of the box, leaving you more time to focus on what matters.

No dependencies

Many frameworks and libraries out there require several layers of dependencies to be able to run properly. If you forget the dependency, or more tragically, if the dependency has a breaking change, your game isn’t going to work.

Kaboom.js doesn’t require any sort of dependencies. While you certainly can add packages such as webpack, natively you just need to import the Kaboom.js library itself. Once that is added, you won’t have the extra worry of maintaining the dependencies. This helps Kaboom.js achieve its goal of making it quick to setup and allowing you to dive straight into the fun stuff of actually making the game.

Cross-platform compatible

Since Kaboom.js is specifically for creating browser-based games, this means that there are no platform limitations. If the device can connect to the internet, your players can play it from anywhere.

For you as a developer, this means two things. First, this helps you avoid messy setups of needing multiple game versions just to have it available for multiple platforms. Second, this opens you up for a wider audience since you can tap into different sorts of players. All in all, though, this is a boon that makes it much easier for you to get the game into multiple different hands.

Simplicity

If you’ve ever tried to read documentation for frameworks or libraries before, you’ll know they can get rather complicated. If you don’t believe us, just go check out Unity’s documentation. While certainly this is fine for experienced developers, beginner developers are going to find this a nightmare.

Kaboom.js was designed to eliminate this problem and be as simple as possible. Not only does this help with keeping it lightweight, but makes the documentation much, much easier to understand when you’re just a beginner. This, in turn, just makes development itself easier.

Additionally, it comes with the extra benefit that this documentation can more easily be maintained as the library is updated. This means you won’t be reading old information that was relevant five versions ago.

Specifically made for beginners

As you might have seen from the previous points, beginners were at the heart of the design choices for Kaboom.js. Everything about the library is made to benefit beginners who have never made a game before. While there is a need for JavaScript experience before diving in, this is a much lower point of entry compared to heftier engines.

Thus, you’re only going to need a few tutorials to get the gist of how Kaboom.js works – and soon be able to develop your own projects with it.

Active development

Over the years, many HTML5 frameworks have come and gone. For others that remain, the development can often be slow and new versions, bug fixes, and features are few and far between. While many of these frameworks still technically work, the lack of developer support can eventually become a hindrance.

Kaboom.js, on the other hand, is very actively and caringly developed. Though we don’t expect them to break their principles of simplicity, improvements to the library come frequently. Thus, you can be assured the library will be supported for whatever time it needs for you to build your project.

Screenshot of the Kaboom.js GitHub page

What can you make with Kaboom.js?

Being based on HTML5 (i.e. for the browser), projects made with Kaboom.js do have limitations – as our browsers and internet are only so powerful no matter which JS library we’re talking about. So, you shouldn’t expect to make any kind of AAA game with the library. Kaboom.js was also specifically made for 2D development, so 3D graphics are kind of off the menu as well.

Past these two minor limitations, though, Kaboom.js does not put any further obstacles in your way. You can build small games in just about every genre, and only your imagination is there to hold you back. This includes everything from platformers to adventure games to old-style retro games like Breakout, Super Mario Bros.Space Invaders, and so forth.

If you want to explore the full scope of what people have already made, you can check out Kaboom.js made games below:

Kaboom.js & JavaScript Tutorials

Ready to create games with Kaboom.js? Check out the links of tutorials below which cover Kaboom.js, JavaScript for HTML5 development, and the game development process.

BUILD GAMES

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

]]>
How to Make a Unity Camera Follow a Player – Platformer https://gamedevacademy.org/unity-camera-follow-tutorial/ Mon, 19 Dec 2022 01:00:16 +0000 https://coding.degree/?p=491 Read more]]>

You can access the full course here: Create Your First 3D Game in Unity

Camera Follow Script

The simplest way to make a camera follow an object is to set it as a child. You can click on the camera and drag it into the Player object:

Main Camera in Unity being dragged as child of Player

Now the camera is set as a child of the Player.

Main Camera as child of player in Unity

If we press play, we can see the camera follows our Player.

Demonstration of camera as child of player in Unity

However, the camera not only follows our Player’s position, but it also follows its rotation.

For example, if you are facing right and hit the left key, the camera is also turned 180 degrees, and this is not ideal.

Creating A CameraFollow Script

First, we’re going to unparent the camera from the Player. (Drop it into where the blue line appears above the Player):

MainCamera being moved to top of Unity Hierarchy

And we’re going to create a new script called “CameraFollow” inside Assets/Scripts.

CameraFollow C# script in Unity Assets

We’re going to attach this script to the camera by dragging it into the Inspector.

CameraFollow script added to Main Camera in Unity

We can then double-click the script and open it up in Visual Studio. Here, we’re going to create two new variables:

public Transform target;
public Vecor3 offset;

The target will be used to reference a Transform component to follow, and the offset will be used to maintain a certain distance away from the player.

Inside the Update function, we’re going to update our camera’s position so that it follows the target’s position, but with some offset so that our camera doesn’t sit inside the player.

//Update is called once per frame.
void Update()
{
   transform.position = target.position + offset;
}

Let’s hit save and return to our editor.

Setting Up Camera

Now we’re going to drag in the Player into the Target slot.

Player being added to Camera Follow script's Target

We’re going to set the offset as (0, 2, -3.5):

Camera with offset set in Camera Follow Script

Unity demo of new Camera Follow script

We’re also going to set the x-rotation of our camera to be 20, so we’re looking down slightly on the player.

Unity Inspector with 20 on X Rotation

Demo of Unity with adjusted X rotation

If we hit Play now, you should see that the camera is following our player, while always maintaining the offset (0, 2, -3.5) away from the player’s position.

Demo of final Camera Follow script in Unity

Transcript

Welcome back everyone in this lesson, we are going to be setting up Camera Follow. And this basically means that we have our camera following our player around, so no matter where we go, we can always have our player in the center of our screen.

So here in Unity, what we want to do first of all, is figure out how we’re actually going to do this. Now, first of all, you may think we can just parent the camera to the player. So that whenever it moves, the camera moves as well. Okay well, let’s try that out and see if it works. So I’m gonna get our camera and I’m gonna drag that into the player object as a child. Okay, so the camera is now a child, and if we press play, we should be able to move our player around, right?

Well, let’s try it now. And you’ll see that when we move, our camera rotates as well with our player. And that is not what we want. We don’t want to pretty much be statically attached to our player like this, where you rotate and move with it. We only want to move with our player.

So to unparent an objects, we can select it, click and drag. And if we move it above player, you’ll see there’s this blue line that appears. Okay, we can just let go. And it is now outside of the player.

So, what we need to do is create a new script. Down here on my scripts folder, inside with project browser. I’m gonna right click create a new C# script called Camera Follow. Okay, Camera Follow right there. I’m gonna select the main camera. And I’m gonna drag this script into the Inspector to attach it as a component.

We can then double click on Camera Follow, to open it up inside of the, Visual Studio here. I’m gonna delete the start function since we don’t need, the Start function for this. We only need update and we are gonna be creating two variables. First of all, we need to give this camera a target.

Okay, what object do we want to be following? So I’m gonna to create and a new public, and then we can enter in Transform here. So a Transform component. We can be referencing a Transform component to follow, and I’m just gonna call this variable target. And also we need a another variable, a public Vector three, and this is going to be for the offset.

Now, when we have the camera following the player, we don’t want to be setting the camera’s position to be directly the exact same as the player’s. Because what that will do is make it so that the camera is inside the player. And we of course do not want that. So we need an offset, which is going to be applied to that position, so that we have maintained a certain distance away from the player.

So, down here on update. What we want to do is set our position. So we go, transform dot position, equals our targets position, plus the offset. So here we can go target dot position plus offset. Okay, and that is it. Just one line of code inside the update function. We are setting out position right here to be equal to the targets position plus the offset vector apply to that. Okay. And off of semi-colon save that script or turn to the editor.

And now what we can do is select our main camera. You’ll see down the bottom here in the Inspector, we have a target and an offset property. Target, we can drag in a transform. And offset, we can enter in a new vector, very similar to how we have up here our position, rotation and scale . So for the target, I’m gonna click and drag our player game object into the target property. So now it is referencing our player’s Transform component and fully offset.

Let’s just say the offset is zero on the X. We’ll make it one on the Y and we’ll make it something such as a negative three point five on the Z. So if we go up to our camera here and set it to zero, one, negative three point five, this is more or less what we’re going to be getting. Okay. let’s maybe also add a bit of a rotation to the camera.

So we’re looking down slightly on the player. So I’m gonna to set the X rotation here to be about 15. No, we could probably make that about 20 and I’m gonna set the Y position up to be about a two. So there we go. We can then change that down here in the offset to two. So zero to negative three point five.

If we press play now, you should see that the camera is now following our player. When we move around luxor. Okay, we can jump. We can move. And the camera is always going to maintain this offset away from the player’s position.

So there we go. That is how we can do a quick and easy, Camera Follow script inside of Unity. So thanks for watching and I’ll see you all in the next lesson.

 

Interested in continuing? Check out the full Create Your First 3D Game in Unity course, which is part of our Unity Game Development Mini-Degree.

]]>
How to Build a Complete 2D Platformer in Unity https://gamedevacademy.org/how-to-build-a-complete-2d-platformer-in-unity/ Sun, 18 Dec 2022 23:43:34 +0000 https://gamedevacademy.org/?p=6509 Read more]]> Since the release of Unity 2017.1 in the summer of 2017, Unity Technologies has made making 2D games incredibly easy and fast.

In this tutorial, we will create a fully-featured 2D platformer. This project will incorporate a number of key topics including how to make cutscenes, how to quickly build and prototype a 2D level, and how to precisely choreograph game objects using the Timeline Editor.

This tutorial can also be thought of as the culmination of several tutorials – posted on Game Dev Academy – about these topics. You can check them out here:

Project Details

Let’s think about what we will be making. As said in the introduction, it will be a 2D platformer. We will use the 2D character from the Unity Standard Assets pack. Then we will create an environment using tilemaps and Unity’s new Tilemap Editor. Then we will create an enemy that has an Idle/Attack animation (you’ll see). Then we will create a cutscene where the camera views the entire level then zooms on the character: here we will use the Timeline Editorand Cinemachine for 2D.

You can download the complete Unity project here.

Before jumping in, while not entirely required, it is good to have familiarity with Unity and Cinemachine. Besides the tutorials above, you may also wish to check out some of our other Unity tutorials. Additionally, you can consider trying some premium online courses that have a more guided learning path and cover many of the same elements featured here.

For teachers, you might also want to consider Zenva Schools instead. Zenva Schools was designed specifically for teaching in the classroom and comes not only with online courses for Unity, but tons of tools like reporting, pre-made course plans, and more to make teaching with them super easy.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Tilemap Editor, Timeline, and Cinemachine

When Unity Technologies released the Unity 2017 version cycle, they introduced three pivotal tools designed to make Unity more accessible to artists. These tools were the Tilemap Editor, Timeline, and Cinemachine.

The Tilemap Editor, released later in the 2017 cycle, allowed users to “…literally paint directly in Unity” according to Rus Scammell, the project manager of Unity for 2D. The Tilemap Editor gives you the ability to create vast and complicated Tilemaps without having to use a third-party program.

The Timeline Editor and Cinemachine were released at the same time, though improvements to Cinemachine were released later. Cinemachine is a suite of cameras that allows you to create cutscenes, specify how the camera tracks a game object, and, in the end, allows you to tell a better story. Combine this with the Timeline Editor, a tool that allows you to choreograph game objects like a movie editor.

With these two tools, you can create stunning compositions with having to write any code.

Well, that’s a summary of the tools that we will be using! This tutorial is by no means exhaustive, for more information about these tools check out the tutorials linked above.

Setting up our project

The assets for this project you can get here. Then create a new Unity project. Let’s import the 2D Standard Assets package by going to the Asset Store panel. Here, search for “Standard Assets” and download it.

Then click on the Import button to import the asset. When the import window pops up, select the Standard Assets > 2D and StandardAssets > CrossPlatformInput folders only. Then import those.

Next, we need to create two new folders. One called “Animations” and the other called “Tiles”.

In the Tiles folder, create another folder called “Tile Palettes”.

The use of this folder will become apparent later on. Now let’s import Cinemachine by going to Package Manager (Window > Package Manager) and installing “Cinemachine”.

Now that we have everything imported we can start getting our tools in order. We will start with the Tilemap Editor. Go to Window > 2D > Tile Palette.

Place it in a sensible place on your workspace. I chose to put it in the space between the inspector and the scene view. Next, we need the Timeline Editor. Go to Window > Sequencing > Timeline.

The position of this tab is not set in stone so be prepared to move it around. We now have our workspace in order! Time to start creating!

Creating our environment

Go to your Tile Palette tab and create a new palette. Call it “Solids” since these are the tiles that the character will not be able to pass through.

A palette works just like you would expect it to based on the name, it is a set of images that we use to “paint” with. Leave all of the settings set to default and save it in the Tile Palettes folder which we created in the Tiles folder.

To setup our tiles, go to the Environment Tiles > Grass folder and drag those sprites into the Tile Palette window (do the same for any other tiles you want). Save the .asset files to the Tiles folder.

Now that all of our tiles are in order, let’s create a “canvas” to paint on. In your hierarchy, right-click and got to 2D Object > Tilemap.

What it has done is created a grid, and inside that grid is our “canvas”, also known as a tilemap. In order to start painting you need to familiarize your self with the toolbar in the Tile Palette tab. With your rule tile selected, start experimenting with the various types of brushes. Once you feel pretty confident with the tools, start creating your level!

Adding the character

The last thing we have to do to our tilemap is to make it have physics interactions. Right now anything we put on it would just fall through the world. To fix this, Unity Technologies released a new collider component called the Tilemap Collider. This behaves just like you would expect it to based on the title, it creates a collider around each tile. Go to your Tilemap and click Add Component.

Search “CharacterRobotBody” and drag the character into the scene.

We will be using the default character that came with the 2D standard asset pack. You can find the character by either going to Standard Assets -> 2D -> Prefabs and then dragging in the “CharacterRobotBoy”, or, you can just search “CharacterRobotBoy” and access it from there. Once the character is in the scene, you can hit play and move the character through the arrow keys. You may have to reposition the camera in order to see the robot. Great! On to the next paragraph!

Creating the enemy

In the “Enemies” folder from the asset pack, pick a certain enemy that you think would go well with your scene.

Drag it into your scene and place it in a sensible spot.

Then create a new tag called “Enemy” and assign it to your enemy.

Now we are going to animate this enemy. You should already have the Animation tab open in the lower window of your workspace. If not, go to Window > Animation > Animation.

With your enemy selected, click “Create” in the Animation tab.

Name it “Enemy1Controller”.

Save the animator controller in the Animations folder we created earlier.

Hit the record button and change the Sprite field to the other image that was provided (in my case it was called Saw_move, it may be similar if you chose a different enemy).

Then move about four frames ahead and change the image back to what it was before.

Then move a couple frames forward and change it back to the first image.

Now if you hit play you will see that our enemy is animating! Cool!

Scripting our enemy

Let’s make it so that whenever the character touches the enemy the level restarts. The best way to do this is to actually create a new script and box collider on our robot character.

Set the box collider to Trigger and make sure it liberally covers the character. Name the new script “EnemyReaction”.

Let’s create a new folder called “Scripts” to house this component.

Here is the content of the EnemyReaction script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; // This is very important if we want to restart the level

public class EnemyReaction : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
	// This function is called every time another collider overlaps the trigger collider
	void OnTriggerEnter2D (Collider2D other){
		// Checking if the overlapped collider is an enemy
		if (other.CompareTag ("Enemy")) {
			// This scene HAS TO BE IN THE BUILD SETTINGS!!!
			SceneManager.LoadScene ("scene1");
		}
	}
}

In order for this script to work, we need to do a couple of things. First, we need to have a collider on our enemy.

A simple box collider works best for covering all needs. Then, we need to save this scene as “scene1”.

Just save it in the root folder since we only have one, but if you are planning on having multiple scenes then you should create a new folder. Finally, that scene has to be put in the build settings. To do this, just go to File -> Build Settings

and then click “Add Open Scenes”.

Now everything should work! Hit play and run into the enemy, the level restarts!

Cinemachine and Timeline

We now come to the last part of this tutorial. In this part, we will be using Cinemachine and the Timeline editor. Let’s start with Cinemachine. You’ll notice that our camera isn’t following the character when he moves around. We can fix this by creating what is known as a Virtual Camera. Navigate to your toolbar and go to Cinemachine -> Create 2D Camera.

Then assign the “follow” field on this camera to be the CharacterRobotBoy. Rename this to “PlayerCam”. Set the Aim to “Do Nothing” and set the Body to “Framing Transposer”.

Next, let’s have a look at the Timeline Editor. Create a new, empty game object, named “Timeline”…

…and then click Create in the Timeline Editor. Call it “TheTimeline” and save it in the root folder.

You can have multiple timeline editors in a scene, which just adds to the complexity so we just have one. With this Timeline, we will create a cutscene where the camera views the entire level and then zooms in on the player. This will occur as soon as the scene starts. In order to do this, we need to combine Cinemachine and the Timeline Editor. We can do this through Cinemachine shot clips. In the Timeline, click “Add” and then go to Cinemachine.Timeline -> Cinemachine Track.

Drag the Main Camera into the field.

Then right-click and go to “Add Cinemachine Shot Clip”.

With this track, we can specify how long we want a certain camera to be active. Let’s create a new 2D camera and position it so that we can see the entire level. Name this one “FullLevel”.

This will be our first camera so select the Cinemachine shot clip and drag this camera into the “Virtual Camera” field.

Set how long you want this camera to last. One thing that helps is to set the timescale to be in second and not frames.

Next, we need to create another clip for the player camera.

Place this at the end of the other clip. Drag either one of the clips on top of each other in order to smoothly transition. Now if you hit play, we have a pretty neat cutscene! But notice when the last track ends it goes back to the first camera instead of staying on the player. The easiest way to fix this is by deactivating the first camera after we have transitioned into the second. We can do this by using an Activation Track. As its title implies, the specified game object will stay active as long as the track persists. Create an Activation track…

…and drag the first camera into its field.

Then set the length to be a little after the transition. Now if you hit play, it all looks good and the player camera persists!

Outro

Congratulations on getting to the end of this tutorial. We now have a 2D platformer in our hands, a perfect addition for any portfolio!

However, as I said before, this is not meant to be exhaustive. In order to find out more about these tools, you can either read the tutorials linked above, or you can explore them on your own! We also recommend you check out our web class on camera following and our mini-course on 2D platformers as well, as they’re sure to help you cement the knowledge you’ve learned here!

However, expanding your knowledge is also important. So be sure to explore other useful Unity skills via other tutorials or courses. Don’t forget there are also solutions for classrooms wanting to teach Unity as well that can come in handy for any teachers out there!

In either case:

Keep making great games!

BUILD GAMES

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

]]>
The Complete Guide to Building 3D Platformers in Unity https://gamedevacademy.org/tutorial-multi-level-platformer-game-in-unity/ Wed, 22 Jun 2022 15:54:50 +0000 https://gamedevacademy.org/?p=4478 Read more]]> Not only are 3D platformers fun, but they’re some of the best ways to learn the basics of Unity when you’re starting out.

In this tutorial, we’re going to cover just that using the popular Unity Engine: how to make a 3D platformer complete with enemy obstacles, multiple levels, coins, and scoring. You’ll also discover how to work with UI elements to build a menu screen too!

Let’s dive in and start learning Unity 3D in earnest!

Tutorial requirements and project files

No prior Unity or C# experience is required to follow along, although you should have familiarity with basic programming concepts such as variables, conditional statements and objects.

Project files can be downloaded here. This zip file contains all the files included in the Assets folder. You’ll still need to create a new project as covered in the tutorial.

Learning goals

The following animated GIF shows what the final game looks like:

Some of the topics we’ll cover include:

  • Basics of the Unity Editor, scenes, game objects and components
  • Understanding game object core methods in C# scripts
  • Working with object transforms both from the Inspector and from scripts
  • Accessing user input from scripts
  • Collision detection and rigid bodies
  • Implementing multiple scenes to create a multi-level game and passing objects along
  • Basic UI and importing fonts
  • Building your game

BUILD GAMES

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

Scene basics

Start by opening Unity. Click New, enter a name for the project (“Zenva 3D Platformer”), make sure 3D is selected, then click on Create project.

This will bring us to an empty Unity scene. I will now describe some of the main panels and elements present in the Unity Editor. If you are already familiar with the basics you can skip straight to the next section.

What is a scene? The word “scene” comes from the Greek skene, and was used back in ancient world for the area in the theater that faces the public, where all the action takes place. In Unity the definition is not too distant: a scene in your game is an object that contains all game objects such as players, enemies, cameras, lights, etc. Every game object within a scene has a position which is described in coordinates X, Y and Z.

The following image shows the main elements we find in the Unity Editor:

  • Project Window: this area shows the files and folders of our project. The only folder we’ll see in our new scene is the Assets folder, which is created automatically and it’s where we’ll place all the game assets (3D models, scripts, audio files, images, etc).
  • Hierarchy Window: shows all the game objects that are present in our scene. By default, Unity creates a camera and a directional light.
  • Scene View: shows the 3D view of your game scene. All the objects that you create in the Hierarchy Window will appear here in their corresponding X, Y, Z positions, and by using different “gizmos” or tools you can move, rotate and scale these objects around.
  • Game View: this view shows what the game actually looks like. In this case, it shows whatever the camera (which was created by default) is looking at.
  • Inspector: whenever you select a game object, the Inspector will show different options and properties that are available for that game object.
  • Toolbar: this area contains different tools we can use to modify our game objects, move around the scene, and modify how the Editor works.

When creating a new scene the first thing you’ll want to do is to save it. Let’s go to File – Save Scene and give it a name (“Game“).

As a Unity project grows, it becomes paramount to keep your files organized. In the Project Window, right click in Assets and create a new folder called Scenes. Drag our newly created Game scene in there.

Transform Component

All game objects in a scene have a Component named Transform. What is a component? Think of components as reusable “Lego pieces” that can be used in different objects. A component provides a game object with certain behaviors and properties.

As we mentioned before, all game objects in a scene have a position described in coordinates X,Y,Z. That in Unity is called the Transform component. This is the only component that is present in all game objects. There can’t be a game object without a Transform component!

On the Hierarchy Window, click on both the default camera and directional light, and observe how the Transform component appears in the Inspector, indicating the position of the object, plus values for rotation and scale.

Lets create a Cube to experiment with transforms. In the Hierarchy Window, right click and select 3D Object – Cube.

Click on the cube and change the position values in it’s Transform component to see how it’s position in the scene changes as well. Experiment changing the scale and rotation as well.

A scale of 1 means no change in size. If you set it to 2, it will twice the size in that axis. If you want it halved, set the scale to 0.5.

Notice that Unity uses what’s called a left-handed coordinate system:

Rotation values are entered in degrees. If you enter, for instance 45 in X, that means that the game object will rotate 45° around the X axis. To determine to which side it will rotate, use the left-hand rule as shown in the image below. If the rotation value is negative, use your right hand.

Besides changing the Transform properties of a game object from the Inspector, you can do so by using the Toolbar buttons and the “gizmos” in the Scene View:

Unity units

You may wonder, what’s the unit of measure in a Unity game? if we move an object from X = 1 to X = 2, how much would that represent in the real world? Unity uses Unity units. By convention (and this even includes some official Unity tutorials), 1 Unity unit is 1 meter.

The Floor

Let’s go ahead and create the floor of the game. For that, we will use a plane. Right click on your scene in the Hierarchy Window and select 3D Object – Plane. This will bring up a plane into our scene. From the Hierarchy Window, we can rename this object by right clicking – Rename, by selecting it and pressing F2, or by single-clicking on it after we’ve selected it. Call it “Floor”.

We will now create a new material so that it can look green. Un Unity, a material is an asset that controls the visual appearance of a game object.  We can easily create materials from the Project Window and assign them to objects in our scene.

Create a new folder inside of Assets called Materials. Inside of this new folder, right click and select CreateMaterial. This will create a new material file. Rename it to “Grass”. If you click on this file, the Inspector will show the properties of the newly created material. Click on the color white in Albedo and pick a color for the grass in the game:

Now drag the material file to the floor in the Scene View. The plane will look green, and if you click on it, you’ll see the material in the Mesh Renderer component in the Inspector.

Lastly, since the floor won’t be moving around in the game, check the Static checkbox located on the top-right of the Inspector.

By making a game object static, we are informing Unity that this object won’t be moving in our game. This allows Unity to perform behind the scenes optimizations when running the game.

Adding more game elements

Let’s add the remaining elements of our game. Start by creating the new materials. Pick whichever color you want for each one:

  • Platform
  • Coin
  • Enemy
  • Goal
  • Player

This is what mine look like:

What we’ll do next is add all the remaining elements to create our level, so that we can get a clear idea of what it will look like. We haven’t implemented our player, the behavior of the enemies or coins yet. Moreover, we haven’t written a single line of code. However, it’s good practice to design a game as early as possible.

Moving around blocks in Unity like we’ll do now is very easy and anyone can do it. This process can give you a very clear idea of what your game will look like, and allow you to save time further down the road, and to show other people what the game will look like. This process is called prototyping.

Let’s thus begin this process by adding some cubes to be used as platforms. Use the position gizmos or the Inspector to position them in different places. Set their scale in Y to a smaller value to make them thinner, and scale them up in X and Y so make them wider. Make sure to drag the Platform material we created to give them the color you want.

Since platforms won’t be moving make sure to set them as “static” (unless you want to create moving platforms of course!).

As we create more platforms, the Hierarchy Window can start to get crowded of elements. Game objects in Unity can be children of other objects. This means that their position is relative to that of the parent. In this case, grouping all the platforms inside of a single parent object can help us keep this window more clear – we won’t be moving this parent object.

In the Hierarchy Window right click and select Create Empty. Rename this new object to “Platforms”. Drag and drop all the platforms you created into this object. Notice that even though Platforms is empty (it doesn’t render anything on the screen), it still has a Transform component. As we said before, this component is always present in Unity game objects.

For the coins we’ll start by creating a cylinder in the Hierarchy Window (3D ObjectCylinder). Shrink it (this means, scale it down) on Y so that it looks more like a coin. Also, scale it down on X and Z to make it smaller (I’ve never seen a coin with a 1-meter diameter!). Lastly, rotate it 90 degrees in X or Z.

Rename the cylinder to “Coin”. Drag the Coin material into your coin and you’ll have your coin ready! Once we get into scripting, coins will have a C# script associated to them which will determine how they behave. Since we’ll have many coins, having to re-create them each time is not the best approach. Imagine we want to change how all coins behave at once? We need to create what’s called a prefab.

Unity prefabs are templates of game objects that can be reused (even used in different projects), and that allow us to generate many game objects that share properties and behaviors. Changes made to a prefab are reflected in all of it’s instances.

Create a new folder in Assets called Prefabs to keep our code organized. To create a prefab, simply drag and drop the coin you created (from the Hierarchy Window) into this new folder in the Project Window.

Now that we have our prefab ready, you could safely delete the coin from the Hierarchy Window, but you don’t really have to. To create more instances of our prefab, simply drag and drop the coin Prefab into the Scene View. Do it many times (you can also do it once and duplicate the object with Control + D).

If you select any of these instance you’ll see a Prefab area in the Inspector. If you click on Select in there, see how the Coin prefab is selected. If you make changes to this particular instance (for example, change the scale, rotation or material) and press Apply, the changes made will be applied to the prefab itself, changing thus all other instances!

Place coins across your level. This will help you get familiar with moving around the scene, duplicating or copying and pasting objects, and using the position gizmo. When you are done we’ll finish off with the design of our level. Make sure to group all the coins in an empty object, just like we did with the platforms before.

We’ll now follow a similar process for the player, enemies and the level goal. For the player and enemies do the following:

  • Create a cube
  • Scale it to 0.6 in all axes
  • Assign the corresponding material
  • Drag to the Prefabs folder
  • Drag the newly created prefab on to the Scene View to create an instance (for the enemy, create more than one, and group them in an empty object)

We can, of course, change of all this later, so don’t much in too much thought or try to be perfectionist at this stage.

For the goal, the only difference is that instead of a cube, we’ll use a sphere (3D ObjectSphere). The process described about is the same.

This is what my level looks like:

Pro tip: when moving a game object with the position gizmo, if you keep the Control key pressed (CMD in Mac) the object will move in fixed increments (which you can change in EditSnap Settings). If you grab the object from it’s center, and press both Control and Shift, the object will snap to the surface of any near object. This is useful to place the player on the ground with precision. Read the documentation under “Snapping” for more details.

Coin rotation script

Coins will always be rotating around the Y axis. This is really a cosmetic aspect of the game. As you might have guessed, I like to create a rough version of the full game before diving into this kinds of details (which I tend to leave for the very end). However, I think coin rotation can give us a very simple example to cover the basics of Unity scripting, so this will be our first approach to scripting, in preparation for the more complex implementation of the player controller.

Unity scripts are a necessary part of any game. Scripts can be written in C#, UnityScript  (aka “JavaScript for Unity”) and a language called Boo. C# is the most popular option these days, so that’s the only language we’ll be using.

Let’s begin by creating a new folder inside of Assets called Scripts. In this new folder, right click and select Create – C# Script, name it CoinController. Voilá! You have created your first Unity script.

Double click on this new file and Visual Studio will open. The default contents are as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CoinController : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

What we have here is:

  • A new class has been created for us. This class is called CoinController , and inherits from another class called MonoBehaviour. Think of a class as a blueprint (“a recipe to make a cupcake”) that can be used to create objects with certain characteristics and behaviors (“an actual cupcake”). Objects created from a class are called instances of that class.

  • Our new class has two methods: Start  and Update . In Unity, there are some reserved method names used in classes that inherit from MonoBehaviour. We’ll now explain what these two methods do. You can find the full list of MonoBehaviour methods here.
    •  Start is called on the first frame of the game.
    • Update is called on every frame, multiple times per second!

What we want to do with our coin is rotate it all the time at a certain speed. We don’t need to perform any action on the first frame of a coin, so we’ll delete the Start method code.

On the other hand, we do want to rotate it slightly on each frame. One way to do that is access the transform of the coin, which as we’ve seen contains it’s position, scaling and rotation values. We’ll start by defining a rotation speed, as a public variable, and give it a default value (more on this later).

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CoinController : MonoBehaviour {

    public float rotationSpeed = 100f;

    // Update is called once per frame
    void Update () {
		
    }
}

A public variable is a property of the class that can be modified from outside the class. As we’ll see shortly, by assigning this property as public we’ll be able to modify it directly from the Unity Editor.

On Unity scripts we have access to an object Time , which has a property called deltaTime  and provides the time in seconds since the last frame.

Basic physics stats that speed is equal to distance divided by time. This means, distance is equal to speed times time. We’ll use that formula to determine how much the coin needs to rotate on each frame:

//distance (in angles) to rotate on each frame. distance = speed * time
float angle = rotationSpeed * Time.deltaTime;

The rotation needs to be about the vertical axis (Y). We can access the object’s transform and make it rotate as shown below:

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CoinController : MonoBehaviour {

    public float rotationSpeed = 100f;

    // Update is called once per frame
    void Update()
    {
        //distance (in angles) to rotate on each frame. distance = speed * time
        float angle = rotationSpeed * Time.deltaTime;

        //rotate on Y
        transform.Rotate(Vector3.up * angle, Space.World);
    }
}
  • transform.Rotate  allows us to rotate the transform. For the full documentation see here.
  • Vector3.up gives us the vertical axis. An alternative would be to create a new Vector3  object like so: new Vector3(0, 1, 0);
  • The last parameter Space.World needs to be specified in this case, and it means that the rotation needs to be to the “up” direction in the world, not relative to the object. Remember how we created our coins: we inserted a cylinder, reduced it in size then rotated it so that it would look like a coin. If you don’t specify this parameter, the rotation will be applies on local coordinates, in which the Y axis is tilted.

Last but not least, we need to attach this script to our coin prefab. So far, Unity has no way of knowing that this script is to be used on coins!

Select your coin prefab (from the Prefabs folder). In the Inspector click on Add Component, select Scripts – Coin Controller. This action will attach the script to all the coins you have created. Notice how we can also change the rotation speed from here – all public properties show in the Inspector and can be edited directly from the Unity Editor. This is quite useful in case you are working with people who don’t do coding but need to make changes to the game.

See it in action! Press the “play” icon on the Toolbar and see how the coins rotate in either the Scene View or the Game View.

Where did the “100” for rotation speed come from? The answer is: from trial and error. When making games you’ll quite often need to set arbitrary values such as speeds, jumping distances, etc. What I usually do is throw in a number and adjust until it looks/feels good.

Player movement

In this section we’ll implement player movement using the arrow keys. Let’s first place the camera in a position where the whole level can be seen easily. See below where I’ve placed mine (you can copy the values in Transform if you want). Feel free to manually adjust it.

Our player will be subject to physics laws: gravity, momentum, etc. For that, Unity provides a component named Rigid Body, which we need to assign to our Player prefab. In the Inspector click Add Component, select Physics – Rigidbody.

Create a new script in the Scripts folder and call it PlayerController. We’ll start by adding some public properties for the walking and jumping speed of our player. Attach the script to the Player prefab as described in the previous section.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float walkSpeed = 8f;
    public float jumpSpeed = 7f;

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

We’ll begin our implementation of basic cursor keys movement by reading user input from the Update  method. When it comes to player controllers, it’s good practice in Unity to read input axes instead of specific keys. For example, when you press the “up” key, you activate the vertical axis. This axis would also be activated if you pressed the “up” key on a gamepad, or some other device. Moreover, people with certain disabilities can map their gamepads or joysticks in different ways. So it’s always good practice to read “axes” instead of specific keys (unless, or course, you really need to read a certain key).

If you are curious, you can see the axes available if you go to the menu EditProject SettingsInput. We’ll be using Horizontal and Vertical.

To be sure that we are reading the arrow keys correctly, add the following code to Update , which will show in the the Editor’s Console (tab next to Projects) a message with the values we get:

    // Update is called once per frame
    void Update () 
    {
        // Input on x ("Horizontal")
        float hAxis = Input.GetAxis("Horizontal");

        print("Horizontal axis");
        print(hAxis);

        // Input on z ("Vertical")
        float vAxis = Input.GetAxis("Vertical");

        print("Vertical axis");
        print(vAxis);
    }

If you play the game and press the arrow keys you’ll notice that hAxis  shows values from -1 (left) to 1 (right). vAxis  shows values from -1 (down) to 1 (up). The value of 0 is shown when no key is pressed.

Each time the input is read, we’ll move a certain distance which can be calculated as speed * time. (remember: speed = distance / time, which means distance = speed * time).

We’ll create a vector that points out where we are moving, based on our current position:

    // Update is called once per frame
    void Update ()
    {
        // Distance ( speed = distance / time --> distance = speed * time)
        float distance = walkSpeed * Time.deltaTime;

        // Input on x ("Horizontal")
        float hAxis = Input.GetAxis("Horizontal");

        // Input on z ("Vertical")
        float vAxis = Input.GetAxis("Vertical");

        // Movement vector
        Vector3 movement = new Vector3(hAxis * distance, 0f, vAxis * distance);

        // Current position
        Vector3 currPosition = transform.position;

        // New position
        Vector3 newPosition = currPosition + movement;
    }

Now, how do we actually move our player? We need to access the player’s rigid body in order to do that (yes, we could just move the transform like we did with the coins, but in this case we want to have an accurate physics simulation with velocity, gravity, etc, so we need to use the rigid body instead).

We need to create a variable to store our rigid body and put the Rigid Body component in it (at the start of our script, for which we can use the Start  method), so that we can then access it for movement, jumping, and whatever else we need.

To make our code cleaner we’ll put all the movement code in it’s own function, named WalkHandler .

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float walkSpeed = 8f;
    public float jumpSpeed = 7f;

    //to keep our rigid body
    Rigidbody rb;

    // Use this for initialization
    void Start () {
        //get the rigid body component for later use
        rb = GetComponent<Rigidbody>();
    }
	
	// Update is called once per frame
	void Update ()
    {
        // Handle player walking
        WalkHandler();
    }

    // Make the player walk according to user input
    void WalkHandler()
    {
        // Set x and z velocities to zero
        rb.velocity = new Vector3(0, rb.velocity.y, 0);

        // Distance ( speed = distance / time --> distance = speed * time)
        float distance = walkSpeed * Time.deltaTime;

        // Input on x ("Horizontal")
        float hAxis = Input.GetAxis("Horizontal");

        // Input on z ("Vertical")
        float vAxis = Input.GetAxis("Vertical");

        // Movement vector
        Vector3 movement = new Vector3(hAxis * distance, 0f, vAxis * distance);

        // Current position
        Vector3 currPosition = transform.position;

        // New position
        Vector3 newPosition = currPosition + movement;

        // Move the rigid body
        rb.MovePosition(newPosition);
    }
}

You can now move around! But as you crash against an enemy or a platform you’ll notice that the player rotates after the collision:

Our  player is represented by a rigid body which simulates real physics. If you put a dice on a surface and hit it on a side, it will of course rotate! What we need to do is disable our player from rotating, which can be easily done from the Inspector. Find the Rigid Body component of the player prefab, under Constraints go and check Freeze Rotation for all axes.

Player jumping

We can now move our player around the game with the arrow keys, and it’s time to give it the ability to jump. Implementing proper jumping logic will take some thought, but we’ll go step by step covering all that it entails.

Unity comes with an Input Axis called “Jump”, which activates with the spacebar by default. Go to Edit – Project Settings –  Input to double check it’s there on your end.

When should the player be allowed to jump? Should it be allowed to jump while it’s already in the air? You start to realize that there are some rules around when the player should be allowed to jump. I’ve put these together in the following diagram:

Let’s begin by creating a function to take care of all the jumping logic. We’ll call that on Update .

    // Update is called once per frame
    void Update ()
    {
        // Handle player walking
        WalkHandler();

        //Handle player jumping
        JumpHandler();
    }

If we just check that the Jump axis has been pressed, we can make our player jump like so:

    // Check whether the player can jump and make it jump
    void JumpHandler()
    {
        // Jump axis
        float jAxis = Input.GetAxis("Jump");

        if (jAxis > 0f)
        {
            // Jumping vector
            Vector3 jumpVector = new Vector3(0f, jumpSpeed, 0f);

            // Make the player jump by adding velocity
            rb.velocity = rb.velocity + jumpVector;
        }
    }

Of course, this is an incomplete implementation, as we are not checking whether the player is grounded or not. Also, if you keep the spacebar pressed, the player will fly away!

We’ll now make sure that we can’t jump more than once on the same key press. We can do that by using a boolean variable which we’ll use as a “flag” to indicate whether we’ve jumped on the current keypress or not.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float walkSpeed = 8f;
    public float jumpSpeed = 7f;

    //to keep our rigid body
    Rigidbody rb;

    //flag to keep track of whether a jump started
    bool pressedJump = false;

    // Use this for initialization
    void Start () {
        //get the rigid body component for later use
        rb = GetComponent<Rigidbody>();
    }
	
	// Update is called once per frame
	void Update ()
    {
        // Handle player walking
        WalkHandler();

        //Handle player jumping
        JumpHandler();
    }

    // Make the player walk according to user input
    void WalkHandler()
    {
        // Set x and z velocities to zero
        rb.velocity = new Vector3(0, rb.velocity.y, 0);

        // Distance ( speed = distance / time --> distance = speed * time)
        float distance = walkSpeed * Time.deltaTime;

        // Input on x ("Horizontal")
        float hAxis = Input.GetAxis("Horizontal");

        // Input on z ("Vertical")
        float vAxis = Input.GetAxis("Vertical");

        // Movement vector
        Vector3 movement = new Vector3(hAxis * distance, 0f, vAxis * distance);

        // Current position
        Vector3 currPosition = transform.position;

        // New position
        Vector3 newPosition = currPosition + movement;

        // Move the rigid body
        rb.MovePosition(newPosition);
    }

    // Check whether the player can jump and make it jump
    void JumpHandler()
    {
        // Jump axis
        float jAxis = Input.GetAxis("Jump");

        // Check if the player is pressing the jump key
        if (jAxis > 0f)
        {
            // Make sure we've not already jumped on this key press
            if(!pressedJump)
            {
                // We are jumping on the current key press
                pressedJump = true;

                // Jumping vector
                Vector3 jumpVector = new Vector3(0f, jumpSpeed, 0f);

                // Make the player jump by adding velocity
                rb.velocity = rb.velocity + jumpVector;
            }            
        }
        else
        {
            // Update flag so it can jump again if we press the jump key
            pressedJump = false;
        }
    }    
}

We can now only do one jump at a time. We can still jump on the sky though. If you were implementing something like Mario’s underwater levels you’d be good to go!

It’s turn to tackle the “player grounded” issue. We should only be allowed to jump when we are grounded. For that, we’ll create a function that checks if the player is grounded, and returns true if that is the case.

There is not an “official” way to check whether an object is grounded in Unity. What we’ll do in this tutorial is the way that I find the simplest and it is to check whether any of the 4 bottom corners of the player is on top of a collider (an object that produces collision, such as the floor or any object with a Collider component). The steps we’ll take are:

  • Get the collider of the player, so that we can get it’s size. We’ll get this collider object in Start , following the same approach we took with rigid body.
  • With the size of the player, get the positions of all 4 bottom corners.
  • Send a raycast from these points, pointing downwards. A raycast is a line that finds colliders. It will return true if it finds a collider such as the floor.
  • If we find that any of the corners is grounded, we’ll say that the player is grounded!

Our code now looks like so, and we have now a platformer jumping behavior that makes sense!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float walkSpeed = 8f;
    public float jumpSpeed = 7f;

    //to keep our rigid body
    Rigidbody rb;

    //to keep the collider object
    Collider coll;

    //flag to keep track of whether a jump started
    bool pressedJump = false;

    // Use this for initialization
    void Start () {
        //get the rigid body component for later use
        rb = GetComponent<Rigidbody>();

        //get the player collider
        coll = GetComponent<Collider>();
    }
	
	// Update is called once per frame
	void Update ()
    {
        // Handle player walking
        WalkHandler();

        //Handle player jumping
        JumpHandler();
    }

    // Make the player walk according to user input
    void WalkHandler()
    {
        // Set x and z velocities to zero
        rb.velocity = new Vector3(0, rb.velocity.y, 0);

        // Distance ( speed = distance / time --> distance = speed * time)
        float distance = walkSpeed * Time.deltaTime;

        // Input on x ("Horizontal")
        float hAxis = Input.GetAxis("Horizontal");

        // Input on z ("Vertical")
        float vAxis = Input.GetAxis("Vertical");

        // Movement vector
        Vector3 movement = new Vector3(hAxis * distance, 0f, vAxis * distance);

        // Current position
        Vector3 currPosition = transform.position;

        // New position
        Vector3 newPosition = currPosition + movement;

        // Move the rigid body
        rb.MovePosition(newPosition);
    }

    // Check whether the player can jump and make it jump
    void JumpHandler()
    {
        // Jump axis
        float jAxis = Input.GetAxis("Jump");

        // Is grounded
        bool isGrounded = CheckGrounded();

        // Check if the player is pressing the jump key
        if (jAxis > 0f)
        {
            // Make sure we've not already jumped on this key press
            if(!pressedJump && isGrounded)
            {
                // We are jumping on the current key press
                pressedJump = true;

                // Jumping vector
                Vector3 jumpVector = new Vector3(0f, jumpSpeed, 0f);

                // Make the player jump by adding velocity
                rb.velocity = rb.velocity + jumpVector;
            }            
        }
        else
        {
            // Update flag so it can jump again if we press the jump key
            pressedJump = false;
        }
    }

    // Check if the object is grounded
    bool CheckGrounded()
    {
        // Object size in x
        float sizeX = coll.bounds.size.x;
        float sizeZ = coll.bounds.size.z;
        float sizeY = coll.bounds.size.y;

        // Position of the 4 bottom corners of the game object
        // We add 0.01 in Y so that there is some distance between the point and the floor
        Vector3 corner1 = transform.position + new Vector3(sizeX/2, -sizeY / 2 + 0.01f, sizeZ / 2);
        Vector3 corner2 = transform.position + new Vector3(-sizeX / 2, -sizeY / 2 + 0.01f, sizeZ / 2);
        Vector3 corner3 = transform.position + new Vector3(sizeX / 2, -sizeY / 2 + 0.01f, -sizeZ / 2);
        Vector3 corner4 = transform.position + new Vector3(-sizeX / 2, -sizeY / 2 + 0.01f, -sizeZ / 2);

        // Send a short ray down the cube on all 4 corners to detect ground
        bool grounded1 = Physics.Raycast(corner1, new Vector3(0, -1, 0), 0.01f);
        bool grounded2 = Physics.Raycast(corner2, new Vector3(0, -1, 0), 0.01f);
        bool grounded3 = Physics.Raycast(corner3, new Vector3(0, -1, 0), 0.01f);
        bool grounded4 = Physics.Raycast(corner4, new Vector3(0, -1, 0), 0.01f);

        // If any corner is grounded, the object is grounded
        return (grounded1 || grounded2 || grounded3 || grounded4);
    }
}

Is it really over? We’ll, there is just one last thing. See what happens if you jump against a wall and keep on pushing towards that direction. Yep, you’ll get stuck on the wall.

This is caused by friction. This can be disabled so that our player doesn’t rotate by creating a physics material. Physics materials allow us to give our game object custom physical properties such as friction, bounciness, and how it will behave when colliding with other objects. In your Assets folder, create a subfolder called Physics Materials, and inside of that folder right click and select Create – Physics Material, name it Player.
Give this new material properties as shown below, so that we don’t have any friction. Make sure to select Minimum in Friction Combine. This means that no matter what the friction is of the colliding object, the minimum value will be used for physics calculations.

Select your Player prefab, in the Inspector look for the Box Collider component and click in Material. Select the physics material you just created in order to assign it to the prefab.

Now we are finally done with player jumping 🙂

Collecting coins

In this section we’ll implement coin collection. When the player collects a coin, a sound will be played. In the next section, we’ll keep track of the score of the player in an object we’ll call GameManager, which will keep track of game-level information (score, high score, level).

Currently, if you touch a coin you’ll notice that they actually stop the player, they are “solid”. This is not the behavior we want. We want to be able to detect a collision between the player an a coin, however, we don’t want coins to affect the velocity, or any physics property, of our player.

We need to make our coins a trigger collider. When another object collides with a coins, a trigger event will be fired, and the physics properties of the object won’t be affected, just as if you were going through thin air! Select the coin prefab, find the component Capsure Collider in the Inspector, and check Is Trigger.

Do the same for the enemy prefab and goal prefab. We can now jump through coins. We need to know “collect” these coins on collision, play a sound and destroy the coins after collected. In our player controller script, we can use a method named OnTriggerEnter  (learn more about it here). This method will be called each time the player runs into a trigger collider. The following code outlines the steps of what we’ll do next. In this section, we’ll only take care of playing the sound and destroying the coin:

void OnTriggerEnter(Collider collider)
{
    //detect that we collided with a coin, if that is the case:
    // - play a coin collecting sound
    // - update the score
    // - destroy the coin
}

To detect whether the trigger object the player ran into is a coin we can give our coin prefab a tag that identifies it. Select the coin prefab and in the Inspector, in Tag go and select Add Tag. Create a “Coin” tag. Also, create “Goal” and “Enemy” as we’ll use those later. After creating the tags, make sure the coin prefab has the Coin tag in Tag on the Inspector (pick it from the list). Do the same for the enemy and goal prefabs.

We can check the tag of the object we’ve collided with, and destroy the coin we’ve collected by doing:

    void OnTriggerEnter(Collider collider)
    {
        // Check if we ran into a coin
        if (collider.gameObject.tag == "Coin")
        {
            print("Grabbing coin..");
            
            // Destroy coin
            Destroy(collider.gameObject); 
        }
    }

Let’s now take care of the coin sound. Create a folder in Assets called Audio, copy the coin.ogg file provided with the tutorial source code (download at the start of the tutorial or here). In the Hierarchy Window, right click and select AudioAudio Source, rename it to “Coin Audio Source”. Select the newly created object. In the Inspector, drag the coin.ogg file to AudioClip. Uncheck the box Play On Awake so that the sound doesn’t play each time the game starts.

We need to know be able to pass this audio source to our player, so that it can be played each time a coin is collected.

For that, we can create a public variable in our player controller, of type AudioSource , and pass our audio source object to it via the Inspector. Add the following at the start of your player controller:

public AudioSource coinAudioSource;

Now drag and drop the coin audio source object into the Coin Audio Source field in the player prefab’s Inspector, Script component.

In your player controller file, we can now play the file in  OnTriggerEnter :

    void OnTriggerEnter(Collider collider)
    {
        // Check if we ran into a coin
        if (collider.gameObject.tag == "Coin")
        {
            print("Grabbing coin..");

            // Play coin collection sound
            coinAudioSource.Play();

            // Destroy coin
            Destroy(collider.gameObject);
        }
    }

Game Manager

Most games have some sort of high-level parameters and operations, such as resetting the game, managing game over, number of lives, current level, options, etc. In our game for instance, we want to keep track of the player score, the high score, and the level we are in.

To keep track of these things, we can create an object that keeps track of these things and helps manage it it all. We’ll call this object the Game Manager.

Something we know for sure about this Game Manager object is that we’ll only want a single instance of this object to exist at the same time. In computer science terminology, we want this object to be a singleton.

Create a script and call it GameManager. The following code will help us keep track of the score.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour {

    // Player score
    public int score = 0;

    // Increase score
    public void IncreaseScore(int amount)
    {
        // Increase the score by the given amount
        score += amount;
    }
}

To actually have this script in our game, create an empty game object in the Hierarchy Window, name it “Game Manager”, and assign our script to it.

We now need to access this object and it’s method IncreaseScore  in our player controller in order to increase the score every time we collect a coin. One way to do this is to repeat the steps we took when attaching the coin audio source to our player (creating a “gameManager” public property and dragging the “Game Manager” object to the player’s Inspector). That works and there is nothing wrong in doing that.

Since we are talking about the game manager here, it’s highly likely that we’ll want to access it from many game objects, not just the player. Having to drag and drop it each time can become time consuming. A different approach is to use a static variable that can be access from anywhere in the code, without having to declare public variables each time and drag and drop elements. This will also help us enforce the fact that there will only be a single instance of the Game Manager in our game (the singleton pattern).

The following implementation will provide all of the above. Plus, when we load different scenes (game over scene, or other levels) the Game Manager is not destroyed, which would happen by default. For more explanations see this official tutorial and this tutorial on game manager.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour {

    // Static instance of the Game Manager,
    // can be access from anywhere
    public static GameManager instance = null;

    // Player score
    public int score = 0;

    // Called when the object is initialized
    void Awake()
    {
        // if it doesn't exist
        if(instance == null)
        {
            // Set the instance to the current object (this)
            instance = this;
        }

        // There can only be a single instance of the game manager
        else if(instance != this)
        {
            // Destroy the current object, so there is just one manager
            Destroy(gameObject);
        }

        // Don't destroy this object when loading scenes
        DontDestroyOnLoad(gameObject);
    }

    // Increase score
    public void IncreaseScore(int amount)
    {
        // Increase the score by the given amount
        score += amount;

        // Show the new score in the console
        print("New Score: " + score.ToString());
    }
}

In our player, we can increase the score like so:

    void OnTriggerEnter(Collider collider)
    {
        // Check if we ran into a coin
        if (collider.gameObject.tag == "Coin")
        {
            print("Grabbing coin..");

            // Increase score
            GameManager.instance.IncreaseScore(1);

            // Play coin collection sound
            coinAudioSource.Play();

            // Destroy coin
            Destroy(collider.gameObject);
        }
    }

We can now collect coins and see the increased score in the Console!

What about keeping high score? That will be be quite straightforward and can be done directly in GameManager:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour {

    // Static instance of the Game Manager,
    // can be access from anywhere
    public static GameManager instance = null;

    // Player score
    public int score = 0;

    // High score
    public int highScore = 0;

    // Called when the object is initialized
    void Awake()
    {
        // if it doesn't exist
        if(instance == null)
        {
            // Set the instance to the current object (this)
            instance = this;
        }

        // There can only be a single instance of the game manager
        else if(instance != this)
        {
            // Destroy the current object, so there is just one manager
            Destroy(gameObject);
        }

        // Don't destroy this object when loading scenes
        DontDestroyOnLoad(gameObject);
    }

    // Increase score
    public void IncreaseScore(int amount)
    {
        // Increase the score by the given amount
        score += amount;

        // Show the new score in the console
        print("New Score: " + score.ToString());

        if (score > highScore)
        {
            highScore = score;
            print("New high score: " + highScore);
        }
    }
}

Of course, for now our high score updates just like our score. This will be fully finished once we implement game over.

Enemy movement

Enemies will have an up-and-down movement within a range. We’ll make it so that you can easily change the speed, initial direction and movement range. In the tutorial we’ll only implement movement in Y, but you can easily modify this code to have enemies moving in other directions too!

Start by creating a new script which we’ll call “EnemyController”. Attach it to the enemy prefab. We’ll add some public variables, and also keep the initial position so that we can move around it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyController : MonoBehaviour {

    // Range of movement
    public float rangeY = 2f;

    // Speed
    public float speed = 3f;

    // Initial direction
    public float direction = 1f;

    // To keep the initial position
    Vector3 initialPosition;

    // Use this for initialization
    void Start () {

        // Initial location in Y
        initialPosition = transform.position;
    }
	
    // Update is called once per frame
    void Update () {
		
    }
}

In each frame, we’ll do the following:

  • Calculate how much we are moving (distance = elapsed time * speed * direction).
  • Calculate the new Y position (new position = old position + distance)
  • If we’ve passed the movement range, change direction

The code of Update  will then be:

    // Update is called once per frame
    void Update() 
    {
        // How much we are moving
        float movementY = direction * speed * Time.deltaTime;

        // New position
        float newY = transform.position.y + movementY;

        // Check whether the limit would be passed
        if (Mathf.Abs(newY - initialPosition.y) > rangeY)
        {
            // Move the other way
            direction *= -1;
        }

        // If it can move further, move
        else
        {
            // Move the object
            transform.Translate(new Vector3(0, movementY, 0));
        }        
    }

Feel free to adjust the range, speed and direction of each one of your  individual enemies if you are not happy with the default values!

To detect enemy collision (for game over purposes!), add the following to your player controller’s  OnTriggerEnter method, after the if statement where we check for the coin tag (this assumes you’ve checked Is Trigger on the enemy prefab):

        else if(collider.gameObject.tag == "Enemy")
        {
            // Game over
            print("game over");
            
            // Soon.. go to the game over scene
        }

Multi-level game

In this section we’ll implement multi-level functionality. Each level will have it’s own scene, and we’ll use the Game Manager to keep track of the current level, the number of levels, and the level loading process.

Go to your Scenes folder (some people like to name this folder _Scenes so that it shows first on the folder list), rename the scene we’ve been using to Level1. Create a new scene by right clicking and selecting CreateScene. Name it Level2.

If you double click on the new scene, you will see that you are taken to a blank scene. The easiest way to start a new level is to “copy and paste” the objects from the Hierarchy Window of Level1, into Level2. In Level1, simply select the objects you want, right click and pick “copy”. In Level2 right click in and pick “paste”.

Lets modify GameManager so that it can take us from one level to the next. I’ve only implemented two levels for this tutorial, but the code is completely genetic – it can be used for hundreds of levels if you so want!

We’ll specify the starting level, and the highest level we have in our game. If we pass that level, we’ll send the user back to level 1. Let’s also add a method to restart the game (used for game over).

To change Unity scenes, we need to import the Unity.SceneManagement  package.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour {

    // Static instance of the Game Manager,
    // can be access from anywhere
    public static GameManager instance = null;

    // Player score
    public int score = 0;

    // High score
    public int highScore = 0;

    // Level, starting in level 1
    public int currentLevel = 1;

    // Highest level available in the game
    public int highestLevel = 2;

    // Called when the object is initialized
    void Awake()
    {
        // if it doesn't exist
        if(instance == null)
        {
            // Set the instance to the current object (this)
            instance = this;
        }

        // There can only be a single instance of the game manager
        else if(instance != this)
        {
            // Destroy the current object, so there is just one manager
            Destroy(gameObject);
        }

        // Don't destroy this object when loading scenes
        DontDestroyOnLoad(gameObject);
    }

    // Increase score
    public void IncreaseScore(int amount)
    {
        // Increase the score by the given amount
        score += amount;

        // Show the new score in the console
        print("New Score: " + score.ToString());

        if (score > highScore)
        {
            highScore = score;
            print("New high score: " + highScore);
        }
    }

    // Restart game. Refresh previous score and send back to level 1
    public void Reset()
    {
        // Reset the score
        score = 0;

        // Set the current level to 1
        currentLevel = 1;

        // Load corresponding scene (level 1 or "splash screen" scene)
        SceneManager.LoadScene("Level" + currentLevel);
    }

    // Go to the next level
    public void IncreaseLevel()
    {
        if (currentLevel < highestLevel)
        {
            currentLevel++;            
        }
        else
        {
            currentLevel = 1;
        }
        SceneManager.LoadScene("Level" + currentLevel);
    }
}

To detect when the level goal is reached. Provided you’ve checked Is Trigger on the goal prefab:

        else if(collider.gameObject.tag == "Goal")
        {
            // Next level
            print("next level");        
        }

If you try playing the game now and you reach the level goal, you’ll see an error message in the console that will say something in the lines of:

Scene 'Level1' couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.

To add a scene to the build settings use the menu File->Build Settings and add your scenes to the list (you might have to click Add Open Scenes for each scene).

We can now play our game and move from one scene to the next! Notice how the score stays in between scenes. Basically, our GameManager object survives between scenes because of the statement DontDestroyOnLoad(gameObject)  (and of course, the rest of the Game Manager implementation).

Adding the HUD

So far we have no idea what our score is. We need to show it to the player. Let’s implement a very simple HUD where we show the current score.

Start by adding a text element in the Hierarchy Window. Right-click, UIText. This will create a Canvas element, with a Text element inside. Rename the text element to “Score Label”. In the Scene View, click 2D, select the text and press f. This will show you the canvas location of the text label.

When adding UI elements, a canvas is created automatically. A canvas in Unity is a game object where all UI elements should be located. Some UI elements such as buttons handle user input, for which the canvas provides event system support, for which an EventSystem object was automatically created in our Hierarchy Window, as you can probably see. You can read more about the canvas in the docs.

Drag the text label to the upper-left area of the canvas. Select the canvas object and find the Canvas Scaler component in the Inspector. Change UI Scale Mode to Scale with Screen Size so that the whole canvas scales up or down depending on the screen size. In this manner, the text label will always stay in that relative position. Set the Reference Resolution to 1024 x 576.

 

We’ll now import a much nicer pixel art font to use called Press Start. Create a folder called “Fonts”. Assuming you’ve downloaded the tutorial files, copy the files prstart.ttf and license.txt (both located in Assets/Fonts) into your Fonts folder. Make sure to read the license file which covers how you are allowed to use this font.

Now, if you select Score Label, find the Font field and click on the circle next to it, you’ll be able to select our Press Start font. Set the font size to 32.

 

We can now see our text in this pixel font! However, it does look a bit blurry:

This can be easily fixed by making a change in the Import Settings of the font. Go to your Fonts folder, select the font file, and in the Inspector, change Rendering Mode to Hinted Raster. Press apply and you are pixel crispy good!

Before we move on to the HUD functionality, feel free to change the font color or style (I’m changing it to white).

We’ll create a new object that will take care of managing the HUD. Create an empty object called Hud Manager. Create a new script and name it HudManager. Drag this new script onto the Hud Manager object in the Hierarchy View.

The HudManager script needs to be able to access the text label we created, so that it can change it’s contents. This will be added as a public variable. We’ll give it a public method called Refresh, so that we can trigger a HUD update from anywhere in our code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HudManager : MonoBehaviour {

    public Text scoreLabel;

    // Use this for initialization
    void Start()
    {
        Refresh();
    }

    // Show player stats in the HUD
    public void Refresh()
    {
        scoreLabel.text = "Score: " + GameManager.instance.score;
    }
}
  • We start by importing the UnityEngine.UI namespace so that we can easily access UI-related functionality
  • Create a public variable of type UnityEngine.UI.Text for our score label.
  • We’ll refresh the HUD on the first frame of the game, to show the initial score.
  • The Refresh method modifies the actual text content of the score field. Notice how we can easily access the current score in our game from the GameManager.

Make sure to drag the Score Label object in your Hierarchy Window to the Hud Manager object, so that it knows which text element to modify!

The last bit missing is to actually call this Refresh method in our game! We’ll do this in our PlayerController. Let’s refresh the HUD at the start of the game (on the first frame), and every time the player gets a coin.

In order to be able to access the HudManager from our PlayerController, we’ll add a public variable:

// access the HUD
public HudManager hud;

Let’s refresh the HUD upon first frame:

    // Use this for initialization
    void Start()
    {
        //get the rigid body component for later use
        rb = GetComponent<Rigidbody>();

        //get the player collider
        coll = GetComponent<Collider>();

        //refresh the HUD
        hud.Refresh();
    }

And every time we collect a coin:

        // Check if we ran into a coin
        if (collider.gameObject.tag == "Coin")
        {
            print("Grabbing coin..");

            // Increase score
            GameManager.instance.IncreaseScore(1);

            //refresh the HUD
            hud.Refresh();

            // Play coin collection sound
            coinAudioSource.Play();

            // Destroy coin
            Destroy(collider.gameObject);
        }

Make sure to drag and drop the Hud Manager object onto our Player object. To make this work multilevel, simply copy these new objects (canvas, HUD manager) into each level, and make the corresponding dragging and dropping so it all wires up.

Note: you could also take a different approach and incorporate HUD management into the Game Manager, or create similar type of object. There is no single correct way and this seemed to be the simplest approach for our game.

Note 2: if you are an advanced programmer and don’t like doing so much “dragging and dropping” I’d recommend reading the Dependency Injection series by Ashley Davis. Keep in mind the approach presented there is definitely more advanced.

Home screen

In this section we’ll implement a simple home screen. Create a new scene in your Scenes folder and call it “Home”. Add it to your Build Settings like we did before, make sure it’s at the start of the list.

For the background of our home screen (and our game over screen) I’ll be using the image that comes in Assets/Images. Feel free to use that or any other image. Create an Images folder in your project, and put the background image in there. The size of the image is 1024 x 576.

We’ll create a text field like before (which will automatically create a canvas). Inside this canvas, also create a new button (UI – Button) and a raw image (UI – Raw Image).

The order in which each UI element is rendered on the screen is that of the elements in the Hierarchy Window. If you want an element to appear on top of everything, move it all the way down. On the contrary, to have an element in the background, move it all the way up. We’ll make sure the raw image is in the background.

Select the Canvas, set the UI Scale Mode to Scale With Screen Size, which will make everything look small. Change the Reference Resolution to 1024 x 576.

Extend the corners of the raw image element to match those of the canvas. In the Inspector, select our background image on the Texture field (or drag the image file onto the RawImage object).

Rename the RawImage object to “Background”, the text to “Title” and the button to “Start Button”.

Change the font of Title to our Press Start font. Change the font size to 48, color white. Move it around so that it looks nicer. You can easily style the button too by expending it in the Hierarchy Window, and editing it’s child Text field just like we did with the title. This is what my home screen looks like:

The last step here is to make our button work and actually make the game start. Create an empty object called UI Manager. Create a new script named HomeUIManager and drag it on to the newly created object.

This new script will contain a single public method which we’ll call StartGame (not to be confused with Start):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HomeUIManager : MonoBehaviour
{

    // Start the game
    public void StartGame()
    {
        SceneManager.LoadScene("Level1");
    }
}

Select Start Button in the Hierarchy Window, find the component Button (Script) in the Inspector. Where it says On Click() click the plus button and find the public method we just created (StartGame). After this, your homescreen should work is you press play!

Game Over screen

For simplicity, we’ll make the Game Over screen will work very similarly to the Home screen. Start by creating a new scene called Game Over. As a starting point, I’d recommend copying and pasting all the objects from the Home scene. Rename the text to “Game Over”. Add the scene to the Build Settings as we’ve done with the previous scenes.

We’ll add 4 additional text labels. Give them style and text values as shown below (enter any number for the score and high score):

The following functionality needs to be implemented:

  • Restart the game when Play is pressed
  • Show the score and high score

For that, we’ll take a similar approach to what we did for the home screen. We already have a UI Manager object in our Hierarchy Window (provided you copied and pasted everything from the Home screen). We’ll use this object, but with a different script, so remove the HomeUIManager script component in the Inspector.

This new script will make use of the GameManager  object, which as we’ve seen keeps track of the score and high score, and already has a method to restart the game. Create a new empty object, name it Game Manager, and drag the GameManager script to it.

Create a new script called GameOverUIManager. This new class will have public variables so that we can pass on the text elements where we want to show the score and high score. Also, it will have a public method to restart the game, which we can use in our Play button.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameOverUIManager : MonoBehaviour {

    // Where the score value will be shown
    public Text score;
    
    // Where the high score value will be shown
    public Text highScore;

    // Run on the first frame
    void Start()
    {
        // Show the score and high score
        score.text = GameManager.instance.score.ToString();
        highScore.text = GameManager.instance.highScore.ToString();
    }

    public void RestartGame()
    {
        // Reset the game
        GameManager.instance.Reset();
    }
}

Go to your button, rename it to “Restart Button”, remove the previous method in the On Click section, and find the newly created RestartGame  public method.

You should be seeing zero values on the score and high score fields. Also, if you click on Play that should take you to Level 1.

The last piece of the puzzle is to actually send the player to Game Over, which we’ll do in PlayerController , upon collision with an enemy. Start by including the UnityEngine.SceneManagement  namespace so we can easily switch between scenes:

using UnityEngine.SceneManagement;

Then send to Game Over:

        else if (collider.gameObject.tag == "Enemy")
        {
            // Game over
            print("game over");

            SceneManager.LoadScene("Game Over");
        }

Finishing up

If you’ve followed along all the way here I have to say well done! We’ve already covered a lot of ground and all the concepts we’ve covered here apply to pretty much all games.

You are definitely on the right path if your goal is to make games with Unity.

The last part is to actually build your game, so that you can run it as a native application on your computer, whether you are on Windows, Mac or Linux (that is the magic of Unity!).

Build the game by going to Build Settings, selecting PC, Mac & Linux Standalone. I’ll select Windows as my target platform and x86 as the system architecture, then click Build and Run. Make sure all the scenes are showing under Scenes to Build.

We’ve built our game assuming a screen ratio of 16:9 (that is the screen ratio of the background image we are using), so we want to make sure only this ratio is supported. Otherwise, in some screens people might see the area outside of our background. Go to Player Settings, find Resolution and Presentation – Supported Aspect Ratios – uncheck all but 16:9.

Choose a destination and a name for the executable file (I’ve called mine game.exe). Choose a resolution and whether you want your game to be windowed or not. You can disable this window in Player Settings – Resolution and Presentation – Display Resolution Dialog.

And we are done! We can now play our newly created game. Good job making it all the way here!

Have you created anything after taking this tutorial? What other topics would you like us to cover?

Feel free to share it in the commenting area!

]]>
Best Beginner’s Online Coding Classes https://gamedevacademy.org/best-online-coding-classes/ Wed, 21 Jul 2021 10:17:48 +0000 https://gamedevacademy.org/?p=13599 Read more]]> Do you want to learn how to code?

Assuming the answer is yes – and assuming we don’t need to extol why coding is a fantastic skill to learn – the next obvious question is how? How does one learn how to code? Well, in our busy modern lives where going to physical classes is not always possible, many people have found the wonders of online coding classes. Everything from basic HTML & CSS, all the way to more difficult languages like C++ are being taught on the internet.

Given the plethora of resources available, though, choosing the best coding classes is a feat in and of itself. As such, to make this process a bit easier, we’ve compiled a list below of some of our recommendations for the best beginner’s level online coding classes. We’ve chosen a mix of languages and coding skills, so regardless of what you’re aiming for particularly, you should be able to find a class for you and learn coding skills to last you a lifetime!

Why Use Online Coding Classes

Before we jump into our list, let’s put on the brakes, as a lot of people are skeptical of online coding classes. I mean, is it really beneficial to learn coding online vs. going to a physical class? Well, let’s talk about some advantages online coding courses have.

Teacher surrounded by students and showing educational material on a tablet

  1. They’re generally lower in cost. Physical locations are expensive to maintain, from just maintaining the building itself to needing a lot of electricity. This is not to mention many institutions require a large staff for a physical location. All this maintenance, unfortunately, results in more costly coding courses in order for the institution to break even. For online coding courses though, there aren’t many similar fees. As such, these generally are much lower priced and affordable for most people (though this depends on the site and course author of course!)
  2. They can be done at your own pace. Due to the limitations of time and access, physical coding courses have to operate on a strict schedule in order to cater to as many students as possible. This means strict start and end times, strict deadlines, and so forth. Online coding courses don’t have any of these limitations. You can do them at whatever pace suits your learning style, life needs, and so forth. As such, this takes off a lot of the pressure that would otherwise be there. If you don’t understand something, you can take your time until you do!
  3. They can be done on-the-go. Unsurprisingly, physical location classes require you to physically be in one location. With online coding courses, though, all you need is the internet in many cases. This means you can learn at home, learn on the bus ride to work or school, practice at lunch, and beyond. These classes go with you – you don’t have to go with them. This offers an unparalleled ability to once again make them suit your schedule.
  4. They have a wider reach of topic. Since institutions have to suit a wide variety of students, they generally can’t cover every niche available with coding. As such, the topics they can teach are limited. Online coding courses don’t suffer these same consequences. There is always a teacher out there willing to explain just about any topic – whether that’s a super obscure computer science algorithm or a niche language only used by a few companies. In the end, you have the freedom to explore any topic that interests you and don’t just have to always go with the mainstream offerings.
  5. They offer more variability to suit your learning style. As online coding courses have the ability to be more numerous, this means there’s simply just more teachers. And more teachers means, naturally, there are more methods of teaching. Thus, it doesn’t matter if you’re someone who is a visual learner, someone who does better with word association, or someone who just memorizes hard cold facts. If one coding class doesn’t suit how you learn, there are plenty to explore until you find the one that clicks!

Now, onto the fun part: the best beginner’s online coding classes!

Woman sitting on some stairs looking at phone

Intro to Programming Bundle

Rather than a single coding class, the Intro to Programming Bundle offers six beginner-level coding courses on different topics. You will explore HTML, CSS, JavaScript, Python, Unity (and C# by association), Java, and C++. This covers all the basic realms of development: web development, Python development, game development, mobile development, and software development. Once again, these are also all beginner-level coding courses, so they all assume you’ve had absolutely no prior experience what-so-ever with any coding.

Why You Should Get it?

This bundle is a fantastic option if you’re actually not sure what area of coding you’re interested in. There are a lot of areas of development, and deciding on your first programming language is tough if you are hesitant to pick a single area. This bundle takes away that pressure and simply lets you explore what’s available and how each language plays a bigger role. In so doing, you can affordably find your niche from which you can pursue other online coding classes!

Length

As mentioned, this is a bundle, so the time for each coding class will vary. However, the entire bundle contains about 13 hours worth of video content.

Cost

The bundle is available through a subscription service that runs at $20/month or $168/annually.

Get the Intro to Programming Bundle

Screenshot of Android Studio with a color selection written in Java shown next to emulator

One-Hour Coder Academy

Similarly to the previous coding courses set, this is another collection of six different coding classes on different topics. While this set doesn’t cover anything related to game development, it does cover several of the same topics, including HTML, CSS, JavaScript, Python, Java, and C++. However, where this collection differs is that each coding class aims to be around 1 hour long. This means you get to learn at a bit more of a rapid pace, and solely focus on the coding fundamentals of each language.

Why You Should Get it?

If you’re short on time, this set of coding courses is well-suited to providing the necessary information without a lot of fluff. Given this is a set and the focus is on the coding fundamentals, you’ll get to explore things like variables, functions, and so forth over and over again – just in different languages. However, the benefit in this is it allows you to better absorb these foundations which are absolutely critical for all coding. So, not only do you learn multiple languages, but also gain an understanding of how each language uses the same principles. Plus, if you kind of know a language but need a good refresher, the quicker pace and shorter nature of these lessons will make your time a bit more worthwhile.

Length

Each coding class in this collection runs about 1 hour to 1 1/2 hours, giving a total of 8.3 hours of video.

Cost

The course is available through a subscription service that runs at $20/month or $168/annually.

Get the One-Hour Coder Academy

Screenshot of Java code example being run in VS Code Terminal

The Complete Python Programming Bundle

Once again, we have another set of multiple online coding classes. In this bundle’s case, the sole focus here is Python. However, this bundle goes a bit beyond just providing beginner-level information on the language (which it does do, so no prior experience is necessary). Instead, besides the language itself, this bundle also shows you beginner-level techniques for applying Python to games, data science, and machine learning. Thus, for a beginner-level set, this gives you an in-depth view not just into coding, but into some sub-specialties you might want to consider pursuing with Python.

Why You Should Get it?

If you’re interested in learning Python, this is about as comprehensive as you can get without going too far into any one Python-related topic. As such, not only do you get to learn Python from the ground up in a beginner-level way, but you’ll also explore the main areas in which Python is used for. Additionally, as this bundle is fairly extensive in the number of coding courses it offers, you’ll really get to develop a strong foundation – which can prepare you to even start jumping into more intermediate-level courses.

Length

While each coding class in the bundle differs in length, the entire collection has 15 hours worth of video content.

Cost

When on sale, you can get this entire bundle for as cheap as $25.

Get The Complete Python Programming Bundle

Showcase of image recognition training with Python

Intro to Game Development with Unity

As pretty clear from the title, this coding class dives into the basics of using the Unity game engine – one of the most popular game engine choices. The class focuses on two different aspects of game development with Unity. First, it dives into the basics of using the engine itself and manipulating objects. So you’ll learn key information about the UI as well as how to move objects, rotate them, and more. However, it also dives into the basics of using C# within Unity and allows you to explore variables, conditionals, and so forth – especially as it applies to Unity’s personal Scripting API. Thus, you’ll learn a well-rounded set of instructions that will help you start developing your own games.

Why You Should Get it?

When it comes to game engines, Unity is considered one of the two top contenders (the other being the Unreal Engine). Consequently, learning how to work with Unity can only benefit you if you’re aiming for a career or hobby in game development. This coding class, in particular, is simultaneously comprehensive in the basics of the engine, while not throwing you too far into the lion’s den. Besides video lessons, this coding class also comes with live coding demonstrations and quiz lessons, so you can test yourself at regular intervals to make sure the knowledge is sinking in. Overall, it is just a super beginner’s level course that just about anyone can do – even if they’ve never touched Unity in their entire life.

Length

This coding class has about 1.4 hours of video content.

Cost

The course is available through a subscription service that runs at $20/month or $168/annually. You can also obtain lifetime access to it for about $50.

Get Intro to Game Development with Unity

Balloon Popper Game being made with the Unity engine

Learn the GODOT Game Engine in 50 MINUTES

In this coding class, you’ll dive into the lesser-known but very powerful Godot engine. You’ll of course learn the basics of the engine and how the engine works – but you’ll do so in the context of setting up your very first prototype game: a platformer. Not only does it show you how to create a player character and the beginnings of a level, but it does so in a way that allows you to master some of Godot’s unique tools and its unique scripting language, GDScript.

Why You Should Watch it?

If you’ve never heard of Godot, Godot is a fantastic engine to start with for beginners. GDScript was made to mimic some of the best qualities of Python in terms of readability, and the engine has an easy-to-understand node architecture for development. As this coding class covers all of that from scratch, you’ll get a great fundamental understanding of how to use Godot to build your games. Plus, because this is framed in a practical sense of building a game, you can skip over learning the coding fundamentals for the millionth time and learn how to actually apply those fundamentals as a real game developer would.

Length

The video course runs about 50 minutes in length.

Cost

This course is absolutely free to watch via YouTube.

Watch the Learn the GODOT Game Engine in 50 MINUTES coding class

Platformer setup in the Godot engine

Learn Unreal Engine in 1 HOUR!

While Unity is great, Unreal Engine (as mentioned earlier), is another great game engine option for game development. This coding class covers just that and showcases the foundations of the Unreal Engine – how it works, how to manipulate objects in the scene editor, how to prepare the engine for games, and so forth. After this, it then explores the Blueprints Visual Scripting system, which allows you to code your game with visual blocks instead of having to code everything from scratch. That being said, you still learn important coding fundamentals like variables that will be needed in your game projects.

Why You Should Watch it?

If you want to make games but coding entirely from scratch just isn’t your thing, this coding class is fantastic. It shows you an alternative way to access the mechanics you’d normally access through coding, but in a way that is much easier than your traditional coding class. You’ll also still learn those essential foundations for coding, though – so if you want to switch to a language like C++, it is a much smoother transition. As this coding class also covers how to use the engine in the first place as well, you get a pretty comprehensive skill-set that will prepare you to start building your first games regardless of what kind of games they are.

Length

This video course lasts about 1 hour and 15 minutes.

Cost

This course is absolutely free to watch via YouTube.

Watch the Learn Unreal Engine in 1 HOUR! coding class

Conditionals demonstration with the Blueprints Visual Scripting system

HTML & CSS 101 – Web Development Fundamentals

This coding class takes a deep dive into HTML & CSS – core pillars that are absolutely needed for all web development. The video lessons are very comprehensive and cover just about all the foundations you’ll need for your web projects. You’ll start with the basics of HTML tags and how they’re used to structure web pages (so obviously, no experience here is required). It also covers a lot of necessary CSS fundamentals, including how to include CSS in your web project, how to actually target HTML elements to aesthetically change them, and beyond. In the end, it is a well-rounded resource that will allow you to expand your skills further.

Why You Should Get it?

The fact of the matter is, you need to understand HTML & CSS if you want to make websites – this is non-negotiable no matter what specialty you pursue in web development. As this coding class covers just about all the fundamentals you’ll need, though, it’s a great option where you can learn it all in one go. Additionally, as the lessons are broken down into small segments (each video is 10 minutes or less), you don’t get bombarded with information. You’ll learn each tag or rule step-by-step, making it easy to digest one web development element at a time.

Length

This course has about 2.1 hours of video content to explore.

Cost

This is course is available for free to anyone, though you do need to make an account on the website to access it.

Get HTML & CSS 101 – Web Development Fundamentals

CSS coding with demonstration

JavaScript 101 – First Programming Steps

As implied by the title, this coding class covers the language basics of JavaScript, which is used both for web development and HTML5 game development. The course does cover all the needed coding fundamentals like variables, functions, methods, and so forth, but it presents all the information as a story to make it both practical and personalized. Further, the course also introduces the concepts of using JavaScript to alter a web page, giving you a beginner’s level taste of where you can go with JavaScript.

Why You Should Get it?

Besides HTML & CSS, JavaScript is another critical language for web development – particularly as you start exploring extra functionality and backend APIs. So, for web developers out there, this is yet another crucial tool you’ll need. As for why this coding class in particular, though, this comes down to its presentation. As mentioned, the course does give you a taste in how JavaScript is used in web development, allowing you to take those first steps into turning the abstract into practical application. Beyond this, though, the course strives to tell a story at each fundamental juncture, allowing you to frame all the coding fundamentals in a way that might actually apply to real-life. Thus, the material just overall sticks better than your average class!

Length

This coding class contains about 2.2 hours of video content.

Cost

This is course is available for free to anyone, though you do need to make an account on the website to access it.

Get JavaScript 101 – First Programming Steps

JavaScript coding class showing multi-dimensional array challenge

Phaser 101 in 1 HOUR

Focusing on the HTML5 2D game framework of Phaser, this coding class teaches you some fundamental skills for making browser-based games. You’ll explore how, combined with a web server, you can use Phaser to render a number of objects to a browser screen – including multimedia objects like sprites. Using these multimedia elements, you’ll also learn how to work with Phaser and JavaScript to manipulate images in various ways, such as rotating them, growing them, and so forth.

Why You Watch Watch it?

Many Phaser tutorials out there jump straight into how to build a game without actually establishing much about the framework itself. This coding class takes the entirely opposite approach and focuses on the framework basics first and foremost – while also letting you explore just what it is capable of in terms of image manipulation. As such, if Phaser is of interest to you, or game development in general, this coding class is a great one in terms of just exploring how tools and coding come together to create functionality. Plus, you’ll still develop beginner-level foundations with practical application of JavaScript that you can use in other areas.

Length

This coding class is just a slight bit less than one hour.

Cost

This course is absolutely free to watch via YouTube.

Watch the Phaser 101 in 1 HOUR coding class

Phaser game project with simple game screen demonstration

Python 101 – Introduction to Programming

This coding class explores the coding fundamentals with the Python programming language – which is considered to be one of the most human-readable languages for beginners. You’ll learn to understand coding in terms of data storage & manipulation, control flow, and functions. You’ll also learn some useful tips on object-oriented computer programming, which is used throughout most development industries in terms of how programs are structured. That being said, it is all definitely at a beginner-level, so it is kept basic enough for anyone to understand.

Why You Should Get it?

Besides the sheer fact Python is a great beginner’s language, knowing the language prepares you to pursue a lot of fields like data science and machine learning. This coding class was painstakingly crafted to be as true to the statement “no experience necessary” as possible. Every fundamental taught is done at the most reasonable pace and in super, duper small chunks. As such, you aren’t getting bombarded with all loop types in one lesson or all operators. Everything is broken down and built around the beginner-level person, so it is a very hand-holding class that will walk you through everything with confidence and patience.

Length

This coding class has approximately 1.4 hours of video content.

Cost

This is course is available for free to anyone, though you do need to make an account on the website to access it.

Get Python 101 – Introduction to Programming

Python demonstration for tracking enemy positions

C++ Programming for Beginners

This coding class focuses on the C++ programming language, which is frankly one of the most difficult languages to learn. However, the class focuses on the fundamentals found in most languages first and foremost, so you’ll still get a beginner’s level education. That being said, the class does also cover some unique features of C++, such as vectors, so you will get the chance to see why this language is also very popular despite its difficulty. In addition, this coding class frames everything in the context of games, so you can once again see how practical application works from the abstract concepts covered.

Why You Should Get it?

While C++ has a difficult learning curve, it is also one of the most used languages in both software and game development – so learning it can’t steer you wrong. Where this coding class stands out from others is the framing, as mentioned above. Taking fundamentals from abstract to reality, especially with more unique features like vectors, is no easy task. As this course is framed around easy-to-understand game concepts, like inventories, it just makes the information stick a lot better. You don’t just learn the fundamentals, you see how they’re used in practice. And believe us, for a language like C++, getting past that realm of abstract is essential to using the language effectively!

Length

This coding class offers about 2.6 hours of video content.

Cost

The course is available through a subscription service that runs at $20/month or $168/annually. You can also obtain lifetime access to it for about $50.

Get C++ Programming for Beginners

C++ code demonstration for an inventory

Augmented Reality 101 – AR Foundation Basics

In this coding class, you’ll learn the foundations of coding for augmented reality with Unity. This class specifically focuses on Unity’s AR Foundation package API, which allows developers to make AR apps for both Android and iOS without the need to have separate SDKs. All this aside, rest assured this is a beginner-level class. You will learn not only the basics of AR itself, but how to build AR apps to your mobile device, add basic object spawning functionality, and more.

Why You Should Get it?

While this coding class does expect you to have some knowledge of Unity, unlike others on this list, it still gives you a great taste into AR technology without being overwhelming for a beginner. The focus here is mostly on getting an application up and running, which honestly, is half the battle. With the AR Foundation package, you don’t have to worry too, too much about device compatibility either. You can focus solely on learning how AR works in the first place, and worry about all the other details a bit later. As this app is very simple as well, you’ll get just enough foundations to start expanding your knowledge. So, overall, it’s just a very good entry-level introduction into augmented reality itself.

Length

This course is a little less than an hour of video content.

Cost

This is course is available for free to anyone, though you do need to make an account on the website to access it.

Get Augmented Reality 101 – AR Foundation Basics

Box in Unity scene editor for AR app

Learn VR Game Development in 2 Hours with Unity

As the title implies here, this coding class focuses on virtual reality and how you can develop games for the technology in Unity. The class covers a very robust set of topics related to it, from just getting a VR project setup in Unity all the way to how to prepare everything for different kinds of headsets. Additionally, the entire class is centered around making a demo project that transports the player around in a stationary experience, so you’ll learn by doing in this particular coding class.

Why You Should Watch it?

If you really just want to jump into things, this coding class does just that. While you do learn some of the necessary essentials for creating VR games in general, the class’s main focus is, at the heart, the project. So you don’t need to sift through hours of coding fundamentals – you’ll jump right into the meat of doing the thing you want to do: make VR games. That being said, the course is still beginner-friendly if you know your way around Unity, so it isn’t as advanced as you might fear! You’ll definitely be taught VR as if you’ve never touched it before, and you’ll gain some novel skills that are becoming big in all areas of the development industry!

Length

This coding class is a little less than 2 and 1/2 hours of video.

Cost

This course is absolutely free to watch via YouTube.

Watch the Learn VR Game Development in 2 Hours with Unity coding class

VR game demonstration in the Unity engine

Summary

We hope this list of best online coding classes helps you in your learning endeavors. There are a lot of ways to learn how to code, and we’ve only just scratched the surface here in terms of what is available learning-wise – especially if you want to dive deeper into computer science. That being said, coding courses are still a fantastic option and allow you to explore computer programming at a fraction of the cost of traditional schooling. So, we hope you try it out and see if one of the coding courses above helps the information click. Either way, we’re excited to see you taking these first steps, and we look forward to the projects you’ll make!

BUILD GAMES

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

]]>
Roblox Game Making: Create Your First Obstacle Course https://gamedevacademy.org/roblox-game-making-platformer-tutorial/ Wed, 16 Jun 2021 01:00:49 +0000 https://gamedevacademy.org/?p=13933 Read more]]> While it’s been around for a while, since 2006 to be specific, Roblox has skyrocketed in popularity in recent years. In turn, interest in Roblox game making has risen as well, and with the Roblox Studio engine, it’s more possible than ever to make your own games. With built-in publishing tools and multiplayer, meaning no networking code or server management on your part, it has also become a top choice for beginning game developers who want to focus on getting fun creations out to the public. How does one get started though? Well, in this tutorial, we’re not only going to show you the foundations of Roblox Studio, but help you start your Roblox game-making journey by building a game in a popular genre – obstacle courses.

Gif demonstration of a Roblox obstacle course

Project Files

You can download the .rbxl file here.

BUILD GAMES

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

Installing Roblox Studio

To create games in Roblox, we need to download the game engine: Roblox Studio. Go to https://www.roblox.com/create and click on the Start Creating button. If you don’t already have it installed, it will prompt you to do that.

Screenshot of the Roblox Studio website

Once Roblox Studio has been installed, we can open it up. Here, it will prompt you to log in. If you already have a Roblox account you can use that, but if you don’t you’ll have to create one.

roblox studio login screen

This will then take us to where we can create a new game. Click on the New tab and then double-click the Baseplate template to create it. We’re going to be basing our game of this template as it comes premade with a spawn point.

Roblox Studio templates with Baseplate selected

Editor Overview

Now we are in the editor. Roblox Studio is comprised of various different windows/panels. We can move them around, resize or remove them if not needed.

Roblox Studio Editor for a blank project

What I’m going to do, is go to the View tab at the top of the screen and disable the Toolbox and Terrain Editor windows so they are no longer in our editor. We don’t need these for the tutorial and it will clear our editor up.

Roblox Studio editor with various windows disabled

Let’s now go over the different windows and what they’re used for.

  • At the top of the screen, we have our main Toolbar. This is where we can change our tools, create models, play the game, change settings etc. It’s fairly general purpose.
  • On the left, we have the Toolbox. This is where we can import models and textures that other people have made and put them into our game.
  • On the right, we have the Explorer. This is a hierarchy of all the objects and parts in our game. As well as the services we can use.
  • Below that is the Properties window. When we select an object in the game, we can modify its properties and settings in this window.
  • Finally, in the center is our viewport into the game. This is a camera we can fly around and build our game.

Navigating the Game View

Right now, the camera is looking at the spawn point, which is sitting on top of our baseplate.

  • Holding down Right Mouse and moving the mouse around will rotate the camera.
  • While doing that, you can use the WASD keys to fly around.
  • and Q can be used to move up and down.

Let’s Begin!

Now let’s start to create our game. Like many other obstacle courses, we can’t have a floor otherwise the players can just run to the end. So we need to delete the baseplate. Over in the Explorer window, open up the Workspace by clicking on the arrow to the left. The Workspace contains all of the objects found in our game that the player can see, interact with, etc.

Select the Baseplate and delete it by clicking the Delete key on your keyboard.

Roblox Studio with the baseplate being deleted

Now we have no floor. But the sky looks a bit weird. Under the Lighting section, delete the Sky object as we need to reset it.

Roblox Studio with the Sky selected for deletion

With the sky deleted, hover over Lighting and click on the + icon. A window opens up and this allows us to create a new object to put into the Lighting section. Search for Sky and add that. You should see now that our sky looks like – a real sky.

Roblox Studio with Lighting selected in the Explorer

Testing the Game

As we create our game, we’ll want to test it out. To do this, go to the Test tab and click on the Play button (shortcut: F5).

Roblox Studio with the Text view open and play button circled

You’ll see your character load in and you can play the game like you would on Roblox. To stop playing, you can click on the Stop button (shortcut: ShiftF5).

Playing a game in Roblox Studio

You’ll notice that you spawn on the white object. This is our spawn point and all players who join the game will spawn here.

Moving Objects Around

Now let’s look at how we can move things around. In Roblox, all objects with physical properties are known as Parts. We currently have our spawn point, which is a part. You can click on it to select it. Over in the Model tab, we can select the Move tool to move the part around. You’ll see three colored arrows. Click and drag on these to move the object along that axis.

Moving parts with the Move tool in Roblox Studio

As well as moving objects, we can also Rotate and Scale them.

Rotating objects in Roblox Studio with the Rotate tool

Creating Our Obstacles

Let’s now create the obstacle course. In the Model tab, you’ll see the Part button. Click on the little arrow underneath it and select Sphere. This is going to create a new sphere part which we can move over to the left.

Roblox Studio with a Sphere created in the project

Let’s also scale it up.

Scaling the sphere in Roblox Studio with the Scale tool

Now by default, all new parts are not anchored. What this means, is that if we were to play the game now, the sphere would fall into the void. Since we want to jump on it, let’s anchor it. Select the sphere and over in the Properties window, find the Anchored property and enable it.

Anchoring the sphere in Roblox Studio

Now if we press play, you should be able to jump on the sphere.

We can also color the parts to make it look more appealing and less bland. Select the sphere and click on the Color dropdown. Here, we can choose from a range of different colors.

Roblox Studio with the Color Picker options window open

I’m going to choose black, so it stands out.

Roblox Studio with the sphere colored black

From here, create a few more spheres, continuously playing the game to make sure that the jumps are possible.

Creating multiple spheres in Roblox Studio project

Checkpoints

In an obstacle game, you don’t always want players to restart from the beginning when they fall. Placing checkpoints along the way is what we’re going to do next. First though, we need to modify our spawn point.

  1. Hover over Workspace, click on the + and create a new Folder.
  2. With the folder selected, go to the Properties window and change the Name property to Checkpoints, this will rename the folder.
  3. Rename the spawn point the Stage1, using the same method as above.
  4. Then click and drag the Stage1 object in the Explorer over the Checkpoints folder to add it.

Checkpoints folder add to the Roblox Studio project

Then we want to go down to the Teams folder. What we’re going to do is create a team for each checkpoint we have, so when a player dies, they will respawn on their teams checkpoint part. Create a new Team and call it Stage1 (it’s important that it’s named the exact same as the part). Down in the Properties window we also want to change the TeamColor. This has to be the exact same color as the spawn point part (Medium Stone Grey).

Stage 1 team in Roblox Studio

To make our checkpoint look cleaner, let’s open it up in the Explorer and delete the Decal object. This is the spiral texture.

Deleting the decal in Roblox Studio project

For the second checkpoint, we want to duplicate the Stage1 object (select it and click Ctrl + D).

  1. Move it over to the other side of the spheres.
  2. Rename it to Stage2.
  3. Change the color to red.

Creating stage 2 in Roblox Studio platformer project

Then down in the Teams folder, we want to create a new team.

  1. Rename it to Stage2.
  2. Change the TeamColor to the exact same as the stage 2 part color.

Creating team stage 2 in Roblox Studio project

For all of the Team objects, do the following:

  1. Enable AllowTeamChangeOnTouch.
  2. Disable Neutral.
  3. Set the TeamColor to that stage’s respective color (must be the exact same as that’s how the checkpoints are identified).

Roblox Studio Explorer and Properties for Stages

Now if we press play and reach the second stage, we will respawn there when we die.

Saving the Game

We’ve worked on our game for a bit now. How about saving our progress? Well, there are a few ways we can do this. If we click on File at the top-left corner of the screen, you’ll see we can save our game to a file, or to Roblox.

Roblox save to file options

Saving our game to file, will create a .rbxl file and store it somewhere on our computer. Saving our game to Roblox will do the same, but store the game on the Roblox servers so we can access it from any computer. You can choose which way you want to save. If you plan on saving to Roblox, then I recommend you also save to file.

Continuing the Obstacle Course

From here, continue to create checkpoints, add in more obstacles and create a fun game! Make sure to test it out along the way as every jump needs to be possible. Another thing: make sure that every new part you create is anchored. If you notice that some parts are missing or falling when you press play, then this may be the issue.

Roblox obstacle course level lay out

Moving Platforms

Let’s add some moving platforms to our obstacle course. These will be moving up and down and will require the player to time their jumps. I’m going to create a new part and call it MovingPlatform. Position it where you want the lowest possible point for the platform to move from. Make sure to also anchor this part!

Roblox Studio process for moving platforms

Then, we’re going to hover over the part, click on the + and add in a new Script. What’s a script? Basically it’s a file where we can write code. This code can then apply logic to the game. In our case, we want this code to move the platform up and down.

Roblox studio with Script file open

Roblox uses Lua as its programming language. If this is your first time ever coding, do know that we’re not going into detail on each element – rather focusing on just the things we need. If you are familiar with programming, then Lua may be easy to get the hang of if you have Python experience.

You’ll notice by default, this script file has one line of code.

print("Hello world!")

This will basically log the message “Hello world!” to the console when we play the game.

What we’re going to do, is delete this line and start from a blank file.

Blank script file for Roblox Studio project

To begin we need to get the part that this script is attached to (the MovingPlatform part). To do this, we’re going to add in this line of code. It is creating a variable (piece of data we can reference) called part and assigning it to the script’s parent, which is the MovingPlatform part.

local part = script.Parent

Then we need to access the tween service. This basically allows us to create smooth movement.

local tweenService = game:GetService("TweenService")

Next, we need to create a new tween. This tween will contain the information of how we want to move the platform. Duration, easing style, easing direction, number of times (-1 means forever), whether it reverses or not and the wait time.

local tweenInfo = TweenInfo.new(3.0, Enum.EasingStyle.Linear, Enum.EasingDirection.Out, -1, true, 0.2)

When we have multiple platforms, we’ll want them to move at different times. To do this, we can delay the final part of the code by using wait(). Wait basically pauses the script for a set amount of time. In our case, we’re going to be choosing a random wait time between 0 and 4.

wait(math.random(0, 4))

Finally, we need to apply this tween to the part and play it.

local tween = tweenService:Create(part, tweenInfo, {Position = part.Position + Vector3.new(0, 20, 0)})
tween:Play()

Here’s the final set of code.

local part = script.Parent
local tweenService = game:GetService("TweenService")

local tweenInfo = TweenInfo.new(3.0, Enum.EasingStyle.Linear, Enum.EasingDirection.Out, -1, true, 0.2)

wait(math.random(0, 4))

local tween = tweenService:Create(part, tweenInfo, {Position = part.Position + Vector3.new(0, 20, 0)})
tween:Play()

Now we can go back to our baseplate tab and play the game!

Going back to the baseplate game in Roblox Studio

You should see the platform move up and down.

Moving platform up and down in Roblox Studio

Next, we can duplicate the moving platform like so. Also adding in a new checkpoint.

Multiple moving platforms and final checkpoint in Roblox Studio obstacle course project

Now when you press play, you should see that the platforms are moving differently from one another.

Playtesting Roblox obstacle course for moving platforms

Publishing Your Game

Right, we’re done! Now it’s time to publish our game on Roblox for all to play. Go to File > Publish to Roblox As… This will open up the publish window. Click on the Create new game… button.

Publish window for Roblox Sutdio with "Create new game..." selected.

Fill out all the information on the next screen, then click Create.

Basic Info window for Roblox Studio game

Next, we need to make it public or for friends only. Go to File > Game Settings… and navigate to the Permissions tab. Here, we can choose who can play our game. I selected Public, then clicked Save to save the changes.

Permissions options with Public circled for Roblox Studio game

Whenever you make changes you want to publish again, you’ll need to go File > Publish to Roblox.

Conclusion

And there we go! You have successfully created your first game for Roblox. Share the game around and see if other people can beat it!

However, we encourage you to not stop here. Many types of games are popular with Roblox game making, and you can really spread your wings in terms of what you can achieve! We encourage you to learn more about Roblox Studio and what you can do with the engine. Additionally, by learning the Lua scripting language more thorough, you can not only make more complex and unique games, but have skills that go beyond just Roblox. Thank you for following along, and I wish you the best of luck with your future Roblox games.

]]>