Explore Free Mutliplayer Game Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Wed, 22 Feb 2023 21:14:26 +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 Mutliplayer Game Tutorials – GameDev Academy https://gamedevacademy.org 32 32 Best Unity Visual Scripting Tutorials – Making a Game https://gamedevacademy.org/best-unity-visual-scripting-tutorials/ Sun, 22 Jan 2023 08:06:11 +0000 https://gamedevacademy.org/?p=15377 Read more]]> Coding from scratch is hard, and frankly, just not for everyone. However, this should not stop you from making the games of your dreams!

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

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

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

About Visual Scripting and Unity

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

What is Visual Scripting?

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

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

Visual Scripting in Unity

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

Unity Bolt

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

Unity 2021.1 and Later

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

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

Duration: 13 minutes

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

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

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

LEARN NOW

Unity Visual Scripting Getting Started

Duration: 6 minutes

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

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

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

LEARN NOW

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

Duration: 57 minutes

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

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

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

LEARN NOW

3D Movement Animation w/ Bolt

Duration: 20 minutes

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

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

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

LEARN NOW

How To Use Bolt State Machines In Unity

Duration: 12 minutes

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

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

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

LEARN NOW

Input in Unity Visual Scripting

Duration: 7 minutes

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

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

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

LEARN NOW

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

Duration: 6 minutes

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

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

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

LEARN NOW

Bolt FPS Tutorial

Duration: 36 minutes

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

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

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

LEARN NOW

Unity Visual Scripting Recommended Practices

Duration: 22 minutes

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

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

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

LEARN NOW

Unity Visual Scripting Tutorials

Duration: 1 hour, 20 minutes

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

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

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

LEARN NOW

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

Duration: 39 minutes

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

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

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

LEARN NOW

Parting Words

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

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

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

BUILD GAMES

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

]]>
Unity MLAPI Multiplayer Tutorials – Complete Guide https://gamedevacademy.org/unity-mlapi-tutorial/ Sat, 14 Jan 2023 03:31:18 +0000 https://gamedevacademy.org/?p=13806 Read more]]> Have you ever wanted a Unity-official solution for multiplayer networking in Unity? Or – do you perhaps just want an alternative to using multiplayer frameworks like Photon and Mirror?

Allow me to introduce Unity MLAPI (or Unity Multiplayer Networking as it’s now called) – the new kid on the block who is ready to help you build your own multiplayer games. While MLAPI is still in active development by Unity Technologies, it comes with huge implications for future Unity game projects. As such, whether you’re looking to explore additional multiplayer game methods or want to expand your skills, mastering Unity MLAPI opens up a world of opportunities.

What is MLAPI?

The acronym, “MLAPI,” stands for “Mid-Level Application Programming Interface” (Mid Level API). In networking, APIs are categorized as being either mid-level, high-level, or low-level. A low-level API deals with things like serializing data, communicating with a network transport, and managing connections. It deals with the nitty-gritty of programming and networking. A high-level API sits on top of the low-level API and makes the complicated processes cleaner and easier to use. It is much easier to program with a high-level API than with a low-level API. That being said, there is a performance cost to using a high-level API. If you want a memory-efficient networked application, using a high-level API isn’t always the best choice.

Enter, Unity MLAPI. Being a mid-level API means it has access to the basic processes of a low-level API while feeling like a high-level API. MLAPI is designed to be the best of both worlds. It gives you access to the central network processes and maintains a level of abstraction for ease of use.

Screenshot of Unity MLAPI page

What can you do with MLAPI?

The true answer is “the sky is the limit.” Of course, there are a couple of things that MLAPI shines at. The biggest is security and connection approval. MLAPI will authenticate on a per-connection basis. This means that you can write your own custom logic and specifications for incoming connections. Having a system like this not only gives you a lot of options for connection authentication but also increases security. Any connection that doesn’t meet your requirements (like providing the right password) is simply denied. This makes MLAPI a serious choice for developers that want a level of security and customization.

However, because MLAPI deals with some lower-level interactions, it is not as easy to learn compared to a normal high-level API. Knowing how to use MLAPI requires a decent amount of experience with C#. While the learning curve is steeper, projects made in MLAPI are easier to scale. Plus, since it is a Unity Official package, it is far less expensive to run than some third-party high-level APIs. All these traits combined make MLAPI an attractive choice for independent game developers.

Where can I get started using MLAPI?

The first step is to download and import MLAPI into Unity from the MLAPI Github: https://github.com/Unity-Technologies/com.unity.multiplayer.mlapi. The documentation for MLAPI can be found here: https://docs-multiplayer.unity3d.com/netcode/0.1.0/getting-started/about/index.html. You can also have a look at Unity’s announcement after acquiring MLAPI: https://blog.unity.com/games/accelerating-unitys-new-gameobjects-multiplayer-networking-framework. This has some information about what the developers are hoping to accomplish with this package. While the documentation covers the basics, it is good to search around for other content that covers MLAPI in more depth. An excellent tutorial series is on Dapper Dino’s youtube channel:

Links

Tutorials

With these tools, I hope you can quickly get started creating multiplayer games in the Unity engine! Unity MLAPI is a new frontier for game development that is sure to present all developers with new opportunities. We’re expecting new features and new content related to the Unity Multiplayer Networking system as well, so keep checking back!

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.

]]>
Free Course – Local Multiplayer Ready Player Controllers https://gamedevacademy.org/local-multiplayer-player-unity-tutorial/ Wed, 21 Jul 2021 01:00:28 +0000 https://coding.degree/?p=1216 Read more]]>

Start creating multiplayer, platforming shooters in Unity by first learning how to set up the all-important player character controller! You can also extend the material covered here by checking out the full course below!

Create a Retro Local Multiplayer Game

About

In this course taught by instructor Daniel Buckley, you’ll explore Unity’s Input System to detect actions from controllers and render players. You’ll start with learning input actions, action maps, scripting, and more – all in ways that you can easily extend for local multiplayer games. Regardless of your skill level, this course will help you get started with platformers and help you learn some quick tricks for getting your player up and running for your game projects!

]]>
Free Ebook – Unity Programming for Human Beings https://gamedevacademy.org/free-ebook-unity-programming-for-human-beings/ Sun, 27 Dec 2020 15:20:07 +0000 https://gamedevacademy.org/?p=4319 Read more]]> We are stoked to announce the launch of our free ebook Unity Programming for Human Beings, authored by game development experts Jesse GloverPablo Farias Navarro, Renan Oliveira, and Tim Bonzon, in collaboration with Daniel Buckley.

In over 230 pages of awesomeness, the book starts from zero and covers all the way to building simple 2D and 3D games with Unity. Some of the topics covered in the course are:

  • Fundamentals of 2D and 3D programming
  • Unity scripting, no prior programming experience required!
  • Shaders
  • How to build your first game in Unity
  • RPGs and multiplayer games
  • Animations

We hope this free ebook helps you gain valuable, real-world skills and we very much look forward to play your games!

This book is provided at no cost in PDF format.

Download the ebook

 

What type of game will you be building in Unity? Share it in the comments!

]]>
An Overview of PlayFab for Multiplayer Games https://gamedevacademy.org/unity-playfab-tutorial/ Fri, 06 Dec 2019 01:00:18 +0000 https://gamedevacademy.org/?p=10527 Read more]]>

You can access the full course here: Player Authentication with Azure PlayFab

Setting up the PlayFab App

To begin, let’s go to the PlayFab website: http://playfab.com. If you have a Microsoft account, click Login, otherwise Sign Up.

Microsoft Azure PlayFab website

When you login, you’ll be taken to the Developer page. Here, click on the New Studio to create a new studio.

Azure PlayFab developer page

All we need to do here, is enter in a Studio Name. Then click the Save Studio button. This will redirect you back to the Developer page. Click on your studio to go to the Dashboard.

Azure PlayFab New Studio setup screen

The Dashboard is the visual interface between you and the database. We can view data about our players and navigate to many of the different databases. Feel free to click around and look at the different pages.

Azure PlayFab dashboard

In the next lesson, we’ll be hop into Unity and start to create our project.

Transcript

Hey everyone! In this lesson, we are gonna be going over basically what is Playfab and how can we use it in our games.

At its core, PlayFab is a backend for your game. And this is for stuff such as storing play information like player accounts. Maybe play information as well. And all sorts of stuff that you want players interacting with each other, for example, maybe trading, selling items, all the sort of stuff that you won’t have directly on the client-side. Something that you want in the back end so when the player turns off the game and turns it back on, that information will still be there.

Traditionally you would have to do it pretty much all on your own. You would have to create your own databases and maybe set up servers and create all the backend code that can interact with your game that the client has. But in this case, PlayFab has that all set up for us and really takes away the stress of wondering how to do it and if you’re doing it in the right way. Taking into consideration stuff such as authentication and making sure that there can’t really be any abuse from the client-side of things.

So, let’s actually look at a bunch of different features here inside of PlayFab. Right now, I’m on the PlayFab website which is just Playfab.com and I’m gonna go up to features here and game services. And here we can have a look at all the different features that PlayFab has.

There’s player authentication and linked accounts. You can create player accounts with a user name, password, email. You can also do it automatically so that the player doesn’t really have to enter any information, it just automatically knows what device they’re on and creates an account for that. You can also log in with Facebook, Google, all those other sort of things that you see with games as well.

There’s also leaderboards, you can set up leaderboards, ranking players based on pretty much anything. You can send push notifications and emails to your players. Maybe if you’re informing them about a new service or a new update on the game. Of course, you can store and manage player data. Any sort of data, really, that you’d want you might wanna store how much gold or something a player has or certain features that you need for a game. Maybe other players also want to be able to access information from other players.

Multiplayer services as well. Now, these multiplayer services, this isn’t really working with Unity at the moment so we’re not really gonna be focusing on this.

There’s commerce which is a big part of PlayFab. This involves having items, players can have inventories that can hold items, you can trade items between players. In-game characters, allow you to create separate characters for your player maybe in your game. Players can play as different classes or different sort of things and this is how you do it. This is very similar to the way you can store individual information for each character, individual inventories, all that sort of stuff.

And finally, you can create and track virtual currencies. This can be used to purchase items from the store. You can also trade currency between players, you can hand it between each other. You can also make it so that players can even buy this currency through in-game purchases. So really, this is just a list of all those sorts of services that you can have in your game and PlayFab makes it so we don’t have to do this all by ourselves, we don’t have to set up the player authentication and logging in, we don’t have to set up all the item stores, all the inventory systems, all that sort of stuff. It is already created for us here on Playfab and all we need to do in Unity is just connect to the API and create calls between it.

PlayFab also has both a free and paid plans. Very similar to Unity with the free plan you have access to quite a lot of the stuff. If we just scroll down here and click on compare all pricing tiers, we can see that all the stuff we really need such as in-game commerce, player profiles, content management, that all comes with the free version of PlayFab.

Now, it’s only really necessary to get the paid plans if you do wish to have access to these professional features. Or if you get over 1000 monthly active users. So, these are unique users each month. If you get over 1000 of those, then you are required to get one of the paid versions of PlayFab. Very similar to Unity how if you get over $100,000 in revenue, you need to upgrade to a pro plan. But for now we can just use the free plan, we can just use the essentials plan right here. As it really is just all the stuff we need right here.

So now, what we’re gonna do is let’s actually login to PlayFab or sign up. If you do have a Microsoft account, you can just login – but we can also sign up if you wish. And once you do that you’ll be taken to the developer page here. I’ve already got a game and studio here set up. But what we can do is just click on this new studio button right here and this will create us a new studio.

Now, the name doesn’t have to be unique or anything like that in general. This can just be whatever you want, just something that you can identify it with. So here I’m just going to call this PlayFabCourse and the authentication provider is going to be Playfab. We can click on save studio. And it will create our new studio here.

So here I can see PlayFabCourse right here. Let’s click on my game. And here we are inside of PlayFab. Now, we land here on the dashboard and there’s a bunch of information. Now, you can’t really see anything because there isn’t, well, no one’s actually connected to this API. No one’s connected to our game yet. So we’re not gonna see any information here. But we can see stuff such as unique users, the API calls, a bunch of other stuff as well. Logins, new users, purchases. This is very useful if you just want to have a front end, direct sort of view on how your app is going perhaps.

There’s also other information down here such as reports but what we wanna be focusing on is the left-hand side here which has a bunch of different tabs that we can select and look at. You have players, economy, leaderboards, multiplayer, groups, content, automation, analytics, add ons, settings, admin, and help.

Let’s click on the players tabs and have a look at this. This here is going to be a list of all our players. Now, whenever a player creates a new account, they’ll be popping up right here so we can have a look at all the players who are in our games. And we can even go into their player accounts and see their individual information. What sort of information are they storing, what sort of items are in their inventory, and yeah, a bunch of other information that we want to save to the cloud here for later use when they maybe log in again or if other players wanna access information about other players.

We then have the economy and here we can create something called the catalog. Now, a catalog is basically a container or a list of item, categorized items perhaps. So let’s just say you have a shop, you could create a new catalog here for that shop and in there you would list a bunch of different items that sort of relate to that catalog. With those items you can give it a unique ID, a display name, maybe even a price. And other things as well such as is it tradable, is it consumable, is it stackable? All the sort of stuff that we want to know when we are implementing them into our game.

Over here in the currency tab up top. We can create new currencies, so in your game you might want to have multiple as well. You can create as much as you want and you can use those individual currencies for purchasing the items and maybe just giving them to other players as well. There’s leaderboards which of course allow you to create leaderboards based on any sort of ranking. Multiplayer, we’re not gonna be looking at that since that is not really implemented into unity yet.

Groups, allow you to create groups for players. Maybe if you wanna have parties or clans, you would create a group for that party or clan and just add the respective people to that. The groups also allow you to store data in them or share data between the players in the group. Content here, this is just pretty much like global sort of information here in the title data.

File management, you can upload files to read. Email templates, push notification templates. Maybe you wanna send your users information about a new update, you could do it that way. In automation there’s something called the cloud script.

Now, when you are setting up stuff and making API calls inside of Unity, you don’t always wanna do everything from Unity. Because, let’s just say you want to access information about another player. Let’s just say you wanna get a player’s inventory because you want to be able to maybe see what items they have. Now, if you were to make an API call to the server from the client app to get the player’s items, then that could actually be abusable. Maybe if someone gets into your game code, maybe figures out a loophole around it. Then they’d actually be able to access information from the player, not just from the inventory.

So, this is where the cloud script comes in handy. You can send a call to the cloud script and on there in the cloud that is where all the game information of the player is and it sends back just the specific information that you need. We won’t be using that in this course, but it is something that is very useful in the PlayFab API.

Okay, that is about it for now. This is just a very brief overview of the dashboard here. There’s, of course, a lot more settings and a lot more things to look at and learn, but for now, we’ll keep it at that. In the next lesson, we’ll actually begin to set up our unity project, implementing the PlayFab plugin and setting that all up. So I’ll see you all then in the next lesson.

Interested in continuing? Check out the full Player Authentication with Azure PlayFab course, which is part of our Multiplayer Game Development Mini-Degree.

]]>
How to Install Webpack https://gamedevacademy.org/install-webpack-tutorial/ Fri, 15 Nov 2019 16:00:06 +0000 https://phasertutorials.com/?p=2972 Read more]]>

You can access the full course here: Discover Developer Tools for JavaScript Apps

In this lesson, we’re going to start the process of converting our client-side code to Node Modules and modern JavaScript. We’ll start by creating a package.json file which holds our Node Package Modules (NPM) configuration. This sets our project directory up to install our NPM dependencies. The first things to install are Webpack and Webpack dev server. Next we’ll install Phaser from NPM.

For this project, the client-side code in the stater-files resides in the folder named zenva_mmorpg. Open this folder in your editor.

Folder for project receiving webpack

Next, create a client folder inside zenva_mmorpg that will hold our client code. The other files, including index.html and folders/files under assets can stay where they are for now. We will migrate them to client in a later step.

Client folder as seen in project folder

In your terminal, change directory to client and follow instructions below to setup the client folder with a package.json file that will contain our NPM dependencies and other project details. Just follow the directions in the video lesson substituting author name for your name.

Ensure your terminal/command prompt is in the client folder in the same location as the package.json file and enter npm init and press enter.

npm init

Accept the defaults except those noted below:

Command Prompt with Webpack installation configuration

Next, open the client folder in your editor and notice the newly created package.json file. Click on the file to open it and notice its contents match what you entered into the terminal.

Package.json file for Webpack

Next, back in terminal, we can start installing our dependencies into our client folder. Some dependencies are needed for production for use in running our code while other dependencies are only needed for development. These are distinguished during installation by adding a --save-dev flag to the npm install command.

Webpack is an example of a dev-dependency, so we install Webpack itself along with the Webpack command line interface (CLI) and the Webpack development server.

WebPack-cli provides a flexible set of commands for developers to increase speed when setting up a custom webpack project.

Webpack-dev-server provides a development server that provides live reloading while using Webpack during development.

Ensure your terminal/command prompt is in the client folder in the same location as the package.json file.

npm install --save-dev webpack webpack-cli webpack-dev-server

You’ll notice that a couple of things have changed in our client folder. Our package.json file has been updated to include the dependencies we installed. As well, we now have a node_modules folder. There is generally no need to touch the node_modules folder. If you do look inside, it may seem like a lot of files got added to our project but rest assured that Webpack will include only the production pieces of code we need in the final bundle it creates.

Node Modules folder added to Project

Currently, we have Phaser.js linked in our index.html file which loads it separately. Since we are using Webpack now we can npm install phaser  as a dependency and we will no longer have to link to it inside index.html. Notice the install difference as Phaser is actually a Production dependency. We therefore add the flag --save instead of --save-dev.

Note: As of NPM version 5, installed modules are added as a dependency by default, so the --save flag is no longer needed.

Ensure your terminal/command prompt is in the client folder in the same location as the package.json file.

npm install phaser

The other advantage of including Phaser this way is we can more easily manage the version of Phaser we are using or upgrading.

Package.json with dependencies added by Webpack

Notice our package.json file now contains both Development dependencies (e.g. Webpack) as well as Production dependencies (e.g. Phaser).

Transcript

So now that we’ve talked about what Webpack is, we’re going to work on adding Webpack to our client-side code.

So in the source code that was provided, you’ll see two folders, one will be ZENVA_MMORPG, this is our client-side code, and the other one is the REST API code, that’s where’s we have our server-side logic. So, right now we’re shifting our focus just on the client-side code, so if you can go ahead and open up the ZENVA_MMORPG folder, inside your code editor, and then inside you will see we have an index.html file, and we have an assets folder. That will have all of our audio, css, images, JavaScript, and everything that we used in the previous courses to start building our MMORPG.

All right, so the first thing that we’re going to do, is let’s go ahead and make a new folder, we’re actually going to go ahead and call it client. So this is going to keep, this will contain all of our client-side logic. For now, we will not drag the index.html file in our assets folder in there, we will do that later.

So, to actually use Webpack, we need to install it as a dependency, so the first thing we should do is actually create a package.json file for our code. So, if we go ahead and switch over to our Terminal, let’s go ahead and go cd into the client folder, and let’s go ahead and run the npm init command.

So, if you recall, the npm init command is going to walk us through creating a package.json, so for a package name, we’re going to go ahead and just leave it as client, we’ll do 1.0, for our version, description we’ll just do client side code for zenvo mmorpg. For our entry point, we’re going to go ahead and do source and then index.js, test command, we’ll go ahead and just leave that a blank for now, we won’t worry about git repository or keywords, and as for author, I’m going to go ahead and put my name, you can go ahead and put yours, and then for our license, we’re just going to go ahead and leave that as the default license.

And then, we just need to go ahead and verify the information we put in. Yes, and then now, if you go ahead and check, we should have, inside our client folder, our package.json.

Perfect, so now, we can go ahead and start, actually installing some of our dependencies, so do go ahead and install Webpack, we just need to do npm install, –save, but instead of just -save, we’re going to go ahead and do save-dev, and what this will do, is it’s going to install this dependency as a dev dependency, which shows that it’s needed, well, for development, but it’s actually not needed in our production code. We’re going to go ahead and do webpack, we’re going to do webpack-cli, and then webpack-dev-server. And then we’ll go ahead and hit Enter to start installing your dependencies, so, webpack-cli, webpack-dev-server, are additional packages that are helpful while you are working with Webpack,

So, what Webpack test server will do, is it’s going to run a development server that’s going to bundle and run our code as we’re working on it, so that way we can actually test our changes in real time, where if we’re just doing the webtag build, we would actually have to build our source code every time we make a change, and then run another server to test it. That’s why webpack-dev-server is really nice, is because we can actually do it while we’re developing. And webpack-cli is just a set of commands for developers that makes it very easy to set up a custom Webpack project.

All right, perfect, so now these are installed. The next package we’re going to go ahead and install is we’re going to go ahead and install Phaser. So, currently, we have our Phaser library included with our source code, since we’ll be switching to Webpack, we can install Phaser as a dependency, and then reference it, and then when our code gets bundled, Phaser will be bundled with our code, and we don’t actually have to include that file separately.

So we’re going to go ahead and do npm install -save and we’ll do phaser, and another benefit of doing this, is we can easily upgrade our version of Phaser, without having to download and save the source code, and then upload it into our server, and since we are including it as a dependency, we can easily update our dependency to get the newest version, re-bundle our code and push it up to our server, and then we’ll be using the new version of Phaser.

All right, so now that Phaser installed, let’s go ahead and switch back to our code editor. And you will see our package.json’s been updated with our dev dependencies and our regular dependency.

Interested in continuing?  Check out the full Discover Developer Tools for JavaScript Apps course, which is part of our MMORPG Academy.

]]>
An Introduction to Webpack https://gamedevacademy.org/webpack-intro-tutorial/ Fri, 08 Nov 2019 16:00:32 +0000 https://phasertutorials.com/?p=2970 Read more]]>

You can access the full course here: Discover Developer Tools for JavaScript Apps

Webpack is an open source JavaScript (JS) static module bundler for modern JS Applications. This has two important implications. One, it means that Webpack is a JS Tool that runs at BUILD-time; not RUN-time which makes it an important part of a modern development process. Secondly, Webpack extends its power and flexibility with various plugins that not only ties together all your code and assets but allows you to incorporate linters for code quality and tools to ensure modern JS will run in all browsers. We will look in greater detail at these tools in upcoming lessons.

Webpack allows you to write as many JS files you want and organize those files along with styles, images and more in a way that makes sense for developing and supporting your project and then bundles everything together in such a way that the end result is an bundled file that is transformed, minified and optimized to run efficiently in any browser you are targeting.

Webpack diagram showing assets to final package

Webpack does this by creating a dependency graph of every part of your project then uses that information to intelligently generate one or more files based on your project needs. Webpack and its plugins are installed in the normal way using Node Package Manger (NPM).

Note: As of Webpack 4, it does not require a config file. This is important because the webpack config file could be a barrier to starting modern projects for many developers. Webpack now bundles your entire frontend app together using intelligent defaults significantly lowering the barrier of entry for the majority of devs. Devs or organizations wanting to take more fine grain control of code bundling still have the option to customize a webpack config file!

Transcript

So the first tool that we’re gonna look to use is Webpack. So if you’re not familiar, Webpack is a module builder and what that means is, Webpack is a tool that we use during development of our code. It’s not something that’s actually used during the run time of our assets. So, it’s only used during development.

So Webpack is a tool where you use a configuration to explain how you want the builder to load specific things. You describe to Webpack how you want to load your JavaScript files or how you want it to look at your SVG, CSS, or JPEG files. Then when you run your – the Webpack builder – it will go into our entry point so what is the main file of our program and it will walk up and down our program to grab all of these assets and it will figure out what needs to be done with them.

So in the case of how we’re going to be utilizing it for our project is we’re going to have all of our JavaScript files separated out as they are now and it’s going to go through and bundle all these files together and to create one JavaScript file for us. So this would be our bundle – it’s gonna bundle everything in together so that way all of our code is optimized into one location.

Furthermore, we’re gonna be able to use plugins like Babel to take our JavaScript code that will be written in ES6 syntax and it can modify and transform it back into ES2015 standard. So that way it’s supported across all browsers. And this is another benefit of using Webpack because we can use these plugins to do all this for us and then that way it ends up in our bundled file.

So to actually use Webpack, it’s actually quite easy. It’s available through NPM so we can install it like any other node package and then what we need to do is we actually need to create a configuration file so Webpack config file and that’ll allow us to tell Webpack how to bundle our code.

Interested in continuing?  Check out the full Discover Developer Tools for JavaScript Apps course, which is part of our MMORPG Academy.

]]>
How to Install Node.js for Phaser Games https://gamedevacademy.org/phaser-nodejs-setup-tutorial/ Fri, 18 Oct 2019 15:00:56 +0000 https://phasertutorials.com/?p=2960 Read more]]>

You can access the full course here: Node.js and Express for Game Development

Node.js is a cross-platform, Javascript runtime environment that executes Javascript code outside of a browser. To follow the videos, you will need Node.js installed on your machine.

Go to nodejs.org on your browser.

Node.js homepage with 10.16 LTS version available

From here we will be able to download a version for our particular operating system (macOS here). There are 2 versions available for download. You are welcome to use the current release (with the latest features) but we recommend the LTS (long term support) version for this course.

Downloading on Mac

Click on the LTS version. We are prompted to download the node.js package. Let’s save it in our install directory.

Saving of Node.js LTS version on Mac

Let’s run the installer (this step will vary based on your operating system). Click Continue.

Node.js Installer on Introduction

Next accept the License Agreement. Click Continue.

Node.js license agreement

The installer displays the space that will be taken by by the installation. Click Continue.

Node.js Installer on Installation Type screen

Node.js begins to install. This may take a few minutes.

Now that Node is installed, let’s open a new terminal (command prompt). Type the following:

$ node -v

This displays the version of Node installed (and being resolved) on our machine.

Terminal displaying node version number

$ npm -v

This displays the version of NPM installed (and being resolved) on our machine.

Terminal display npm version number

Transcript

So for our API, we will be dealing with this using Node.js. If you’re not familiar, Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a browser. And so to follow with the videos, you will need to have Node.js installed on your machine.

So in your browser, if you go to nodejs.org, you’ll be taken to this page here, and you’ll be able to download a version for your particular operating system. So it’ll be two different versions. One will be LTS and the other one will be current, so I recommend the LTS version. So this is the long-term support. This is currently the supported version of Node.js. You are welcome to use the current release that has the latest features, but I do recommend the LTS version since that’s what we’ll be using for this course.

So to download it, go ahead and click on the LTS button. You’ll be then prompted to download the package. Go ahead and save. So then after the package has been installed, you’ll wanna go ahead and run your installer for your appropriate operating system, so this may be different, because I am on a Mac.

So after you run the installer, you’ll be prompted and it’ll let you know you’ll be installing Node and npm, so to install Node, you’ll need to agree to the software license agreement. So if you wanna go ahead and pause the video and read that.

Then next you’ll see you’ll go ahead and continue through the prompts until you install Node on your machine. This may take a few minutes. All right, so to verify if Node is installed and working correctly, let’s go ahead and open up a new terminal or command prompt. And then once you’re there, if you go ahead and do node -v, it’ll show you which version of Node that you currently have installed on your machine, and which one’s been resolved. And then also, if you do npm -v, it’ll show you which version of npm is currently installed as well.

Interested in continuing? Check out the full Node.js and Express for Game Development course, which is part of our MMORPG Academy.

]]>