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).
First, create a cube (by navigating to GameObject | Create Other | Cube) and scale it to 1 x 1 x 4. Name it Paddle
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:
- Firstly, set the camera to Orthographic and position it at (
0
, 10
, 0
). 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. - Create a directional light that points straight down. This will illuminate the paddles and ball to make them pure white.
- Finally, duplicate the player paddle and move it to the other half of the field.
Now we're going to create the Ball script. We'll add the multiplayer code later, for now this is offline only:
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 (0
, 0
, 0
). Add a rigidbody component to the cube, untick the Use Gravity checkbox, and tick the Is Kinematic checkbox. The Rigidbody
component is used to let our ball get the OnTriggerEnter
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).
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 AcceptsInput
field is for):
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.
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:
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:
Attach this script to both goals. For player 1's goal, set the Player to 2
(player 2 gets a point when the ball lands in player 1's goal), for player 2's goal, set the Player to 1
(player 1 gets a point when the ball lands in player 2's goal).
The game is almost completely functional now (aside from multiplayer). One problem is that we can't tell that points are being given until the game ends, so let's add a score display.
Displaying the score to the player
Create two 3D Text objects as children of the scorekeeper. Name them p1Score
and P2Score
, and position them on each side of the field:
Let's make the scorekeeper display the player scores:
The score is now displayed properly when a player gets a point. Be sure to give it a test run—the ball should bounce around the field, and you should be able to deflect the ball with the paddle. If the ball hits player 1's goal, player 2 should get 1 point, and vice versa. If one player gets 10 points, both scores should reset to zero, the ball should move back to the center of the screen, and the game should restart.
With the most important gameplay elements complete, we can start working on multiplayer networking.
For testing purposes, let's launch a network game as soon as the level is launched:
If we start this level without hosting a server first, it will automatically do so for us in ensuring that the networked code still works.
Now we can start converting our code to work in multiplayer.
Let's start by networking the paddle code:
The paddle will detect whether it is owned by the local player or not. If not, it will not accept player input, instead it will interpolate its position to the last read position value over the network.
By default, network views will serialize the attached transform. This is OK for testing, but should not be used for production. Without any interpolation, the movement will appear very laggy and jerky, as positions are sent a fixed number of times per second (15 by default in Unity Networking) in order to save on bandwidth, so snapping to the position 15 times per second will look jerky. In order to solve this, rather than instantly snapping to the new position we smoothly interpolate towards it. In this case, we use the frame delta multiplied by a number (larger is faster, smaller is slower), which produces an easing motion; the object starts quickly approaching the target value, slowing down as it gets closer.
When serializing, it either reads the position and stores it, or it sends the current transform position, depending on whether the stream is for reading or for writing.
Now, add a Network View to one of your paddles, drag the panel component attached to the Paddle into the Observed slot, and make it a prefab by dragging it into your Project pane.
Next, delete the paddles in the scene, and create two empty game objects where the paddles used to be positioned. These will be the starting points for each paddle when spawned.
Next, let's make the scorekeeper spawn these paddles. The scorekeeper, upon a player connecting, will send an RPC to them to spawn a paddle:
At the moment, when you start the game, one paddle spawns for player 1, but player 2 is missing (there's nobody else playing). However, the ball eventually flies off toward player 2's side, and gives player 1 a free point.
Let's keep the ball frozen in place when there's nobody to play against, or if we aren't the server. We're also going to add networked movement to our ball:
The ball will stay put if there's nobody to play against, and if someone we're playing against leaves, the ball will reset to the middle of the field. The ball will also work correctly on multiple machines at once (it is simulated on the server, and position/velocity is relayed to clients). Add NetworkView to the ball and have it observe the Ball component.
There is one final piece of the puzzle that is keeping score. We're going to convert our AddScore
function to use an RPC, and if a player leaves we will also reset the scores:
Our game is fully networked at this point. The only problem is that we do not yet have a way to connect to the game. Let's write a simple direct connect dialog which allows players to enter an IP address to join.
Note
With direct IP connect, note that NAT punch-through is not possible. When you use the Master Server, you can pass either HostData or GUID of a host which will perform NAT punch-through.
The following script shows the player IP and Port entry fields, and the Connect and Host buttons. The player can directly connect to an IP and Port, or start a server on the given Port. By using direct connect we don't need to rely on a master server, as players directly connect to games via IP. If you wanted to, you could easily create a lobby screen for this instead of using direct connect (allowing players to browse a list of running servers instead of manually typing IP address). To keep things simpler, we'll omit the lobby screen in this example:
With this, we now have a complete, fully functional multiplayer Pong game. Players can host games, as well as join them if they know the IP.
When in a game as the host, the game will wait for another player to show up before starting the game. If the other player leaves, the game will reset and wait again. As a player, if the host leaves it goes back to the main menu.