10. Multiple Players

Introduction

This tutorial will cover how to add multiple players to the GameScreen. Fortunately we have programmed almost everything to support multiple MainShips from the beginning, so this tutorial will not require too much work.

Detecting number of players

Most games include two requirements for a new player to join the game:

  1. A controller must be connected for the player
  2. The player must perform some action (such as pressing a button in a join screen)

To keep the tutorial shorter than it would otherwise be, we will assume that if a controller is connected, then the player intends to play. If you are developing a game which you intend to distribute to others, you should consider giving the player more freedom such as being able to drop out of a game and to require explicit action to join.

Adding additional players

To add additional players we will detect how many controllers are connected, and create additional players as necessary. To do this:

  1. Open GameScreen.cs in Visual Studio
  2. Find the CustomInitialize function
  3. Add the following code to CustomInitialize:

Next we’ll need to implement AddAdditionalShips. Add the following function to GameScreen.cs:

Now that we’re assigning the PlayerIndex we’ll need to make a variable for it in Glue. To do this:

  1. Open MainShip.cs in Visual Studio
  2. Add the following field and property to MainShip.cs:

RockBlasterMultipleShips.png

Changing the look of the ship

Currently all players are using the same image for the ship. When we initially set up our Entity we added four PNG files. We have all four available to use, so let’s modify the PlayerIndex property to change the texture according to the player index.

Change the PlayerIndex property so it reads:

RockBlasterDifferentShipTextures.png

Conclusion

Now each ship will use a different texture so that players will be able to tell each other apart. The next tutorial will improve on the way player death is handled by adding the concept of player health and a health bar.

<- 09. Hud11. Health ->