Stagner | Unity Multiplayer Games | E-Book | www.sack.de
E-Book

E-Book, Englisch, 242 Seiten

Stagner Unity Multiplayer Games

Take your gaming development skills into the online multiplayer arena by harnessing the power of Unity 4 or 3. This is not a dry tutorial – it uses exciting examples and an enthusiastic approach to bring it all to life.
1. Auflage 2025
ISBN: 978-1-84969-233-5
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)

Take your gaming development skills into the online multiplayer arena by harnessing the power of Unity 4 or 3. This is not a dry tutorial – it uses exciting examples and an enthusiastic approach to bring it all to life.

E-Book, Englisch, 242 Seiten

ISBN: 978-1-84969-233-5
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)



Unity is a game development engine that is fully integrated with a complete set of intuitive tools and rapid workflows used to create interactive 3D content. Multiplayer games have long been a staple of video games, and online multiplayer games have seen an explosion in popularity in recent years. Unity provides a unique platform for independent developers to create the most in-demand multiplayer experiences, from relaxing social MMOs to adrenaline-pumping competitive shooters.

A practical guide to writing a variety of online multiplayer games with the Unity game engine, using a multitude of networking middleware from player-hosted games to standalone dedicated servers to cloud multiplayer technology. You can create a wide variety of online games with the Unity 4 as well as Unity 3 Engine.

You will learn all the skills needed to make any multiplayer game you can think of using this practical guide. We break down complex multiplayer games into basic components, for different kinds of games, whether they be large multi-user environments or small 8-player action games. You will get started by learning networking technologies for a variety of situations with a Pong game, and also host a game server and learn to connect to it.Then, we will show you how to structure your game logic to work in a multiplayer environment. We will cover how to implement client-side game logic for player-hosted games and server-side game logic for MMO-style games, as well as how to deal with network latency, unreliability, and security.

You will then gain an understanding of the Photon Server while creating a star collector game; and later, the Player.IO by creating a multiplayer RTS prototype game. You will also learn using PubNub with Unity by creating a chatbox application. Unity Multiplayer Games will help you learn how to use the most popular networking middleware available for Unity, from peer-oriented setups to dedicated server technology.

Stagner Unity Multiplayer Games jetzt bestellen!

Autoren/Hrsg.


Weitere Infos & Material


Creating a multiplayer Pong game


Now that we've covered the basics of using Unity Networking, we're going to apply them to creating a multiplayer Pong clone.

The game will play pretty much as standard Pong. Players can choose their name, and then view a list of open servers (full rooms will not be shown). Players can also host their own game.

Once in a game, players bounce a ball back and forth until it hits the opponent's side. Players get one point for this, and the ball will reset and continue bouncing. When a player hits 10 points, the winner is called, the scores are reset, and the game continues. While in a match with no other players, the server will inform the user to wait. If a player leaves, the match is reset (if the host leaves, the other player is automatically disconnected).

Preparing the Field


First, create a cube (by navigating to GameObject | Create Other | Cube) and scale it to 1 x 1 x 4. Name it and set the Tag to Player. Check the Is Trigger box on the collider.

Our ball will detect when it hits the trigger zone on the player paddle, and reverse direction. We use triggers because we don't necessarily want to simulate the ball realistically with the Unity physics engine (we get far less control over the ball's physics, and it may not behave exactly as we would like).

We will also line our playing field in trigger boxes. For these you can duplicate the paddle four times and form a large rectangle outlining the playing field. The actual size doesn't matter so much, as long as the ball has room to move around. We will add two more tags for these boundaries: Boundary and Goal. The two boxes on the top and bottom of the field are tagged as Boundary, the two boxes on the left and right are tagged as Goal.

When the ball hits a trigger tagged Boundary, it reverses its velocity along the z axis. When the ball hits a trigger tagged Player, it reverses its velocity along the x axis. And when a ball hits a trigger tagged Goal, the corresponding player gets a point and the ball resets.

Let's finish up the playing field before writing our code:

  1. Firstly, set the camera to Orthographic and position it at (, , ). Rotate it 90 degrees along the x axis until it points straight down, and change its Orthographic Size to a value large enough to frame the playing field (in my case, I set it to 15). Set the camera's background color to black.
  2. Create a directional light that points straight down. This will illuminate the paddles and ball to make them pure white.
  3. Finally, duplicate the player paddle and move it to the other half of the field.

The Ball script


Now we're going to create the Ball script. We'll add the multiplayer code later, for now this is offline only:

using UnityEngine; using System.Collections; public class Ball : MonoBehavior { // the speed the ball starts with public float StartSpeed = 5f; // the maximum speed of the ball public float MaxSpeed = 20f; // how much faster the ball gets with each bounce public float SpeedIncrease = 0.25f; // the current speed of the ball private float currentSpeed; // the current direction of travel private Vector2 currentDir; // whether or not the ball is resetting private bool resetting = false; void Start() { // initialize starting speed currentSpeed = StartSpeed; // initialize direction currentDir = Random.insideUnitCircle.normalized; } void Update() { // don't move the ball if it's resetting if( resetting ) return; // move the ball in the current direction Vector2 moveDir = currentDir * currentSpeed * Time.deltaTime; transform.Translate( new Vector3( moveDir.x, 0f, moveDir.y ) ); } void OnTriggerEnter( Collider other ) { if( other.tag == "Boundary" ) { // vertical boundary, reverse Y direction currentDir.y *= -1; } else if( other.tag == "Player" ) { // player paddle, reverse X direction currentDir.x *= -1; } else if( other.tag == "Goal" ) { // reset the ball StartCoroutine( resetBall() ); // inform goal of the score other.SendMessage( "GetPoint", SendMessageOptions.DontRequireReceiver ); } // increase speed currentSpeed += SpeedIncrease; // clamp speed to maximum currentSpeed = Mathf.Clamp( currentSpeed, StartSpeed, MaxSpeed ); } IEnumerator resetBall() { // reset position, speed, and direction resetting = true; transform.position = Vector3.zero; currentDir = Vector3.zero; currentSpeed = 0f; // wait for 3 seconds before starting the round yield return new WaitForSeconds( 3f ); Start(); resetting = false; } }

To create the ball, as before we'll create a cube. It will have the default scale of 1 x 1 x 1. Set the position to origin (, , ). Add a rigidbody component to the cube, untick the Use Gravity checkbox, and tick the Is Kinematic checkbox. The component is used to let our ball get the events. Is Kinematic is enabled because we're controlling the ball ourselves, rather than using Unity's physics engine.

Add the new Ball component that we just created and test the game. It should look something like this:

You should see the ball bouncing around the field. If it hits either side, it will move back to the center of the field, pause for 3 seconds, and then begin moving again. This should happen fairly quickly, because the paddles aren't usable yet (the ball will often bounce right past them).

The Paddle script


Let's add player control to the mix. Note that at the moment player paddles will both move in tandem, with the same controls. This is OK, later we'll disable the player input based on whether or not the network view belongs to the local client (this is what the field is for):

using UnityEngine; using System.Collections; public class Paddle : MonoBehavior { // how fast the paddle can move public float MoveSpeed = 10f; // how far up and down the paddle can move public float MoveRange = 10f; // whether this paddle can accept player input public bool AcceptsInput = true; void Update() { // does not accept input, abort if( !AcceptsInput ) return; //get user input float input = Input.GetAxis( "Vertical" ); // move paddle Vector3 pos = transform.position; pos.z += input * MoveSpeed * Time.deltaTime; // clamp paddle position pos.z = Mathf.Clamp( pos.z, -MoveRange, MoveRange ); // set position transform.position = pos; } }

You can now move the paddles up and down, and bounce the ball back and forth. The ball will slowly pick up speed as it bounces, until it hits either of the goals. When that happens, the round resets.

Keeping score


What we're going to do now is create a scorekeeper. The scorekeeper will keep track of both players' scores, and will later keep track of other things, such as whether we're waiting for another player to join:

using UnityEngine; using System.Collections; public class Scorekeeper : MonoBehavior { // the maximum score a player can reach public int ScoreLimit = 10; // Player 1's score private int p1Score = 0; // Player 2's score private int p2Score = 0; // give the appropriate player a point public void AddScore( int player ) { // player 1 if( player == 1 ) { p1Score++; } // player 2 else if( player == 2 ) { p2Score++; } // check if either player reached the score limit if( p1Score >= ScoreLimit || p2Score >= ScoreLimit ) { // player 1 has a better score than player 2 if( p1score > p2score ) Debug.Log( "Player 1 wins" ); // player 2 has a better score than player 1 if( p2score > p1score ) Debug.Log( "Player 2 wins" ); // both players have the same score - tie else Debug.Log( "Players are tied" ); // reset scores and start over p1Score = 0; p2Score = 0; } } }

Now our scorekeeper can keep score for each player, let's make the goals and add points with a Goal script. It's a very simple script, which reacts to the GetPoint message sent from the ball upon collision to give the other player a point:

using UnityEngine; using System.Collections; public class Goal : MonoBehavior { // the player who gets a point for this goal, 1 or 2 public int Player = 1; // the Scorekeeper public Scorekeeper scorekeeper; public void GetPoint() { // when the ball collides with this goal, give the player a point scorekeeper.AddScore( Player ); } }

Attach this script to both goals. For player 1's goal, set the Player to (player 2 gets a point when the ball lands in player 1's goal), for player 2's goal, set the...


Stagner Alan R. :

contacted on 6 may '16 __________ Alan R. Stagner is an independent developer. He was introduced to programming by his father, he sought out different ways to create games in a variety of languages. Most recently, he found the Unity game engine and was instantly hooked, and discovered his love of multiplayer game development. He has also dabbled in database and server programming from time to time, mostly involving PHP and MySQL with recent forays into ASP.NET



Ihre Fragen, Wünsche oder Anmerkungen
Vorname*
Nachname*
Ihre E-Mail-Adresse*
Kundennr.
Ihre Nachricht*
Lediglich mit * gekennzeichnete Felder sind Pflichtfelder.
Wenn Sie die im Kontaktformular eingegebenen Daten durch Klick auf den nachfolgenden Button übersenden, erklären Sie sich damit einverstanden, dass wir Ihr Angaben für die Beantwortung Ihrer Anfrage verwenden. Selbstverständlich werden Ihre Daten vertraulich behandelt und nicht an Dritte weitergegeben. Sie können der Verwendung Ihrer Daten jederzeit widersprechen. Das Datenhandling bei Sack Fachmedien erklären wir Ihnen in unserer Datenschutzerklärung.