Explore Free Retro Game Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Fri, 07 Apr 2023 08:33:06 +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 Retro Game Tutorials – GameDev Academy https://gamedevacademy.org 32 32 How to Create a Race Car in Unity https://gamedevacademy.org/race-car-unity-tutorial/ Fri, 07 Apr 2023 08:33:06 +0000 https://gamedevacademy.org/?p=19898 Read more]]> Racing games are a classic, whether found on modern consoles or in old-timey arcades.

Regardless of their rendition though, one of the few fundamentals they have in common is their cars. Cars are one of the key buildings blocks, and will probably be one of the first things you want to learn to make your own racing game.

In this tutorial, we’re going to cover just that: building a race car using the popular Unity Engine. We’ll be covering everything from setting up movement with Unity’s Input System, to adding physics for sterring.

Let’s dive in!

Project Files

You can download a copy of the source code files for the project done in this tutorial here. Note that this tutorial requires good familiarity with Unity and C# scripting.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Setting Up the Input System

After creating a new 3D project in Unity, we need to install the Input System Package first of all.

Installing Input System Package

Let’s open up the Package Manager window (Window > Package Manager):

Accessing Package Manager from the Window tab in Unity

Select Packages > Unity Registry to access all the Unity packages:

Select Unity Registry to get to the Input System Package

And install the Input System:

Installing Input System in Unity

Creating Input Actions

Once the Input System Package is installed, we can right-click on the Project window (inside the Assets folder) and click on Create > Input Actions.

Creating Input Actions in Unity

We’re going to call this “PlayerControls” and double-click to open it up:

Rename it to "PlayerControls"

This is going to open up the Input Actions window. On the left panel, we can create an Action Map by clicking on the + button. This is basically a category for all your different inputs:

Creating an Action Map in Unity

We’ll call the first action map “Main“, and create a new Action connected to the “Main” action map. Actions define what we want to do when pressing certain keys:

Creating our first action map named "Main" in Unity

So first of all, we’re going to create an action called “Move“:

Create an action called "Move" to the 'Main' action map

Then we want to go over to the Properties panel and set the Action type to Button:

Setting the Action Type to be Button

Now we can click on Binding > Path > Listen and then press any button on the keyboard to register and bind it with our Input Action:

Click on Listen to bind a key to the new action Press the desired button to bind it to the Move action

Alternatively, if we want our movement to be represented with a Vector2 value between -1 and 1, we can change the Action Type to Value and set the Control Type to Vector2:

Representing the action with a Vector2 in Unity

In that case, we can determine which direction the player needs to move in by adding 2D Vector Composite to the Move action. This will create a new binding with four children bindings called Up, Down, Left, and Right:

Adding a 2D Vector Composite to bind the 4 possible moving directions

Bindings for moving up, down, left, and right

To bind a key to an input action, click on Path > Listen, and hit the corresponding keyboard button (W, A, S, and D):

Binding keys to each of the directions

Make sure that all input actions are assigned a key:

Basic move actions for the Unity Input System

Additional Inputs

What if we want to plug in a controller for our second player? In that case, we can click on the + (Add) button next to the Actions heading, and then click on Add Binding:

Including additional inputs for a second player

If you have Xbox or PlayStation controllers, you can choose the Gamepad option instead of the Keyboard for binding the keys:

Binding the keys with the Gamepad option, instead of using keyboard entries

For specific gamepad controls’ information, refer to the documentation:  https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Gamepad.html

You can also separate the window for each type of controller by adding a new Control Scheme:

Adding a new Control Scheme to separate the inputs from each type of controller

By clicking on the Control Scheme dropdown at the top-left corner, you can switch over to different control schemes (Keyboard/Controller/Joystick/etc).

If you have multiple control schemes, you need to make sure that each key binding is used in the appropriate control scheme. This can be done by enabling/disabling the checkboxes under ‘Use in Control Scheme‘:

Checking that the bindings are coherent for each control scheme in Unity

Refer to the table below to complete all control schemes:

Accelerate Up Arrow [Keyboard]
Accelerate Button South [Gamepad]
Turn Left Stick/X [Gamepad]
Turn Left/Right Arrow (-/+) [Keyboard]

Control schemes for our game in Unity

Make sure to click Save Asset before closing the window:

Click on "Save Asset" before closing the window

Car GameObject

To set up a new GameObject for our car, let’s create a new empty GameObject called “Car”. Then we want to add a Rigidbody component for the physics, a Sphere Collider for the collision, and a Player Input for detecting inputs:

Setting up a new GameObject for the car

We also need to attach a new C# script, which will detect inputs and enable us to drive the car around. Let’s call this script “CarController”:

Attaching a new script to our car

Next, we’re going to right-click on our Car object and click on Create Empty to create a new empty child object. This is going to allow our car model to maintain upright rotation (instead of spinning around with the parent Car object):

CarModel as a child of the Car object

The car models can be found in the Project Files link above, and you can import them into a Assets > Models > Cars folder. Let’s drag it into our CarModel object:

Importing the model to our Unity project

Ensure that the model‘s Y-rotation is correctly facing forward by setting it to 180. Also, adjust the Sphere Collider to match the model’s size. The model should be positioned at the bottom of the sphere:

Adjusting the model to be at the bottom of the Sphere Collider

Remember to assign a ‘Player’ tag to the car object too, as follows:

Assigning the Player tag to the car in Unity

Rigidbody Settings

The Rigidbody component controls the car’s position through physics simulation. By default, it is set to be pulled downward by gravity and to react to collisions with other objects.

To simulate a realistic car’s behavior, we’re going to adjust these properties:

  • Drag: 0 → 0.5 (This acts as wind resistance/ground friction in forwarding momentum)
  • Angular Drag: 0.05 → 3 (Same as Drag, but for rotation)
  • Interpolate: None → Interpolate (Smoothes out the effect of running physics at a fixed frame rate)

Car's Rigidbody settings

Feel free to tweak the values as you like.

Camera Settings

The Main Camera in the scene will be moving based on the car’s position and rotation, keeping a certain distance away from the car. We’re going to call this ‘Camera Offset‘.

First, we need to create an empty object that will contain our camera as a child object:

Placing the camera as a child object

For the Main Camera to orbit around the car, we need to have the parent container object located at the exact same position as the car. We can copy the position values of the car by Right-click on Transform > Copy Component:

Copying the position values of the Car object

Then, we can go to the Main Camera object and right-click on Transform > Paste Component Values:

Pasting over the Component Values of the Car's position

Now you can tweak the position and rotation values of the Main Camera to set the default camera angle:

Main Camera now rotates around the car

Make sure that you have assigned the Input Action Asset and the Main Camera to the Player Input component:

Player Input component settings in Unity

Car Controller Script

Once you have the script attached to our Car GameObject, let’s start editing the script:

The Car Controller script has to be attached to the Car GameObject

Creating Variables

To control our car, we need to define some variables. Take a look at the list below for a brief description of each variable:

  • Acceleration (float) – the rate at which the car accelerates forward
  • Turn speed (float) – the rate at which the car rotates left and right when steering
  • Car model (Transform) – the reference to the car’s model, which we want to keep stationary in terms of rotation.
  • Start Model Offset (Vector3) – The distance offset from the car model to its parent object to update the model’s position on every frame.
  • Ground Check Rate (float) – The rate of raycasting in order to determine if the car is on the ground.
  • Last Ground Check Time (float) – The time the previous ground check was performed.
  • Current Y Rotation (float) – The current Y rotation of the car model.
  • Accelerate Input (bool) – Input state for acceleration
  • Turn Input (float) – Input state for turning
  • Rigidbody
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class CarController : MonoBehaviour
{
    public float acceleration;
    public float turnSpeed;

    public Transform carModel;
    private Vector3 startModelOffset;

    public float groundCheckRate;
    private float lastGroundCheckTime;

    private float curYRot;

    private bool accelerateInput;
    private float turnInput;

    public Rigidbody rig;
}

Once all the variables are declared, we can save the script, go back to the editor, and set up the public variables’ values in the Inspector:

Setting up the public variables' values in Unity's Inspector

Detecting Inputs

Since we’re using UnityEngine.InputSystem, we can create some functions that we can connect to the Player Input component attached to the Car object.

The name of the function can be whatever you want, but it should have a parameter of InputAction.CallbackContext.

For example, let’s start working on the function to be called when the Accelerate input is detected:

// called when we press down the accelerate input
public void OnAccelerateInput (InputAction.CallbackContext context)
{
}

Here, the “context” sends over all the information regarding the input, such as if the button has just been pressed down, the duration of holding down the key, etc.

By checking if its phase is InputActionPhase.Performed, we can ensure that the key is being pressed down:

// called when we press down the accelerate input
public void OnAccelerateInput (InputAction.CallbackContext context)
{
    if(context.phase == InputActionPhase.Performed)
        accelerateInput = true;
    else
        accelerateInput = false;
}

Similarly, we can read the turn input as a float value (negative = left, positive = right):

// called when we modify the turn input
public void OnTurnInput (InputAction.CallbackContext context)
{
    turnInput = context.ReadValue<float>();
}

Let’s save the script, and bind the input functions with specific keys. Go to the Player Input component, assign the Car object to the input events (under Events > Main), and select both OnAccelerateInput and OnTurnInput:

Event settings for the Player Input in Unity

Settings for the Player Input component in Unity

Now, these event functions are connected to the keys which we have mapped in our Input Action Asset.

Defining Offset

Right now, we have the car’s model attached under its parent Car GameObject. In order to fix the model’s position at the current offset from the parent, we’re going to store the initial localPosition in a Vector3 variable, called startModelOffset.

So let’s define the Start() function to set the startModelOffset‘s value:

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

public class CarController : MonoBehaviour
{
    ...
    private Vector3 startModelOffset;
    void Start ()
    {
        startModelOffset = carModel.transform.localPosition;
    }
}

We can then define the FixedUpdate function to add force to our car. Remember, FixedUpdate runs 60 times per second consistently (whereas Update runs every single frame), and hence it is useful for physics calculations.

Here, we’re only adding force into the forward direction if we have ‘accelerateInput‘ as true:

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

public class CarController : MonoBehaviour
{
    ...
    void FixedUpdate ()
    {
        if(accelerateInput == true)
        {
            rig.AddForce(carModel.forward * acceleration, ForceMode.Acceleration);
        }
    }
}

Our car model should only rotate around the y-axis based on our turn input. We can directly replace the y-rotation to reflect our turnInput and turnSpeed:

Our car model should only rotate around the y-axis Using our turn inputs for the rotation of the car

So let’s manually update the rotation inside Update:

public class CarController : MonoBehaviour
{
    ...
    void Update ()
    {
        curYRot += turnInput * turnSpeed * Time.deltaTime;

        carModel.position = transform.position + startModelOffset;
        carModel.eulerAngles = new Vector3(0, curYRot, 0);
    }

}

Our final code looks like this:

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

public class CarController : MonoBehaviour
{
    public float acceleration;
    public float turnSpeed;
    
    public Transform carModel;
    private Vector3 startModelOffset;

    public float groundCheckRate;
    private float lastGroundCheckTime;

    private float curYRot;

    private bool accelerateInput;
    private float turnInput;

    public Rigidbody rig;

    void Start ()
    {
        startModelOffset = carModel.transform.localPosition;
    }

    void Update ()
    {
        curYRot += turnInput * turnSpeed * Time.deltaTime;
        
        carModel.position = transform.position + startModelOffset;
        carModel.eulerAngles = new Vector3(0, curYRot, 0);
    }

    void FixedUpdate ()
    {
        if(accelerateInput == true)
        {
            rig.AddForce(carModel.forward * acceleration, ForceMode.Acceleration);
        }
    }

    // called when we press down the accelerate input
    public void OnAccelerateInput (InputAction.CallbackContext context)
    {
        if(context.phase == InputActionPhase.Performed)
            accelerateInput = true;
        else
            accelerateInput = false;
    }

    // called when we modify the turn input
    public void OnTurnInput (InputAction.CallbackContext context)
    {
        turnInput = context.ReadValue<float>();
    }
}

And that’s that for this tutorial!

Conclusion

Congratulations on concluding the tutorial!

You now have a car GameObject inside Unity that you can accelerate forward and steer left and right! You’ve also already tackled setting up Rigidbody, Colliders, and Player Input components, aside from using models and scripting in Unity.

As for the next step, well you’re ready to continue developing your project further! You could start by creating the scenery and road environment, or even start considering splitting the screen to add multiplayer, for instance. There is no limit what you can do with these foundations – so don’t be afraid to experiment!

We wish you the best of luck implementing your future games!

Want to learn more about racing games in Unity? Try our complete Build an Arcade Kart Racing Game course.

BUILD GAMES

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

]]>
Best Racing Game Tutorials – Cars, Tracks, and More https://gamedevacademy.org/best-racing-game-tutorials/ Wed, 25 Jan 2023 09:24:47 +0000 https://gamedevacademy.org/?p=15460 Read more]]> Nowadays there’s a huge variety of racing games out there, dating back to the first Mario Kart and coming all the way to the modern ones we have today, such as Need For Speed, Forza Motorsport, Forza Horizon, Gran Turismo, and many others. As racing games are classic, they can be very nostalgic for those who grew up playing their disparate genres, in particular arcade, kart, and simulation.

The coolest thing about coding racing games is that they are easy to start with, not to mention that we have various famous engines to suit the needs of all different levels of the required programming for such a task. That being the case, we can have a basic 2D racing game ready in about an hour and a multiplayer more advanced version in a day. So, let us now take a look at the best racing game tutorials you can follow to get you easily into coding your own games with the Unity, Unreal, Roblox, and Godot engines.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

How to Make a Driving/Racing Game in Unity

This tutorial from Jimmy Vegas teaches you how to create a driving and racing game from scratch with Unity, a very popular and powerful cross-platform engine for the creation of 2D and 3D games. Here, you’ll learn how to implement a car selection screen in order to be able to customize your car, along with the development of interesting features such as a minimap, lap count and timer, cutscenes and music, unlockables, plus a cash system. You can also choose the track you want to race in, as well as have different game modes you can play.

Topics Covered:

  • Project creation
  • Textures and car import
  • Camera angles
  • Lap count
  • Lap timer
  • Minimap
  • Car selection
  • Game modes 
  • Cutscenes
  • Race positions
  • Saving and credits

Duration: 7 hours of video training

Access now: How to Make a Driving/Racing Game in Unity

Build an Arcade Kart Racing Game – Unity

This Unity tutorial by Zenva Academy walks you through the creation of an arcade kart racing game in a style similar to Mario Kart, where players race around a track both on keyboard and controller until they complete a few laps within the specified window of time. The instructor uses Unity’s Input System to create a split-screen multiplayer game mode that you can play with your friends.

Topics Covered:

  • Project setup
  • Creating the track and environment
  • Kart movement and position
  • Camera controls
  • Split-screen multiplayer implementation
  • Countdown and winning conditions

Duration: 2 hours of video training

Access now: Build an Arcade Kart Racing Game – Unity

How to Create a 2D Arcade Style Top-Down Car Controller in Unity

With this tutorial series by Pretty Fly Games, you’ll see how to apply the physics needed for a top-down 2D racing game, including how to implement smooth movement and drift to your car. The instructor also goes over how to apply different controller inputs to each car making local multiplayer available for the game. In addition, you’ll learn how to alter the user interface to have touch input implemented for your mobile devices as well.

Topics Covered:

  • Basic game design
  • Sound effects
  • Checkpoints and laps
  • Leaderboard interface
  • Car selection
  • Local multiplayer
  • Mobile touch input

Duration: 6 hours of video training

Access now: How to Create a 2D Arcade Style Top-Down Car Controller in Unity

Unity3D Top-Down Racing Game Tutorial

In this tutorial by Stevie ROF, you’ll build a top-down racing game in Unity where you complete laps by controlling your car with the mouse cursor. Stevie explains the logic behind how to make the car drift around the custom racetrack by going over each step he’s taking with you as he’s coding.

Topics Covered:

  • Setting up the environment
  • Mouse pointer control
  • Drift implementation

Duration: 1 hour of video training

Access now: Unity3D Top-Down Racing Game Tutorial

3D Racing Game in Unity

In this Unity tutorial series from pablos lab, you’ll go over customizing and adding collision to a 3D model car to make it drift and speed on the racetrack. The presenter will teach you how to add a screen for the car selection, how to implement an AI controller for the car, show the speedometer for your car, include animations and effects such as the drifting smoke, and much more.

Topics Covered:

  • Map import into Unity
  • Camera and animation
  • Wheel colliders
  • Vehicle customization and selection screen
  • Speedometer
  • AI system
  • Drift controller
  • Adding the drift smoke effect

Duration: 4.5 hours of video training

Access now: 3D Racing Game in Unity

Low Poly Racing Game with Unity and Blender

This series from Imphenzia covers the creation of a low poly racing game with Unity that uses Blender for the modeling of the racetrack and objects of the game scene. Blender is a free and open-source graphics software used for designing animations, artworks, and 3D models.

You’ll be guided through the whole process of the game’s racetrack and visual elements making, the exporting of the models from Blender to be imported into Unity, along with all the scripting needed for the colliders’ logic, wheels, steering, checkpoints, lap system, and even best and last time tracking.

Topics Covered:

  • Importing the car model to Blender
  • Racetrack design in Blender
  • Shortcuts for the tools in Blender
  • Terrain blueprint and decoration
  • Exporting the track model from Blender to import into Unity
  • Colliders scripting in Unity
  • Checkpoints implementation
  • Lap count and timer
  • Best and last lap times

Duration: 3 hours of video training

Access now: Low Poly Racing Game with Unity and Blender

Creating a Car Game in Unreal Engine 4

In this tutorial series, Unreal Joe presents his way of designing a car game with Unreal Engine in a very easy-to-understand manner. Unreal Engine is used by many AAA game companies and also by indie developers, being a real-time 3D creation platform with photorealistic rendering and lifelike animations. Joe goes through the creation of the racetrack and landscape to menu implementation, level selection, and vehicle speedometer and sound in this quick yet very focused series.

Topics Covered:

  • Importing the car model
  • Making the track and a pitstop
  • Creating a landscape
  • Pause menu
  • Level selection
  • Speedometer
  • Adding vehicle sound

Duration: 1.5 hours of video training

Access now: Creating a Car Game in Unreal Engine 4

Create a mobile racing game in Unreal Engine

Here, Sir_Fansi Gamedev walks you through a simple project using Unreal Engine to have a racing game running on your mobile device. The instructor creates all the necessary blueprints, respawning function for the car when it gets stuck, and a checkpoint system. Moreover, he goes over the implementation of the AI logic for the other cars in the game too while continuously testing that everything still works.

Topics Covered:

  • Setting up the project
  • Creating the racetrack
  • Respawning the car
  • AI implementation for the other cars in the game
  • Checkpoint system

Duration: 30 minutes of video training

Access now: Create a mobile racing game in Unreal Engine

Fully Drivable Kinematic Car from Scratch – Unreal Engine 5 Tutorial

In this tutorial, you’ll follow Marco Ghislanzoni as he creates a kinematic car from scratch in Unreal Engine 5. He shows all the mechanics and physics you’re going to need to have a fully drivable car, testing it with you along the way. He also includes in-car camera view as well as the steering wheel animation for a more dynamic game experience.

Topics Covered:

  • Car and racetrack setup
  • Creating the car blueprint
  • Steer events
  • Adjusting the driving speed
  • Adding camera controls
  • Collision handling
  • Testing the car mechanics

Duration: 1 hour of video training

Access now: Fully Drivable Kinematic Car from Scratch – Unreal Engine 5 Tutorial

How to Make a Roblox Racing Game

Although older, this video series from Roblox gets us through the basics of building the car and racetrack in Roblox Studio, movement scripting, car respawning, the implementation of checkpoints along the game track, and ultimately the game loop logic with the Lua programming language.

Topics Covered:

  • Creating the car
  • Designing the racetrack
  • Adding checkpoints
  • Game loop
  • Building a lobby

Duration: 4 hours of video training

Access now: How to Make a Roblox Racing Game

Create Your Own Racing Game – Roblox

In this tutorial from AstrophsicaDev, the instructor shows how you can use a racing kit he made himself inside Roblox to make your own racing game by adding your own touch to the scenery and making your customized version of the game. He gives you all the instructions on how to arrange the commands for the lights and barriers spread throughout the track so you can choose your own setup.

Topics Covered:

  • Adding racing kit to Roblox
  • Custom kart
  • Safety lights
  • Starting lights
  • Kart spawn
  • Collision
  • Publishing the game

Duration: 1 hour of video training

Access now: Create Your Own Racing Game – Roblox

Godot Recipe: 3D Arcade-Style Car

Finally, we have this tutorial from KidsCanCode that uses a rigid body sphere as the basis for what will become the car object of the game, demonstrating a very simple way of implementing a 3D arcade-style car game in Godot. Godot is a free 2D and 3D, cross-platform, and open-source game engine. In this video, the instructor shows how to configure the invisible sphere that is being used as the car so that it steers, takes the turns, and goes up ramps as expected.

Topics Covered:

  • Adding a rigid body sphere to the track
  • Placing a car mesh at the location of the sphere
  • Physics configs to better control the car
  • Aligning the car with inclined road surfaces

Duration: 15 minutes of video training

Access now: Godot Recipe: 3D Arcade-Style Car

Extra Links

Unity Game Development Mini-Degree

If you’re interested in making your own games in Unity and getting to know it in depth, Zenva Academy has a Mini-Degree specifically focused on game development with Unity. Created by Unity certified developers, you’ll be creating games of the most varied genres, varying from first-person shooter to RPG, through a curriculum that counts on 25 different projects for you to hone your game designing skills using this widely known game engine.

Topics Covered:

  • Unity setup
  • Navigating the Unity Editor
  • Scripting in C#
  • Designing of level selection screens
  • 2D and 3D game techniques
  • Game audio effects
  • Procedural terrain generation
  • Cinematic cutscenes
  • Testing and debugging

Duration: 36 hours of video training

Access now: Unity Game Development Mini-Degree

Roblox Kart Racer Development Log

This video tracks the development of a kart racing game made with Roblox by Fluffmiceter based on the Mario Kart idea of throwing objects to the other karts, having to jump over obstacles or contour them, taking speed boosts, spinning around, etc. You can see the new features being added over time as well as the progress made with the camera controls, car movement, drifting, and animation effects. You can also spot some game testing too. This log is great for showing the whole evolution and making off of the scenery and the game physics and logic with each new version of the game.

Duration: 7 minutes

Access now: Roblox Kart Racer Development Log

I Made a Racing Game in 3 Days – Unreal Engine

This video from Fat Dino presents to you his journey of making a racing game in 3 days with Unreal Engine 4. He starts by modeling a simple car object then adding wheels to it, making the car move, then steering the wheels correctly by fixing them to the car with bolts.

The presenter will take you through his personalized car game design with the possibility of using weapons to target the other cars in the game and explode them. He also implements some AI for these other cars, allows car bumps, designs a nice island map for the scenery, and even creates a basic starting menu plus a car selection screen for the game. At last, he plays it with lap count and background music to a really satisfying feel of the final version of his racing game.

Duration: 12 minutes

Access now: I Made a Racing Game in 3 Days – Unreal Engine

Summary

With all that, you have plenty of resources to draw ideas from and get inspired by to start a racing game of your own! We hope you have enjoyed reading this article and that you have learned a lot from it.

There’s a myriad of options available in terms of game engines and styles that you can adhere to. It’s up to you to choose whichever suits you better or try different things until you find the one you like the most. In the end, regardless of your choice, what you can look forward to is having fun implementing it your way!

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.

]]>
Create a Basic Multiplayer Game in Phaser 3 with Socket.io – Part 1 https://gamedevacademy.org/create-a-basic-multiplayer-game-in-phaser-3-with-socket-io-part-1/ Mon, 19 Dec 2022 12:57:07 +0000 https://gamedevacademy.org/?p=6753 Read more]]> In this multipart tutorial, we will be using Phaser 3 and Socket.io to create a simple multiplayer game. For our multiplayer game, we will follow the client-server game architecture. If you are not familiar with the client-server game architecture, the client is responsible for displaying the game to the player, handling the player’s input, and for communicating with the server. The server, on the other hand, is responsible for broadcasting that data to each client.

The goal of this tutorial is to teach you the basics of creating a multiplayer game. You will learn how to:

  • Setup a Node.js and Express server that will render our game and communicate with it.
  • Setup a basic Phaser 3 game that will act as our client.
  • Use Socket.io to allow the server and the client to communicate.

Course Files and Versions

You can download all of the files associated with the source code for part one here.

At the time this tutorial was written, the following versions were used. You may need to use these versions to have the same results from this tutorial.

  • Node.js: 10.13.0
  • JSDOM: 13.0.0
  • Express: 4.16.4
  • Socket.IO: 2.1.1
  • Datauri: 1.1.0

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Tutorial Requirements

For this tutorial, we will be using Node.js and Express to create our server. We will also be using NPM to install the required packages we need for the server to run. In order to follow along with this tutorial, you will need to have Node.js and NPM installed locally, or you will need access to an environment that already has them installed. We will also be using the Command Prompt (Windows) / Terminal (Mac) to install the required packages, and to start/stop our Node server.

Having a prior experience with these tools is a plus, but it is not required for this tutorial. We will not be covering how to install these tools as the focus of this tutorial is making a game with Phaser. The last thing you will need is an IDE or Text Editor for editing your code.

To install Node.js, click the link here: and choose the LTS version. You can download and use the current version with this tutorial, however, the LTS version is recommended for most users. When you install Node.js, NPM will also be installed on your computer. Once you have these tools installed, you can move on to the next part.

As a last note, we do not recommend this tutorial be used by educators looking for new classroom resources. Instead, try Zenva Schools which features K12-friendly courses on web development and game development – plus classroom management features.

Setting up the server

The first thing we are going to do is create a basic Node.js server that will serve our game files. To get started, create a new folder on your computer, it can be called anything you want. Then navigate inside this folder and create a new file called server.js. Open up server.js and add the following code to it:

var express = require('express');
var app = express();
var server = require('http').Server(app);

app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

server.listen(8081, function () {
  console.log(`Listening on ${server.address().port}`);
});

In the code above we:

  • referenced the express module, which is a web framework that will help us render our static files.
  • created a new instance of express and called it app.
  • supplied the app to the HTTP server, which will allow express to handle the HTTP requests.
  • updated the server to render our static files using express.static built-in middleware function in Express.
  • told the server to serve the index.html file as the root page.
  • had the server start listening on port 8081.

Before we can run the server, we will need to install the required modules for the server. Open your terminal/command prompt, and navigate to your project folder. Once there you will need to run the following command: npm init -f. This will create a package.json file in your project folder. We will use this file to keep track of all the packages that our project depends on.

Now, we will install express. In your terminal run the following command: npm install –save express. This will create a folder called node_modules in your project folder, and by adding the –save flag to the command, npm will save this package in our package.json file.

Setting up the client

With the basic server code finished, we will now work on setting up our client-side code. In your project folder, create a new folder called public. Any file we put in this folder will be rendered by the server that we set up. So we will want to put all of our static client-side files in this folder. Now inside the public folder, create a new file called index.html. Open up index.html and add the following code to it:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
    </head>

    <body>
        <script src="//cdn.jsdelivr.net/npm/phaser@3.0.0/dist/phaser.min.js"></script>
        <script src="js/game.js"></script>
    </body>

</html>

In the code above, we set up a simple HTML page and we referenced two JavaScript files, phaser.min.js (the phaser game framework) and game.js (our Phaser game code). Back in the public folder, create a new folder called js , and in this folder create a new file called game.js. Open up game.js and add the following code to it:

var config = {
  type: Phaser.AUTO,
  parent: 'phaser-example',
  width: 800,
  height: 600,
  physics: {
    default: 'arcade',
    arcade: {
      debug: false,
      gravity: { y: 0 }
    }
  },
  scene: {
    preload: preload,
    create: create,
    update: update
  } 
};

var game = new Phaser.Game(config);

function preload() {}

function create() {}

function update() {}

Let’s review the code we just added:

  • We created the configuration that will be used for our Phaser game.
  • In the config object, in the type field, we set the renderer type for our game. The two main types are Canvas and WebGL. WebGL is a faster renderer and has better performance, but not all browsers support it. By choosing AUTO for the type, Phaser will use WebGL if it is available, otherwise, it will use Canvas.
  • In the config object, the parent field is used to tell Phaser to render our game in an existing <canvas>  element with that id if it exists. If it does not exists, then Phaser will create a <canvas>  element for us.
  • In the config object, we specify the width and height of the viewable area of our game.
  • In the config object, we enabled the arcade physics that is available in Phaser, and we set the gravity to 0.
  • In the config object, we embedded a scene object which will use the preload, update, and create functions we defined.
  • Lastly, we passed our config object to Phaser when we created the new game instance.

With our basic client-side code setup, we will now test our server and make sure everything is working correctly. Back in the terminal/command prompt, run the following command: node server.js and you should see the following line appear Listening on 8081. Now, if you open up your web browser and navigate to http://localhost:8081/, you should see a black box on the web page, and if you open the console in the developer tools, you should see a log with the version of Phaser your game is running.

Blank Phaser 3 game running in Google Chrome

Adding Socket.IO

With our server now rendering our game, we will now work on adding Socket.IO to our game. If you are not familiar with Socket.IO, it is a JavaScript library that enables real-time, bi-directional communication between web clients and servers. To use Socket.IO, we need to update our client and server code to enable the communication between the two.

Back in your terminal, run the following command: npm install –save socket.io. If your server is still running, you can either: open a new terminal window and run the code in your project folder, or stop the server (CTRL + C) and then run the command. This will install the Socket.IO node package and save it in our package.json file.

Now, in server.js add the following code below the var server = require(‘http’).Server(app); line:

var io = require('socket.io').listen(server);

Then add the following code above the server.listen line:

io.on('connection', function (socket) {
  console.log('a user connected');
  socket.on('disconnect', function () {
    console.log('user disconnected');
  });
});

In the code above we:

  • referenced the socket.io module and had it listen to our server object.
  • added logic to listen for connections and disconnections.

Next, we will update the client side code to include the Socket.IO library. Open up index.html and add the following line at the top of the <body> element:

<script src="/socket.io/socket.io.js"></script>

Then, open up game.js and add the following line inside the create function:

this.socket = io();

Now, if you start the server back up again, and refresh your game in your browser, you should see the user connected/disconnected messages in your terminal.

Console information denoting users connecting and disconnecting

Adding players – Server

Now that we have our socket connections setup, we can move on to adding players to our game. In order to keep all of the player’s games in sync, we will need to notify all players when a user connects or disconnects from the game. Also, when a new player connects we will need a way to let the player know of all the other players in the game. To do all of this we will need to store some player data, and we will use the socket connections to send messages to our players.

For this tutorial, we will store the player data in memory on the server. Normally, we would want to store this data in some type of database, that way it would be persistent, and if the server fails, we could easily recover the state of the game.

In server.js add the following line below the io variable:

var players = {};

We will use this object to keep track of all the players that are currently in the game. Next, in the callback function of the socket.io connection event add the following code below the console.log(‘a user connected’); line:

// create a new player and add it to our players object
players[socket.id] = {
  rotation: 0,
  x: Math.floor(Math.random() * 700) + 50,
  y: Math.floor(Math.random() * 500) + 50,
  playerId: socket.id,
  team: (Math.floor(Math.random() * 2) == 0) ? 'red' : 'blue'
};
// send the players object to the new player
socket.emit('currentPlayers', players);
// update all other players of the new player
socket.broadcast.emit('newPlayer', players[socket.id]);

Let’s review the code we just added:

  • When a player connects to the web socket, we store some player data in the players object and we use the socket.id as the key.
  • We are storing the rotation, x, and y position of the player, and we will use this to control were we create sprites on the client side, and use this data to update all players games. We also store the playerId so we can reference it in the game, and we added a team attribute that will be used later.
  • We used socket.emit and socket.broadcast.emit to emit an event to the client side socket. socket.emit will only emit the event to this particular socket (the new player that just connected).  socket.broadcast.emit will send the event to all other sockets (the existing players).
  • In the currentPlayers event, we are passing the players object to the new player. This data will be used to populate all of the player sprites in the new player’s game.
  • In the newPlayer event, we are the passing the new player’s data to all other players, that way the new sprite can be added to their game.

When a player disconnects, we need to remove that player’s data from our players object, and we need to emit a message to all other players about this user leaving, that way we can remove that player’s sprite from the game.

In the callback function of the socket.io disconnect event add the following code below the console.log(‘user disconnected’); line:

// remove this player from our players object
delete players[socket.id];
// emit a message to all players to remove this player
io.emit('disconnect', socket.id);

Your server.js file should look like the following:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);

var players = {};

app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  console.log('a user connected');
  // create a new player and add it to our players object
  players[socket.id] = {
    rotation: 0,
    x: Math.floor(Math.random() * 700) + 50,
    y: Math.floor(Math.random() * 500) + 50,
    playerId: socket.id,
    team: (Math.floor(Math.random() * 2) == 0) ? 'red' : 'blue'
  };
  // send the players object to the new player
  socket.emit('currentPlayers', players);
  // update all other players of the new player
  socket.broadcast.emit('newPlayer', players[socket.id]);

  // when a player disconnects, remove them from our players object
  socket.on('disconnect', function () {
    console.log('user disconnected');
    // remove this player from our players object
    delete players[socket.id];
    // emit a message to all players to remove this player
    io.emit('disconnect', socket.id);
  });
});

server.listen(8081, function () {
  console.log(`Listening on ${server.address().port}`);
});

Conclusion

With our server code for adding players in place, this brings part one of this tutorial to an end. In part two we wrap up our multiplayer game by:

  • Adding the client side logic for adding players to our game.
  • Adding logic for player input.
  • Adding collectibles for the players to collect.

I hoped you enjoyed part one of this tutorial and found it helpful.

Note that if you feel a bit out of debt, don’t be afraid to explore some basic web development courses first for individuals or even for teachers to use in the classroom.

BUILD GAMES

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

]]>
How to Create a Multiplayer Game in Unity https://gamedevacademy.org/how-to-create-a-multiplayer-game-in-unity/ Mon, 19 Dec 2022 09:13:56 +0000 https://gamedevacademy.org/?p=4819 Read more]]> In this tutorial, we are going to build a simple demo to learn how to use Unity multiplayer features. Our game will have a single scene where we will implement a multiplayer Space Shooter. In our demo multiple players will be able to join the same game to shoot enemies that will be randomly spawned.

In order to follow this tutorial, you are expected to be familiar with the following concepts:

  • C# programming
  • Using Unity Editor, such as importing assets, creating prefabs and adding components

We’ll be using an asset known as Mirror. This is an expansion on Unity’s default networking system, adding in new features and fixing a large amount of bugs and problems.

Before You Begin

This tutorial assumes basic familiarity with Unity. If this is your first time into the world of Unity, we first suggest learning through some of our free Unity tutorials or through some amazing online courses.

For teachers wanting to incorporate Unity into the classroom or into school-related activities, Zenva Schools is also an option. This platform offers Unity courses for classroom use alongside useful features such as course plans, classroom management tools, reporting, and more.

Creating Project and Importing Assets

Before starting to read the tutorial, you need to create a new Unity project and import all sprites available through the source code. In order to do that, create a folder called Sprites and copy all sprites to this folder. Unity Inspector will automatically import them to your project.

However, some of those sprites are in spritesheets, such as the enemies spritesheets, and they need to be sliced. In order to do that, we need to set the Sprite Mode as Multiple and open the Sprite Editor.

Importing sprite assets.

In the Sprite Editor (shown below), you need to open the slice menu and click in the Slice button, with the slice type as automatic. Finally, hit apply before closing.

Unity sprite editor.

We also need to import the Mirror asset. Go to the Asset Store (Window > Asset Store) and download “Mirror”.

Downloading Mirror from the Asset Store.

Source Code Files

You can download the tutorial source code files here.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Background canvas

The first thing we are going to do is creating a background canvas to show a background image.

We can do that by creating a new Image in the Hierarchy, and it will automatically create a new Canvas (rename it to BackgroundCanvas).

In the BackgroundCanvas, we need to set its Render Mode to be Screen Space – Camera (remember to attach your Main Camera to it). Then, we are going to set its UI Scale Mode to Scale With Screen Size. This way the Canvas will appear in the background, and not in front of the other objects.

Creating the background canvas game object.

In the BackgroundImage we only need to set the Source Image, which will be the space one.

Creating the background image with Unity's UI.

Try running the game now and you should see the space background in the game.

Background star image.

Network Manager

In order to have a multiplayer game, we need a GameObject with the NetworkManager and NetworkManagerHUD components, so let’s create one.

Network manager using Unity's networking framework and Mirror.

This object will be responsible for managing for connecting different clients in a game and synchronizing the game objects among all clients. The Network Manager HUD shows a simple HUD for the players to connect to a game.

For example, if you play the game now, you should see the following screen:

What the game looks like right now.

In this tutorial we are going to use the LAN Host and LAN Client options. Unity multiplayer games work in the following way: first, a player starts a game as host (by selecting LAN Host). A host works as a client and a server at the same time. Then, other players can connect to this host by as clients (by selecting LAN Client). The client communicates with the server, but do not execute any server only code. So, in order to test our game we are going to open two instances of it, one as the Host and another as the Client.

However, you can not open two instances of the game in the Unity Editor. In order to do so, you need to build your game and run the first instance from the generated executable file. The second instance can be run from the Unity Editor (in the Play Mode).

In order to build your game you need to add the Game scene to the build. So, go to File -> Build Settings and add the Game scene to build. Then, you can generate and executable file and run it by clicking on File -> Build & Run. This will open a new window with the game. After doing that, you can enter Play Mode in the Unity Editor to run the second instance of the game. This is what we are going to do every time we need to test a multiplayer game.

Unity build settings.

Ship Movement

Now that we have the NetworkManager, we can start creating the game objects which will be managed by it. The first one we are going to create is the player ship.

For now, the ship will only move horizontally in the screen, with its position being updated by the NetworkManager. Later on, we are going to add to it the ability to shoot bullets and receive damage.

So, first of all, create a new GameObject called Ship and make it a prefab. The figure below shows the Ship prefab components, which I will explain now.

Player ship object with Unity mirror networking components.

In order to a game object to be managed by the NetworkManager, we need to add the NetworkIdentity component to it. In addition, since the ship will be controlled by the player, we are going to set the Local Player Authority check box for it.

The NetworkTransform component, by its turn, is responsible for updating the Ship position throughout the server and all the clients. Otherwise, if we’ve moved the ship in one screen, its position wouldn’t be updated in the other screens. NetworkIdentity and NetworkTransform are the two components necessary for multiplayer features. Enable Client Authority on the NetworkTransform component.

Now, to handle movement and collisions, we need to add a RigidBody2D and a BoxCollider2D. In addition, the BoxCollider2D will be a trigger (Is Trigger set to true), since we don’t want collisions to affect the ship physics.

Finally, we are going to add a MoveShip script, which will have a Speed parameter. Other scripts will be added later, but that’s it for now.

The MoveShip script is very simple, in the FixedUpdate method we get the movement from the Horizontal Axis and set the ship velocity accordingly. However, there are two very important network-related things that must be explained.

First, typically all Scripts in a Unity game inherits MonoBehaviour to use its API. However, in order to use the Network API the script must inherit NetworkBehaviour instead of MonoBehaviour. You need to inlcude the Networking namespace (using UnityEngine.Networking) in order to do that.

Also, in a Unity multiplayer game, the same code is executed in all instances of the game (host and clients). To let the players to control only their ships, and not all ships in the game, we need to add an If condition in the beginning of the FixedUpdate method checking if this is the local player (if you’re curious on how the game would work without this If condition, try removing it. When moving a ship in a screen, all ships should move together).

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

public class MoveShip : NetworkBehaviour 
{
    [SerializeField]
    private float speed;

    void FixedUpdate () 
    {
        if(this.isLocalPlayer) 
        {
            float movement = Input.GetAxis("Horizontal");	
            GetComponent<Rigidbody2D>().velocity = new Vector2(movement * speed, 0.0f);
        }
    }
}

Before playing the game, we still need to tell the NetworkManager that the Ship prefab is the Player Prefab. We do that by selecting it in the Player Prefab attribute in the NetworkManager component. By doing so, everytime that a player starts a new instance of the game, the NetworkManager will instantiate a Ship.

Setting the network manager player prefab.

Now you can try playing the game. The ship movement should be synchronized between the two instances of the game.

Game scene showing two blue space ships

Spawn Positions

Until now all ships are being spawned in the middle of the screen. However, it would be more interesting to set some predefined spawn positions, which is actually easy to do with Unity multiplayer API.

First, we need to create a new Game Object to be our spawn position and place it in the desired spawn position. Then, we add the NetworkStartPosition component to it. I’m going to create two spawn positions, one in the coordinate (-4, -4) and the other one in the coordinate (4, -4).

Spawn position object with a network start position.Start position object with a NetworkStartPosition component.

Now we need to define how the NetworkManager will use those positions. We do that by configuring the Player Spawn Method attribute. There are two options there: Random and Round Robin. Random means that, for each game instance, the manager will choose the player start position at random among the spawn positions. Round Robin means it will go sequentially through all spawn positions until all of them have been used (for example, first SpawnPosition1 then SpawnPosition2). Then, it starts again from the beginning of the list. We are going to pick Round Robin.

Setting the player spawn method to round robin in the network manager.

By now you can try playing the game again and see if the ships are being spawned in the correct positions.

Game scene with blue space ships farther apart

Shooting Bullets

The next thing we are going to add in our game is giving ships the ability fo shooting bullets. Also, those bullets must be synchronized among all instances of the game.

First of all, we need to create the Bullet prefab. So, create a new GameObject called Bullet and make it a prefab. In order to manage it in the network, it needs the NetworkIdentiy and NetworkTransform components, as in the ship prefab. However, once a bullet is created, the game does not need to propagate its position through the network, since the position is updated by the physics engine. So, we are going to change the Network Send Rate in the Network Transform to 0, to avoid overloading the network.

Also, bullets will have a speed and should collide with enemies later. So, we are going to add a RigidBody2D and a CircleCollider2D to the prefab. Again, notice that the CircleCollider2D is a trigger.

Bullet object with the physics and networking components.

Now that we have the bullet prefab, we can add a ShootBullets script to the Ship. This script will have as parameters the Bullet Prefab and the Bullet Speed.

Attaching the shoot bullets script to the ship prefab.

The ShootBullets script is also a NetworkBehaviour, and it is shown below. In the update method, it is going to check if the local player has pressed the Space key and, if so, it will call a method to shoot bullets. This method will instantiate a new bullet, set its velocity and destroy it after one second (when the bullet has already left the screen).

Again, there are some important network concepts that must be explained here. First, there is a [Command] tag above the CmdShoot method. This tag and the “Cmd” in the beginning of the method name make it a special method called a Command. In unity, a command is a method that is executed in the server, although it has been called in the client. In this case, when the local player shoots a bullet, instead of calling the method in the client, the game will send a command request to the server, and the server will execute the method.

Also, there is call to NetworkServer.Spawn in the CmdShoot method. The Spawn method is responsible for creating the bullet in all instances of the game. So, what CmdShoot does is creating a bullet in the server, and then the server replicates this bullet among all clients. Notice that this is possible only because CmdShoot is a Command, and not a regular method.

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

public class ShootBullets : NetworkBehaviour
{
    [SerializeField]
    private GameObject bulletPrefab;

    [SerializeField]
    private float bulletSpeed;

    void Update () 
    {
        if(this.isLocalPlayer && Input.GetKeyDown(KeyCode.Space)) 
        {
            this.CmdShoot();
        }
    }

    [Command]
    void CmdShoot ()
    {
        GameObject bullet = Instantiate(bulletPrefab, this.transform.position, Quaternion.identity);
        bullet.GetComponent<Rigidbody2D>().velocity = Vector2.up * bulletSpeed;
        NetworkServer.Spawn(bullet);
        Destroy(bullet, 1.0f);
    }
}

Finally, we need to tell the network manager that it can spawn bullets. We do that by adding the bullet prefab in the Registered Spawnable Prefabs list.

Adding the bullet prefab to the network manager's registered spawnable prefabs.

Now, you can try playing the game and shoot bullets. Bullets must be synchronized among all instances of the game.

Unity Game scene with two blue spaceships and a bullet

Spawning Enemies

The next step in our game is adding enemies.

First, we need an Enemy prefab. So, create a new GameObject called Enemy and make it a prefab. Like ships, enemies will have a Rigidbody2D and BoxCollider2D to handle movements and collisions. Also, it will need a NetworkIdentity and NetworkTransform, to be handled by the NetworkManager. Later on we are going to add a script to it as well, but that’s it for now.

Enemy prefab with Mirror and Unity's networking components.

Now, let’s create a GameObject called EnemySpawner. The EnemySpawner will also have a NetworkIdentity, but now we are going to select the Server Only field in the component. This way, the spawner will exist only in the server, since we don’t want enemies to be created in each client. Also, it will have a SpawnEnemies script, which will spawn enemies in a regular interval (the parameters are the enemy prefab, the spawn interval and the enemy speed).

Enemy spawner object which spawns enemy prefabs.

The SpawnEnemies script is shown below. Notice that we are using a new Unity method here: OnStartServer. This method is very similar to OnStart, the only difference is that it is called only for the server. When this happens, we are going to call InovkeRepeating to call the SpawnEnemy method every 1 second (according to spawnInterval).

The SpawnEnemy method will instantiate a new enemy in a random position, and use NetworkServer.Spawn to replicate it among all instances of the game. Finally, the enemy will be destroyed after 10 seconds.

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

public class SpawnEnemies : NetworkBehaviour 
{
    [SerializeField]
    private GameObject enemyPrefab;

    [SerializeField]
    private float spawnInterval = 1.0f;

    [SerializeField]
    private float enemySpeed = 1.0f;

    public override void OnStartServer () 
    {
        InvokeRepeating("SpawnEnemy", this.spawnInterval, this.spawnInterval);
    }

    void SpawnEnemy () 
    {
        Vector2 spawnPosition = new Vector2(Random.Range(-4.0f, 4.0f), this.transform.position.y);
        GameObject enemy = Instantiate(enemyPrefab, spawnPosition, Quaternion.identity) as GameObject;
        enemy.GetComponent<Rigidbody2D>().velocity = new Vector2(0.0f, -this.enemySpeed);
        NetworkServer.Spawn(enemy);
        Destroy(enemy, 10);
    }
}

Before playing the game, we need to add the Enemy prefab to the Registered Spawnable Prefabs list.

Adding the enemy prefab to the network manager's registered spawnable prefabs list.

Now you can try playing the game now with enemies. Notice that the game still doesn’t have any collision handling yet. So you won’t be able to shoot enemies. This will be our next step.

Unity game scene with spaceships and green enemies

Taking Damage

The last thing we are going to add to our game is the ability to hit enemies and, unfortunately, to die to them. In order to keep this tutorial simple, I’m going to use  the same script for both enemies and ships.

The script we are going to use is called ReceiveDamage, and it is shown below. It will have as configurable parameters maxHealth, enemyTag and destroyOnDeath. The first one is used to define the initial health of the object. The second one is used to detect collisions. For example, the enemyTag for ships will be “Enemy”, while the enemyTag for enemies will be “Bullet”. This way, we can make ships colliding only with enemies, and enemies colliding only with bullets. The last parameter (destroyOnDeath) will be used to determine if an object will be respawned or destroyed after dying.

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

public class ReceiveDamage : NetworkBehaviour 
{
    [SerializeField]
    private int maxHealth = 10;

    [SyncVar]
    private int currentHealth;

    [SerializeField]
    private string enemyTag;

    [SerializeField]
    private bool destroyOnDeath;

    private Vector2 initialPosition;

    // Use this for initialization
    void Start () 
    {
        this.currentHealth = this.maxHealth;
        this.initialPosition = this.transform.position;
    }

    void OnTriggerEnter2D (Collider2D collider) 
    {
        if(collider.tag == this.enemyTag) 
        {
            this.TakeDamage(1);
            Destroy(collider.gameObject);
        }
    }

    void TakeDamage (int amount) 
    {
        if(this.isServer) 
        {
            this.currentHealth -= amount;

            if(this.currentHealth <= 0) 
            {
                if(this.destroyOnDeath) 
                {
                    Destroy(this.gameObject);
                } 
                else 
                {
                    this.currentHealth = this.maxHealth;
                    RpcRespawn();
                }
            }
        }
    }

    [ClientRpc]
    void RpcRespawn () 
    {
        this.transform.position = this.initialPosition;
    }
}

Now, let’s analyze the methods. In the Start method, the script sets the currentHealth to be the maximum, and saves the initial position (the initial position will be used to respawn ships later). Also, notices that there is a [SyncVar] tag above the currentHealth attribute definition. This means that this attribute value must be synchronized among game instances. So, if an object receives damage in one instance, it will be propagated to all of them.

The OnTriggerEnter2D method is the one responsible for handling collisions (since the colliders we added were configured as triggers). First, we check if the collider tag is the enemyTag we are looking for, to handle collisions only against objects we are looking for (enemies against ships and bullets against enemies). If so, we call the TakeDamage method and destroy the other collider.

The TakeDamage method, by its turn, will be called only in the server. This is because the currentHealth is already a SyncVar, so we only need to update it in the server, and it will be synchronized among the clients. Besides that, the TakeDamage method is simple, it decreases the currentHealth and checks if it is less than or equal to 0. If so, the object will be destroyed, if destroyOnDeath is true, or it the currentHealth will be reset and the object will be respawned. In practice, we will make enemies to be destroyed on death, while ships will be respawned.

The last method is the respawn one. Here we are using another multiplayer feature called ClientRpc (observe the [ClientRpc] tag above the method definition). This is like the opposite of the [Command] tag. While commands are sent from clients to the server, a ClientRpc is executed in the client, even though the method was called from the server. So, when an object needs to be respawned, the server will send a request to the client to execute the RpcRespawn method (the method name must start with Rpc), which will simply reset the position to the initial one. This method must be executed in the client because we want it to be called for ships, and ships are controlled only by players (we set the Local Player Authority attribute as true in the NetworkIdentity component).

Finally, we need to add this script to both the Ship and Enemy prefabs. Notice that, for the ship we need to define the Enemy Tag as “Enemy”, while for the Enemy this attribute value is “Bullet” (you also need to properly define the prefabs tags). Also, in the enemy prefab we are going to check the Destroy On Death attribute.

Finishing off the player ship object.

Finishing the enemy prefab.

Now, you can try playing the game shooting enemies. Let some enemies hit your ships to see if they’re being correctly respawned as well.

Conclusion

And this concludes this tutorial! While small, we now have a nifty multiplayer game to work with. However, you don’t have to stop here! You consider improving this project by adding sounds, or maybe even making a procedurally generated map for more endless amounts of fun. Either way, this project is sure to make a great addition to any coding portfolio!

You can also choose to expand your Unity knowledge with online courses on other topics such as making RPGs, FPS games, and much more. For classrooms, Zenva Schools also offers a great selection of Unity courses suitable to classrooms and with expansive topics on other genres – including VR.

We hope you’ve learned a lot here, and we wish you the best of luck with your future game projects!

BUILD GAMES

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

]]>
Make Games without Coding – Free Unreal Engine Ebook https://gamedevacademy.org/make-games-without-coding-free-unreal-engine-ebook/ Mon, 28 Dec 2020 01:22:48 +0000 https://gamedevacademy.org/?p=2044 Read more]]> We are excited to announce our latest eBook: Unreal Engine Game Development for Beginners

Authored by Unreal Engine expert Daniel Buckley, this eBook explores all there is to know about getting started with Unreal Engine development. You’ll learn not only how to work with the foundations of the engine itself, but also develop several projects from scratch including an FPS game, an action RPG, a road-crossing game, a platfromer, and a puzzle-like game! In addition, you’ll do all this while using the Blueprints Visual Scripting system – meaning no prior coding knowledge is required or needed to create your game projects!

Whether you’ve always wanted to learn Unreal Engine or want to start putting knowledge into practice, this eBook will help you gain the in-demand skills necessary to start building your dream game projects!

Download the eBook here

]]>
Creating an Arcade-Style Game in the Unreal Engine https://gamedevacademy.org/arcade-game-unreal-engine-tutorial/ Wed, 10 Jun 2020 01:00:36 +0000 https://gamedevacademy.org/?p=12063 Read more]]> Introduction

Complex games can be a lot of fun, but sometimes all players want to do is sit back and relive the retro days where simple mechanics and goals were the reigning champs.  As a developer, not only might you want to create your own retro, arcade-style types of games (with some modern flair), but it can also be a great beginner’s project to start your game development skills!

As such, in this tutorial, we’ll be creating a road-crossing arcade game in the Unreal Engine. The game will feature a player controller, coins, cars, and an end goal – capturing the sorts of straight-forward mechanics you’d expect.  Additionally, we’ll be working heavily with Unreal Engine’s unique Blueprinting system, so no coding from scratch is necessary!

If this is your first time using the Unreal Engine, we recommend you follow our intro to Unreal Engine tutorial first, as this one won’t be going over the basics of the engine itself.

GIF of road-crossing style game in Unreal Engine

BUILD GAMES

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

Project Files

For this project, we’ll be needing some 3D models made in MagicaVoxel.

You can also download the compete project with all the blueprints, levels, settings and models.

Creating the Project

To begin, create a new project (no starter content needed). Then we’re going to create three new folders in the Content Browser.

  • Blueprints
  • Levels
  • Models

Unreal Engine Content Browser

Next, save the open level to the Levels folder as MainLevel.

We’ll be using some pre-made 3D models from MagicaVoxel, so download the included assets (top of the tutorial) and drag the contents inside of the Models folder, into the Content Browser in our Models folder. Like so:

Unreal Engine Content Browser with game project assets added

Creating the Player

Now we can create our player. This player will be able to move forwards, left and right. To begin, we need to setup our key bindings. Go to the Project Settings window (Edit > Project Settings…) and navigate to the Input tab. We want to create three new action mappings.

  • Move_Forward = W
  • Move_Left = A
  • Move_Right = D

Unreal Engine Project Settings window

Back in the level editor, we can navigate to our Blueprints folder and create a new blueprint for our player. Make it’s parent class a Pawn and call it Player.

Player blueprint created in Unreal Engine

Open it up and we can begin.

First, create a new Static Mesh component.

  • Set the Static Mesh to Player
  • Set the Location to 50, 50, -50
  • Set the Rotation to 90, 0, -90
  • Set the Scale to 50, 50, 50
  • (not pictured) Disable Generate Overlap Events

Player overview in Unreal Engine

Next, create a Capsule Collider component as a child of the static mesh.

  • Set the Location to 0.96, -1.58, -1.0
  • Set the Rotation to 90, 0, 0
  • Set the Capsule Half Height to 0.5
  • Set the Capsule Radius to 0.2
  • Enable Simulation Generates Hit Events
  • Set the Collision Presets to Trigger

Player in Unreal Engine with Details window open

Finally, we have the camera setup. Create a new Spring Arm component as the child of static mesh. This component will hold our camera in place, even if we’re rotating.

  • Set the Socket Offset to 100, 0, 0
  • Set the Target Offset to 0, 227, 820

Then, create a Camera component as a child.

  • Set the Rotation to 0, -65, -40
  • Set the Field Of View to 50

Unreal Engine camera added to project

Let’s now go back to the level editor and in order to play as the player, we need to create a game mode blueprint.

Unreal Engine MyGameMode blueprint added to Content Browser

Open it up and all we need to do, is set the Default Pawn Class to our Player blueprint.

Unreal Engine with Default Pawn Class set to Player

Save and compile it. Back in the level editor, go to the World Settings panel and set the GameMode Override to our new game mode.

Unreal Engine World Settings window

Now if you press play, you’ll see the player appearing with the camera above them.

Moving the Player

Back in the Player blueprint, we can begin to implement the movement. First, we’ll need to create the variables.

  • TargetPos (Vector)
  • CanMove (Boolean)
  • Score (Integer)

Click Compile and set some default values.

  • CanMove = true

Unreal Engine with various Components added to blueprint

In the Event Graph, we can begin by resetting the player position. The Target Pos variable is where the player is moving to, so we’ll set it to our position first.

Unreal Engine Event Graph for player

Next, we’ll need to do pretty much the same thing for moving forward, left and right. To bypass just having three copies of the same code, we’re going to create a new function called TryMove. Create a new input for the function called Direction and make that of type Vector.

What we’re doing here, is checking if we can move. If so, add the direction to our TargetPos and then disable can move. But we want to be able to move eventually, so we’re going to call a function with a delay. The EnableCanMove function is what we’ll call after 0.3 seconds.

Unreal Engine Blueprinting logic for a Timer and movement

Let’s now create that EnableCanMove function. All we’re doing here is enabling the can move function.

Unreal Engine Enable Can Move node

Back in the main event graph, let’s now setup our movement input to call the TryMove function. Make sure to fill in the respective Direction inputs.

Unreal Engine logic for player trying to move

Next, we need to actually move the player. So every frame (event tick node), we’re going to trigger the Move Component To node which moves a component to the requested position.

Unreal Engine Event Graph that moves player to position

You can now press play and test it out!

Level Layout

Before we continue with the rest of the game’s systems, let’s create our level. So in the level editor begin by deleting the floor object.

Then, in the Models/Ground folder, drag in the Tile_Ground model.

  • Set the Location to -50, 50, -110
  • Set the Rotation to 90, 0, 0
  • Set the Scale to 50, 50, 50

Unreal Engine with tile mesh added for level

Combining the ground and road tiles, create a layout like the one below.

Tile combination in Unreal Engine to create road layout

Collectable Coins

When playing the game, players can collect coins to increase their score. Create a new blueprint (parent class of Actor) and call it Coin.

Coin blueprint added in Unreal Engine Content Browser

All we’re going to do component wise, is create a new Static Mesh component.

  • Set the Static Mesh to Coin
  • Set the Location to 2.6, -18.0, -97.0
  • Set the Rotation to 90, 0, 0
  • Set the Scale to 50, 50, 50
  • Enable Simulation Generates Hit Events
  • Set the Collision Presets to Trigger

Overview of coin object in Unreal Engine

Create a new variable of type Float and call it RotateSpeed. Compile and set the default value to 90.

Unreal Engine with RotateSpeed added to Components for coin

In the event graph, we’re first going to set it up so the coin rotates over time. We’re multiplying by the delta seconds so that the coin rotates in terms of degrees per second and not degrees per frame. This will make it the same across any frame rate.

Logic for Coin spin in Unreal Event Graph

Next, we need to add the score to the player when they collect the coin. First, go to the Player blueprint and create a new function called AddScore.

  • Create an input for the function called ScoreToAdd of type Integer

This function will just add to the existing score.

Unreal Engine with AddScore script added to Blueprint

Back in the Coin blueprint, let’s create the logic so that when the player collides with the coin, we add to their score and get destroyed.

Collision logic for player and coin in Unreal Engine project

In the level editor now, we can drag in the coin blueprint and position it where we want. If you press play and collect the coin, you should see that it gets destroyed.

Coin blueprint added to Unreal Engine arcade game

We can also then add in the rest of the coins.

Unreal Engine project with several coins added

Creating the Cars

The cars are going to be the player’s main obstacle. Hitting them will cause the game to restart.

Create a new blueprint (parent class of Actor) and call it Car. Open it up and we’ll start by creating a static mesh component.

  • Set the Static Mesh to Car
  • Set the Location to 75, -37, -100
  • Set the Rotation to 90, 0, 180
  • Set the Scale to 50, 50, 50
  • Disable Generate Overlap Events
  • Set the Collision Presets to Trigger

Unreal Engine with car object model for new blueprint

Next, create a Box Collider component.

  • Set the Location to 1.5, -2.5, -0.75
  • Set the Box Extents to 1.3, 0.45, 0.6
  • Enable Simulation Generates Hit Events
  • Set the Collision Presets to Trigger

Unreal Engine with Details window open for car blueprint

Let’s now head over to the Event Graph where we’ll begin by creating some variables.

  • StartPosition (Vector)
  • Speed (Float)
  • Distance (Float)

Compile, then for each variable, enable Instance Editable so we can change the values in the level editor. But for the speed, let’s set that to a default value of 400.

Car blueprint components added in Event Graph

Now for the nodes. Each frame, we’re going to be moving in our forward direction.

Logic for forward car movement in Unreal Engine

We’re also wanting to check each frame if we’ve driven as far as the distance variable. If so, then reset our position to the start position.

Logic to reset car based on distance traveled

Finally, we’re going to check for an overlap of the player collider. If so, we’ll restart the scene.

Logic to check for car player collision

Back in the level editor, let’s place down our first car.

  • Set the Location to 400, -550, 0
  • Set the Rotation to 0, 0, 90
  • Set the Start Position to 400, -550, 0
  • Set the Distance to 1100

Now if you press play, you should see the car move down the road, then reset its position once it reaches the end.

Car blueprint added to Unreal Engine project

Go ahead and create many more cars to fill in the roads.

Various cars added to Unreal Engine arcade game

Game UI

Now we’re going to create some UI for the game. We’re going to have two elements. A win screen and a score text so the player can see their current score. In the Blueprints folder, right click and select User Interface > Widget Blueprint. Call it GameUI. Double-click to open the UI editor window.

First, drag in a new Text component.

  • Set the Name to ScoreText
  • Enable Is Variable
  • Set the Anchors to Top-Center
  • Set the Position X to -250
  • Set the Position Y to 60
  • Set the Size X to 500
  • Set the Size Y to 80
  • Set the Text to Score: 0
  • Set the Size to 50
  • Set the Justification to Center

Unreal Engine text UI for score

Next, we want to create the win screen. Drag in a canvas panel component. This will be the contents of the win screen. Populate it with a header text and button to restart the game. Make sure that the canvas panel has Is Variable enabled.

Win popup for Unreal Engine arcade project

We then want to select our restart button, and in the Details panel create an On Clicked event.

Unreal Engine Details panel with focus on Events

This will create an OnClicked node in the graph. All we want to do with this, is when triggered – restart the current level. Also, we’ll add the EventConstruct node which gets called when the UI is created. All we’re doing here, is disabling the win screen panel.

Event Graph logic to restart the game

Next, we’ll create the UpdateScoreText function. This gets called when we collect a coin. Add an input of type Integer and call it NewScore.

Event Graph logic to update score UI text

Then we have the SetWinScreen function which just sets the win screen panel to be visible.

Logic to notify player of winning in Unreal Engine

Back in the Player blueprint, we can initialize the UI. First, create a new variable of type GameUI called GameUI.

Then continuing on the EventBeginPlay flow, create and initialize the UI widget.

Unreal Engine Event Graph with event to initialize the UI

So inside of the AddScore function, we can update the UI.

AddScore logic with UI logic added

If you press play, you’ll see it in action!

End Goal

To finish the project off, we’re going to create a flag at the end of the level that the player needs to reach. This will enable the win screen, prompting them to restart the game. So in the Blueprints folder, create a new blueprint of type Actor called EndFlag.

All we’re going to do component wise is add in a static mesh.

  • Set the Static Mesh to Flag
  • Set the Location to -37.0, 7.8, -100.0
  • Set the Rotation to 90, 0, 0
  • Set the Scale to 50, 50, 50
  • Enable Simulation Generates Hit Events
  • Set the Collision Presets to Trigger

EndGoal blueprint created with flag model

Over in the Event Graph, we just want to check when the flag has collided with something. If it’s the player, enable the win screen. Also enable the cursor.

Logic to trigger game win pop up in Unreal Engine project

Back in the level editor, let’s drag in the flag and position it at the end of the level.

  • Set the Location to 1800, 0, 0
  • Set the Rotation to 0, 0, 90

EndGoal blueprint added to Unreal Engine level

Conclusion

There you have it!  You now have a complete road-crossing, arcade game made with Unreal Engine!  Over the course of this tutorial, we’ve learned to set up everything from coin collection to the constant flow of forward-moving cars to create obstacles for the player.  All of this was accomplished with Unreal Engine’s Blueprinting system, which handles all our game logic – including win conditions!

From here, you could expand the game by adding in more obstacles, collectibles, or even more unique levels.  You can also use these fundamentals to create an entirely new game with your new-found knowledge. Whatever you decide, good luck, and we hope you’ve learned a lot about building games with Unreal Engine!

Unreal Engine road-crossing arcade game

]]>
Creating a Retro Base Defender Game https://gamedevacademy.org/unity-base-defense-tutorial/ Fri, 23 Aug 2019 15:00:42 +0000 https://gamedevacademy.org/?p=9538 Read more]]>

You can access the full course here: Unity 2D Projects – Rocket Defender

Part 1

Welcome to Zenva’s Retro Series – Rocket Defender course.  Throughout this course, we’re going to build a base defending game where we protect our bases from falling enemies using rockets.  In this lesson, we’re going to lay out our level.

Project Setup

To begin, we’re going to open up Unity Hub and create a New Project.  We will call this project Rocket Defender and use the 2D template.  For our Unity Version, we will be using version 2019.2.0a4.

Unity Hub Project creation screen

Once Unity opens up, you might find it helpful to change the Layout to Default via the button in the top right corner.  This way our screen setups will match for the duration of the course.

Unity Layout menu with default selected

After this, we need to turn to the Assets folder, right click, and Create a new Folder called Tiles.

Unity Create menu with folder selected

We will drag each PNG below over to the new Tiles folder in Unity.

Unity sprite tiles

Tilemap Painting

Now that we have our tiles, we can start setting up our Tilemap.  From the GameObject menu at the top, we need to select 2D Object and then Tilemap.  This will add two elements to our Hierarchy: a grid which will show a grid on the scene view and the Tilemap itself for painting the tiles.

Unity GameObject window with 2D Object > Tilemap selected

However, in order to paint our Tilemap, we need a Tile Palette.  From the Window menu in the top bar, we want to open up the 2D window Tile Palette and dock it right next to the Inspector.

Unity window menu with 2D > Tile Palette selected

Once docked, we want to Create a New Palette called Main.  Make sure to save the Tilemap to the Tiles folder when prompted.

Unity Inspector with Create New Palette component

Before we add the tiles to the palette, we need to select all of the sprites and change their Pixels per Unit to be 128 in the Inspector.  This ensures that they don’t overextend our grid and line up correctly.

Unity inspector with pixels per unit changed

Afterwards, creating the palette itself is as easy as selecting all the tiles in the Tiles folder and dragging them over to the Tile Palette.

Unity Tile Palette with sprites

We can now paint our Tilemap!  Selecting the Tilemap from the Hierarchy, we can then choose our paintbrush from the Tile Palette and paint the tiles on.  You can paint the level to look however you want, but make sure the ground is relatively flat.

Unity scene with painted tilemap

After painting the Tilemap, select the Main Camera and change the background color to a dark blue.

Unity Inspector with camera color picker

Sprite Atlas

Before we continue, we want to create a Sprite Atlas in the Tiles folder.  We will call it Main.

Unity Create menu with Sprite Atlas selected

A Sprite Atlas is a way to make our game more efficient, as it packs all our sprites into a single object and loads them in via a coordinate system.  Most of this is handled by Unity, and once created all we have to do is drag the sprites to the Objects for Packing list in the Inspector for the Sprite Atlas.

Unity Objects for Packing list

Our level is all painted!  In the next lesson, we will set up the bases that we need to protect.

Part 2

In this lesson, we’re going to build the bases that enemies will target and set up our base script component.

Adding Bases in the Scene

Rather than as tiles, we want to create our bases as regular game objects.  As such, from the Hierarchy, we want to start off by creating a new 2D Object Sprite.  We will call it Armed Base.  This will be the base that can actually fire rockets later.

Unity 2D Object menu with sprite selected

In the Inspector, we’re going to assign Sprite_165 as the sprite for this base.  We want to scale it to be 1.25 on both the X and Y axis so that it’s a bit larger.  For its position, we will set X to 0, Y to -2.4, and Z to 0.  Feel free to position and size the sprite as you would like, though.

Unity Inspector with Transform highlighted

Next, we can create our non-firing bases that need to be protected.  From the Hierarchy, we can hit Ctrl + D to duplicate the Armed Base and rename the object to Base.  For this Base, we want to use Sprite_166 and move it to be on -3.5 for the X.

Unity Inspector with Transform and Sprite Renderer

With the Base object, we want to duplicate it three more times and change the X position.  One of these new objects should be placed a -7, one at 3.5, and one at 7.  Inevitably, we should wind up with our Armed Base surrounded by two bases on each side.

Unity scene with bases added

Base Script

Our bases are setup, but now we need to create our script.  In the Assets folder, we want to create a new folder called Script.  Then, with Script folder open we will right click and Create a new C# Script called Base.  Once created, you can drag the Base script onto the Base objects.  However, don’t add it to Armed Base.  This object will be a child class of Base that we will work on later.

Unity Inspector with Script component added

Once complete, you can double click the Base script to open it in Visual Studio.  The script for Base will be simple and include health information and a way to damage the base.  At the top of the Base class, we will add a variable to store our health.  Under this, we will create our Damage method.  This method will take in an amount to damage the base by and then subtract that amount from the health.

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

public class Base : MonoBehaviour
{
    public float health;

    public void Damage(int amount)
    {
        health -= amount;
    }
}

For this course, we won’t be focusing too much on aesthetics for what happens to the base when it dies.  As such, we’re going to handle base death very simply in this script. Under the Damage method, we will add a new method that uses Debug.Log to mention the base has died.  After which, in Damage, we just need to check if the health is less than or equal to 0 and call this Die method if that’s the case.

public void Damage(int amount)
{
    health -= amount;
    if (health <= 0)
    {
        Die();
    }
}

private void Die()
{
    Debug.Log("A base died!");
}

(Note: You are free to add your own material to the Die method, such as changing the sprite).

Last but not least, we have to assign some health.  Since we made the variable public, we can add it via the Inspector.  However, to make things simple, we can add an Awake function (the first script run) to assign the health for us.

private void Awake()
{
    health = 3;
}

In the next lesson, we’re going to start writing the script that controls our rocket projectiles.

 

Transcript 1

Hey guys, my name is Austin Gregory and in this course, I’m gonna teach you how to create the classic Rocket Defender game where you’re gonna have these baddies, these enemies falling from the sky, targeting your bases, and you have to shoot them with rockets.

So if I were to click play here, you can see my timer counting down. I’m shooting these, we can just imagine they’re rockets and these enemy things are falling from the sky and they’re targeting my bases and, if they hit them, they’ll damage my bases.

And I get points depending on how many bases I have every single round. And my rounds are based on 10 seconds, but yours can be based on anything from number of enemies per level or a random set of time between values, depending on whatever you’d like to do for your game. And every single round, it accumulates the score and it keeps adding to it so you just keep playing until you lose and once you lose, you start all over.

My name is Austin Gregory and I will see you in the first lesson.

Transcript 2

Hey guys. My name is Austin Gregory, and in this course we’re going to build a cool little rocket defender game. Where we’re going to have to defend our bases against falling enemies by shooting rockets at them from our armed base right in the center.

We are going to spawn enemies randomly at the top of the screen. Off the top of the screen a bit with a width that they can spawn at off the top. They’re gonna target a single base individually. We gonna choose that randomly, and they’re going to drive straight for that base. Trying to damage the base. Takes three hits to kill a base. At the end of a round you get points for each base you have still alive. And you keep doing this for as long as you can, to see what kind of score you can get. Each round will last for a set number of seconds or a random set number of seconds depending on how you want to do it. And we just keep going until you die.

So, in this lesson we’re going to lay out the level using some tiles that I have. And we’re going to just build a nice little level, and in the next level, or in the next lesson, we will set up our bases on this level.

So, we’re going to use a Sprite Atlas for our tiles. And we’re going to use a tilemap to allow us to paint tiles in unity. And we’re going to just lay out a nice little level. The Sprite Atlas is going to allow us to be more efficient with the way our tiles and our sprites are handled. It’s very easy to do. So I’m gonna jump up into Unity Hub here – it’s gonna open up Unity Hub. I’m gonna create a new project.

So new project, it’s going to call this rocket defender, and we gonna use the latest version available – which is actually in beta at the moment 2019 point 2.0 a 4. And this is gonna be a 2d template project and just create project . Now in a folder here, I have all the tiles were gonna be using and a couple of sound effects. We gonna use these tiles to lay out the level. We gonna use this golden gem here as our rocket.

And we have some buttons down here that will act as our basis, if I can find them here. Here we go. It’s gonna be our regular basis and it’s gonna be our armed base that we’re gonna be shooting from. So here we are in the default layout. If you do not see what I’m seeing right now go up to the top right go to default and this is the layout you will get.

We want to start by creating our tilemap and our tile atlas. So I’m going to create a new folder. It’s gonna hold all of our tiles it’s gonna call it tiles. And inside of this, I’m just gonna drag the tiles we’re gonna use right into it. We’re gonna use these to add some flowers to our level and then we’re going to use let’s just find the tiles here. So when I create a platform on the ground using these tiles. We gonna want this as the rocket and it will grab these buttons. Just drag these into that folder there, and I selected those holding down control.

And I also wanna add this just plain brown so we can actually add a little depth to our platform’s off the bottom there. And now I wanna create a tilemap using these sprites, so I’ll go to game object 2d object, and I want to create a tilemap. And that’s going to add a grid to our scene with a tilemap just like that.

Now I wanna open up another window that’s going to be the tile palette – to the place where we can put our tilemap tiles and allow us to paint the tiles in our world so it’s going to be under 2D tile palette. Now I’m going to just dock this right next to my Inspector so I can just switch between the two there. Just like that. And I want to create a new tile palette, and I will call it main and all this stuff will keep default for now. I just want to use all the default stuff just get this going pretty quickly.

And I wanna put this tilemap in the tiles folder, so select that folder and there we go. Now I need to drag tile sprite or sprite texture assets to create the tilemap. So I’ll have to do this take these tiles. These are individual tiles. You could use a tilemap for this it’s already put together. But I have individual tiles, I’ll just drag this over into my tilemap. And again select a folder what’s going to generate the tiles. I’m gonna generate it right in the same folder. Just like that.

Now I have these tiles – you can rearrange them if you want by going to edit clicking them and dragging them around. If you were to actually select it and then move it, but it’s fine where they are I don’t really care. Now turn off edit, let’s select our town map, and we will have the brush selected here. And I’ll just select a tile and I will start painting.

Now one thing you’re seeing is it has these edges extruded over the actual tile size. So we haven’t set up a size for our tiles, and we haven’t actually set up our individual sprites. So if I were to come and look and inspect here with these selected, if I select, our sprites should end this before here about just control.

Select all of these all the individual sprites – not the tiles themselves. And what I want to do is set the pixels per unit. I know my sprites are 128 by 128, so I’ll just say 128 pixels per unit. That means now our sprites will be 1 by 1 unit to unit by default, which is exactly what we want. So now that just fits snuggly inside of our tile barriers, there our tile grid.

And I’ll add some edges here just round it off – you won’t even see these are off the camera. But just in case we’ll have that there and then just add the ground below that. And we can also add some flowers here, some plants just to give it a little life. And what we gonna do is put our base, our main armed base in the middle, and then we’re going to have the four defending the four bases that will be targeted off to the left here and off to the right.

So I wanna jump in really quickly and say that I forgot to set up the Sprite Atlas like we were supposed to in this lesson. So I wanna go and show you how to do that right now. If I go to right-click, go to create, I can create a new Sprite Atlas just like that. And I’ll call this main as well.

So when the atlas is gonna do for us is we’re going to be able to add our individual sprites to it, and it’s gonna create one single object that they can get all of these images from. And it’s going to do that using a coordinate system. It’s really fancy, but all we care about is it makes our game more efficient and it just simply makes it work better. So what I’m gonna do then is just drag these over and add it to objects for packing. One at a time – or what we can do is we can lock the Inspector so this doesn’t go away when I select another object. And I can just select them all holding down control and then just drag them over and drop it on objects for packing.

And if I click pack preview, we can see what it looks like in the end. This is what it creates. And right now it’s on tight packing with for padding. You can also not allow rotation and make it not tight packing. You can see what that looks like. There you go. Completely up to you anyway how you do that how efficient you want to be. But in my case this is great. And what’s cool about this is it doesn’t force automatically. Now if it tries to get a sprite that we have referenced by one of these instead of doing that it’ll simply go to the sprite atlas. Unity handles that for us. If it’s in a sprite atlas it does it, very simple.

Now back to what we were doing.

So that looks pretty good. I want to take my camera and change the background color So we can actually match – let’s actually do a blue in the back like a dark blue, something like that looks pretty good And our enemies are gonna come down from the top and just target these bases.

So in the next lesson, guys, we’re going to set up our bases. We’re gonna build the object itself and write a simple script that will tell the base what it’s supposed to do. That’s in the next lesson. My name is Austin, and I will see you there.

Transcript 3

Hey guys. In this lesson, we’re going to build our bases. It will be the targets of our falling enemies. So we have to decide where we’re gonna place our bases. We’re just gonna create some sprites in our game world. Then we’re gonna create a base script that’s going to just give the object some health and the ability to be damaged. And then we’re going to, later on, have a collection of all of these bases.

So we have the four regular bases, the one armed base, and we’re going to be able to get a random base as a target for an enemy, and also check to see if the base is alive or not. If the base is dead, don’t target that base. So if you come down to the point where you only have one base left, every enemy will target that base, making it a bit more difficult for you as you progress through a round.

So now to keep things simple, we are not going to necessarily use the tiles of our buttons here, of these bases. We’re just going to create objects in our scene just like we normally would, and we’re gonna use those as our bases. So first of all, let’s create our armed base. I’ll create a 2D object that is a sprite, and I’ll call it armed base, just like that. And I want to see where this is here. Let’s place this, zero, zero, zero. And the sprite I wanna use for the armed base is going to be that button right there, and we can see it right there.

So if I were to drag this down to the dead center, right on top of the ground, that’s what you get. Now, the size, it’s up to you how you want to do this depending on the scale of your game. But maybe I wanna do like 1.25, 1.25 on the X, and the Y, just drop where it is there; maybe 1.25 on the Y as well and just place it right on top there. About -1.24 on the Y looks like a good position, and our other buttons, our other bases here, are gonna be the same thing, except we’re gonna place them off to the left and the right. So I’m gonna duplicate armed base. I’ma call it base. And I’m going to use this sprite for the base, and we’re gonna move it off to the left on the X, -2, maybe -3. 3.5 looks pretty good. And we’ll just duplicate it again and then do -7.

And we can obviously move these plants around if we want to. And then we’re gonna do the same thing in the other direction. So take both of these bases, duplicate those, move them off to the right three, and then move the other one off to the right, actually 3.5, and then seven. So there we go. Now they’re nice and centered. They are evenly distributed between the left and the right of the armed base, and that looks pretty good.

So now let’s create a scripts folder to hold all of our scripts we’re gonna be writing here. Just gonna call it scripts, and inside of this we’ll create a new C# script called base. Now this will be on all of our bases, so I can add this to base, just like this, or we can select them all at once, do it all at once. Now armed base will have a derived class of base that allows it to fire. So it’s going to be a base, but it’s going to be a child class of base, as opposed to the parent class which we’re writing right now.

So open this up in Visual Studio. The base base class is going to be really simple: it’s gonna have a health property that is gonna start at like three or so. If it gets down to zero, that base is dead, and it’s going to have a method for damaging the base if it were to collide with an enemy. So what I wanna do is have a public float health, maybe an integer as well depending on how you want to calculate your health, but I’ll just use a float for now.

And we don’t need either of these methods. What I wanna do is I wanna have a public void – returns nothing – and it’s gonna just be called damage. Now damage is gonna be the method we call whenever the enemy collides with the base. The enemy’s gonna be responsible for calling this method from itself. So it’s gonna pass in the amount of damage it should do, or you can just always say one enemy hitting this base means one damage.

Now I could add this simply by saying amount, and then we could just use this amount so you could have different sized enemies, maybe a big enemy does more damage, a smaller enemy does less damage, and so on. Or you could just keep it with simply -1 per damage.

So what this will do is do health-amount, right? So you could say health minus one, or health minus minus to subtract just the one. Or you could say health-=amount. And that will subtract from health the amount that we passed in, and it will then store that amount back in health. So health will be equal to whatever health minus amount is. And then simply have to check if health = 0, that means this base is dead, so I can just say died.

Now we’re not going to do anything directly if the base dies, because all we care about is if the base is alive whenever we’re trying to get a target for an enemy. Whenever we spawn an enemy, it’s going to check to see what bases are alive and give me a random one of those alive bases. So the base dying doesn’t necessarily matter to me in this simple form of the game, but I would expect you would wanna do something with it. Maybe play a sound effect when it dies or maybe change the sprite to a different sprite if it’s dead. Very simple thing to do, but we’re keeping it really simple here. I’m just adding this in just in case you want to do that.

So I can add then a private void, I’ll just call it die. And we’ll just call this whenever we die, so we’ll just say die. Now anything you wanna do when a base dies, you just do it right here in this method. For now, I’ll just log out a message that says a base died. And now back in Unity, all I have to do is I can add health directly in the Inspector like this, or I could go back in and say whenever this base is created, we wanna add three health to it.

So we could say void Awake, and we’ll just say health = 3. Just as simple as that. So now whenever we start the game, health is equal to three on all of our bases. Very cool.

That’s gonna be it for this lesson, guys. In the next lesson, we’re going to write our rocket script. That’s going to be what our armed base fires. Whenever we click, it’s going to grab a direction and move in that direction based on the mouse position. That’s in the next lesson, guys. My name is Austin, and I will see ya there.

Interested in continuing? Check out the full Unity 2D Projects – Rocket Defender course, which is part of our Unity Game Development Mini-Degree.

]]>
Setting up a Competitive 2D Arcade Game https://gamedevacademy.org/unity-arcade-game-tutorial/ Fri, 05 Jul 2019 15:00:39 +0000 https://gamedevacademy.org/?p=9838 Read more]]>

You can access the full course here: Unity 2D Projects – Toads and Fireflies

Part 1

Setting Up Our Scene:

  • Import needed sprites.
  • Create our Toad objects.
  • Create our level.

Open the Unity editor and create a new Unity project and call it “Toads and Fireflies.”

For this course we are using the latest version of Unity which is currently at version 2019.2.0a11.

Use the 2D template, and disable the Unity Analytics.

Click on the Create Project button:

Unity create project window with 2D template

Use the Default layout during this course so that your Unity editor will look like Austin Gregory’s.

Create a new folder and call it “Sprites” this is where we will keep all of the sprites used in the creation of this game.

We’ll be using the assets below.  Drag and drop three sprites right into Unity inside the Sprites folder you just created:

Toad, firefly, and background sprite assets for Unity game

With all three of the sprites selected inside Unity make sure the Texture Type in the Inspector window is set to Sprite (2D and UI).

Unity Important settings with Sprite option selected

Select just the Toads sprite and for Sprite Mode make sure this is set to Multiple in the Inspector window:

Unity Inspector with Multiple selected for toad sprite

Then open the Sprite Editor, Apply the Changes, and we need to split this sprite up into a total of three:

Unity sprite editor window

Click on the Slice option in the menu, and set the Type to Grid by Cell Count, set the Columns to 3, and then click on the Slice button:

Unity slice options in sprite editor window

Now click on the first toad in the editor, and name this to “idle_toad.”

Unity sprite sheet with first sprite renamed idle_toad

Click on the second toad and name this one “jump_toad.”

Unity sprite sheet with second sprite renamed to jump_toad

Click on the third sprite and name this one “tongue.”

Unity sprite sheet with sprite renamed to tongue

Make sure to Apply the changes.

You should now have three sprites that you are able to work with:

Unity sprites folder showing multiple sprites for one asset

Set the screen size to 16:9.

Select the background and drag and drop it into the Scene, then all you need to do is simply drag it out to resize it to fit in the camera space:

Unity scene with background sprite added

Select all of the sprites in the Sprites folder and change the Filter Mode to Point (no filter). Hit the Apply button to apply the changes to the Sprites.

Create a 2D object and rename it to “Toad.”

Set the Sprite to the idle_toad in the Inspector:

Unity scene with white frog sprite added

You can change the color of this toad to a green color using the color picker:

Unity scene with frog sprite colored green in Inspector

Move the green toad over to the left side of the screen:

Unity scene with frog moved to bottom left

Create a new folder and name this folder “Prefabs.”

Turn the green toad into a Prefab by dragging and dropping it from the Hierarchy into the Prefabs folder:

Unity with sprite made into prefab

Create a 2D Object>Sprite, and rename this to “firefly.”

Change the Sprite to the Firefly in the Inspector:

Unity scene with Firefly added

We now need to add a Sorting Layer, so add a new Sorting Layer and name it “Background.”

Unity Inspector with Tags & Layers options

Add another layer for “Player.”

Unity Inspector with Player layer added

Add another layer for “Foreground.”

Set the sorting layer for the Firefly to be on the Player sorting layer.

Set the Toad sorting layer to be on the Player sorting layer.

Set the Background sorting layer to be on the Background sorting layer.

Part 2

The Toad

  • Create a script for our Toad object.
  • Setup a “jump path” for our toads.
  • Jumping moves between jump path points.
  • Add an attack to strike fireflies.

The first thing we will do in this lesson is setup the jumping points for our toad. Create an empty game object, and we will be using the empty game objects to define points for the toad to follow along its jumping path. The first empty game object will be at position (0, 2, 0).

Unity scene with Empty Game Object added

Rename the empty game object to “Path Point.”

Create another empty game object and rename this object to “Left Pad.” Set this position to (0,0,0.)

Add an empty game object as a child to the Left Pad, and position it at (-4, -3, 0). 

Duplicate the Path Point and set Path Point (1) to be at position (-5.5, -2.75, 0).

Duplicate the Left Pad and rename it to “Right Pad.”

Reposition the Right Pad Path Point to be at (4, -2.75, 0).

Reposition the Right Pad Path Point (1) to be at (5.5, -2.75, 0).

We now have the path for the toad setup.

 

Transcript 1

Hey guys, my name is Austin Gregory. And in this course, I’m gonna teach you how to create a pretty cool little game.

I’m gonna be creating Toads and Fireflies. It’s based on another game with a similar name. There’s gonna be two little frogs. It’s a two-player game, a local two-player game, where you can play with a friend and compete. You’re gonna jump and you’re gonna try and attack these fireflies. And each firefly has a unique speed and a unique point value. They can be different sizes, different colors, all kind of fun things. And the frogs – you can have as many frogs as you would like, as many players as you like. But we’re gonna go with two players.

You’re gonna jump from pad to pad. You’re gonna follow a nice little jump path. Each frog has their own jump path. And while you’re in the air, if you try to jump again, if you use the action button again, you’re going to attack these fireflies. And the level, the competition takes place over a set amount of time, so you’ve got 30 seconds or a minute or two minutes (or however long you want your game to be). And at the end, whenever the time runs out, whoever has the most points wins the game.

It’s going to be pretty simple to do. And we’re gonna learn quite a few fun things, a few fun things that you can take and apply to this game and extend it into something fun, something a bit more. And also things you can take and apply to whatever kind of project you want to work on, because these are gonna be very general topics that we’re going to cover.

So again my name is Austin Gregory. And I will see you in the first lesson of Toads and Fireflies.

Transcript 2

Hey guys, in this first lesson, we are going to set up our level. We’re gonna simply import some sprites, so we need to build our very simple level. We are gonna create our Toad objects, which are not just going to be objects with a sprite renderer on them. Someone can add our Toads sprites to them. And then we are going to set up our level sprite. Just one big sprite as a couple of lily pads that we can jump from and catch those flies in the sky.

So, first thing I want to do is create a new project in Unity Hub, call it Toads and Fireflies. And I want to use the latest version available to me, which is 2019.2Alpha11, and I want to select 2D as my default template and click create project. And then to make sure we’re on the same page, I want to go up to layout and I want to select default, so we all have the exact same layout going into this.

And I want to create a folder for my sprites, I’m gonna call it Sprites. And then what I wanna do is- I wanna go into my Assets folder that is included in the project, and I’m just gonna grab these three sprites: we have our toads sprites, the idle, the jump, and our little tongue is gonna be shooting out and catching these fireflies, and then our background image. So, let’s take these and drag them into our Sprites folder. Now with them all selected, make sure we have it set to 2D and UI sprite. If you have your template set to 2D, this should be the default, so that should be okay.

Then for our toads, we have three sprites in one, so what I want to do is set this sprite mode to be multiple then I want to go to Sprite Editor and apply my changes for the multiple there. And what I want to do, is split this up into my three sprites. So, I know I have three columns here, so the easiest way to do this is to go to slice, type, and I want to do grid by cell count; and I know I have three columns and click slice. There we go, so we have one, two, three. Now to keep this organized, I could name this idle toad, jump toad, and tongue, and apply those changes. Now we should have three sprites that we can work with right here all from one sprite sheet.

Now, I know I’m going to be building my game based on a 16×9 screen. If you have more time and you want to put a bit more work in you can obviously do this where it’s dynamic and resizes and all that fun stuff, but I’m gonna keep mine very simple and just restrict it to now by a 16×9 aspect ratio. And the first thing I want to do with our scene is add a background. Now if I take this and drag it out, this is what we get, and all I simply have to do is just resize this to kind of match, holding down shift. So we get, we lock in the aspect ratio to kind of match our size of the screen here. Zero, zero. And there we go, so there is our game world. Very simple.

Let’s select these, and I want to change the filter mode, these are, this is a pixel art sprite, all of these are. And we’re getting this weird blur from when it’s trying to scale up these sprites. So, what I want to do is set the filter mode to be .nofilter, which when I add any anti-aliasing to our pixels as we scale it up. So, there we go, and now let’s create a 2D object sprite for our Toad. And this is gonna be by default, just our little idle sprite. And we can add color to this, so one of our frogs, or one of our toads, sorry, will obviously, probably be a green color. So, we can just place him in the back where he would be. And then we’d have another toad that we can make a different color for player two. But we will do that in a bit.

Then I’m gonna create a folder for our prefab objects. The objects that we’ve already fabricated that way we can just create new versions of that. So, I know I’m gonna have two frogs, and they’re all going to have the same settings, except for, one’s gonna be player one, one’s gonna be player two, and they’re gonna have two different colors. So, other then that, they’re the same thing. So, I’m just gonna create a prefab from that frog. That way all I’ll have to do is drag it out and then have another frog that is set up the same way. And I can change the color on that frog. So that’s what we’re doing eventually.

And then the next thing I want to do for now is create a firefly. And the sprite for firefly will be our firefly sprite. Here we go, so this is what we look like at the moment.

So if we have these all on the exact same Z, that means they’re going to be fighting to see which one is displayed. So the simple way to fix that is by using sorting layers for our sprites. So, if I want to go to sorting layer, I don’t have any set defaults, I’m gonna add a sorting layer and I’m gonna add a sorting layer for background. So what’s going to be drawing on the background. I’m gonna add a layer for player, so what things are drawn on the player level, so our frog, our fireflies, our tongue, or again, our toad. And we’re gonna have foreground if we’re gonna have something floating in our foreground. Not sure we will though.

And then I just set this to be a player, and set the toad to be player and set the background to be background. Then we have some nice organization so we know easily how to place things in our game world so they are displayed correctly.

And that’s gonna be it for this first lesson guys. In the next lesson, we are going to work on our toad. Which is gonna be the most complex thing we do, because he has to jump, he has to attack, and all these fun things. So, it’s going to take a couple of lessons to get it done, but we are gonna get started on that in the next lesson. My name is Austin, and I will see you there.

Transcript 3

Hey guys, welcome back. In this lesson, we’re going to set up our toad, which means we have to create a new script for our toad object. It’s gonna control everything the toad can do. We’re gonna also have to set up a path.

So there’s a bunch of ways we could do the jump for our toad, because they have to jump from one pad to another. Now, I need to know exactly where my toad’s going, and I need to be able to control it very precisely, because it has to jump from an exact point on one pad to an exact point on another. There’s a bunch of ways we can do this. We could calculate the exact amount of velocity that we have to have to get from one point to another, but that’s going to lose precision over time the more that we do that. Just a couple of points here and there, but it will make a difference.

Also, we could do it with a parabola. We could just calculate the type of- or the parabola that we’ll need to get from one point to the next. And that’s a lot of math that we’ll have to walk through and talk about. That’s just not absolutely necessary to make simple, little game like this.

So what we’re gonna end up doing is just placing a couple of points along the path that the toad has to jump. Then we’re gonna go from one point to the next whenever we jump. If we’re on the left side, we’ll jump and follow to the right. If we’re on the right side, we’ll jump and follow to the left. That should cover what we need to do for such a simple game. And our toad also has to have the ability to strike or to attack, using its tongue, which we’ll set up the method for this for now. But we will not have the tongue action until a couple of lesson for now, because we have to animate it, and we have to set up collisions, and we have to have flies to test it with. Just a bunch of stuff we have to do for that. So over the next couple of lessons, we’re gonna be working on our toad and getting it do all of these things.

The first thing I’m gonna do for my toad is set up those jumping points, so that it can jump from here to here. The way we’ll do this is we’ll have two toads, and the toad that’s on the left side here can jump from this point, up here, try to grab some flies, and fall down right here. We’re not gonna share a point because they’re gonna have to be next to each other while they’re on the pad. The other frog can be standing right here. It’ll jump, do the same thing, but it will land in the back. So they move the same distance. They have the same amount of ability and potential to catch these flies, but they’re at a slightly different position.

What I’ll do first of all is create an empty object, and we’re gonna be using empty objects to define the points for our pad. So all I have to do is take this object. If I just grab this, I can just move it to wherever I want it to be and say, okay, this where it’s gonna jump to. From here, to here, and then down to here. So I can place this at maybe 1.5. Maybe something like two, however high you want your frog to jump. And, again, place it at zero on the Z there. And I’ll call it Path Point.

Then I have to have two points on each of these pads to show where the frogs start and where they can end up. To do that, I’ll create an empty object, and I will call it Left Pad. And, again, I’ll just center this. Inside of left pad, I’ll have a couple of empty objects, and I can place where I want them to be. So I’m thinking this is about -4 and -2.75, or maybe -2.8, maybe -3. I have to see how that looks whenever we set this to be at that point. If we look at our toad, we can see negative -2.75 is right on the pad, so we’ll do that for this Path Point. Then I’ll duplicate that, and I’ll put this one at about -5.5, where that frog is going to be. Then we have those two points there.

Then all I have to do is duplicate the Left Pad, and then move these over. I’ll rename it Right Pad. And move these over to the right, so instead of being negative, zero is right here. We’re off -4 and -5.5, so I wanna go positive four and positive 5.5. Basic math there, so four and then 5.5. And there we go. That’s our path. So we can jump from here, up to there, and then down to this point, and then jump from here, up to there, and down to this point. Just keep going back and forth for both toads.

That’s gonna be it for this short lesson. In the next lesson, we’re gonna start using these path points to control our toad. My name is Austin, and I will see you there.

Interested in continuing? Check out the full Unity 2D Projects – Toads and Fireflies course, which is part of our Unity Game Development Mini-Degree.

]]>
Virtual Reality Mini-Degree https://gamedevacademy.org/virtual-reality-mini-degree-vr/ Fri, 26 Oct 2018 23:30:23 +0000 https://gamedevacademy.org/?p=7755 Read more]]> Become a professional VR developer as you learn to code and create 15 immersive games in Unity from the ground up – no prior programming experience required! 

Welcome to the world’s most comprehensive online curriculum on VR game development, where you will learn and master the foundations of C#, Unity and VR by building practical projects. Whether your goal is to make VR games for fun, start a business in this exciting field, or become a professional Unity development, this online curriculum contains everything you need to reach your goals.

Covering all the major VR platforms – including Oculus Rift, HTC Vive / SteamVR-compatible headsets, Samsung Gear VR, and Google Cardboard (Android and iOS), you will learn:

  • How to code in C# and build immersive games with Unity
  • Locomotion in VR
  • Working with 360° media (photos and video)
  • Preventing simulator sickness
  • 3D game mechanics and physics
  • Room-Scale Experiences with SteamVR and VRTK
  • Modular level design techniques
  • Basics of 3D game artwork creation using Blender and MagicaVoxel

…and more!

Access this Mini-Degree on Zenva Academy

]]>