How to make a multiplayer game in Godot 3

Introduction

This article is intended for people who want to learn how to use Godot 3 to make a multiplayer game with no experience in the network field.The magic with Godot is that the majority of the difficulty with multiplayer is hidden by the engine itself.

I’ve attached a sample game with source code, you can download it and read it to better understand how it works. This program is pretty easy to use, you launch one instance as a server and many others as clients that connect to the server.

Even though I’ve been developing games for several decades and have used multiple engines in the past, my experience with Godot is quite recent (only a few months), so if you see anything horrible in the code, please let me know.

https://github.com/cobolfoo/godot3-spacegame/

Description of the game

It’s an arcade top-down space combat game. You use WASD to move and SPACEBAR to shoot. When you die, you reappear at a random location. A server is used to host the game space. Clients connect to the server to control a ship. There is a login form that asks for the player’s name and the color of the ship.

First, let’s start with the server:

To start a server, it’s pretty easy. You create a new scene containing any kind of node (I used Node). You create a script and attach to this node. You put this code in your script:

func _ready(): 
    var peer = NetworkedMultiplayerENet.new()
    var result = peer.create_server(5555, 32)
    get_tree().set_network_peer(peer) 
    get_tree().connect("network_peer_connected", self, "player_connected")
    get_tree().connect("network_peer_disconnected", self, "player_disconnected") 

func player_connected(id): 
    print("Callback: player_connected:", id) 

func player_disconnected(id): 
     print("Callback: player_disconnected:", id) 

This code create a server listening on port 5555 and allow up to 32 connections. If someone connect, player_connected function will be called. The same for disconnection with the  player_disconnect function.That’s it, you have a basic server running now.

On the client:

This is pretty much the same thing, you create a scene, add a node and a script, then you type:

func _ready(): var peer = NetworkedMultiplayerENet.new()     peer.create_client("127.0.0.1", 5555)     get_tree().set_network_peer(peer)   get_tree().connect("connected_to_server", self, "client_connected_ok")     get_tree().connect("connection_failed", self, "client_connected_fail")     get_tree().connect("server_disconnected", self, "server_disconnected") func client_connected_ok():     print("Callback: client_connected_ok") func server_disconnected():     print("Callback: server_disconnected") func client_connected_fail():     print("Callback: client_connected_fail") read more