Godot High-Level Multiplayer
Godot 4 has networking built into the engine, no plugin needed. The high-level multiplayer API (MultiplayerAPI, reached as multiplayer from any node) gives you peers with numeric ids, RPCs declared with the @rpc annotation, and two nodes that remove most boilerplate: MultiplayerSpawner (replicates node creation and deletion) and MultiplayerSynchronizer (replicates properties). Underneath sits a multiplayer peer: ENet (UDP) for desktop and mobile, WebSocket or WebRTC for web exports. Engine basics are in the Godot course.
Peers and ids
extends Node
const PORT := 7000
const MAX_CLIENTS := 4
func host() -> void:
var peer := ENetMultiplayerPeer.new()
var err := peer.create_server(PORT, MAX_CLIENTS)
if err != OK:
push_error("could not listen on %d" % PORT)
return
multiplayer.multiplayer_peer = peer
multiplayer.peer_connected.connect(_on_peer_connected)
multiplayer.peer_disconnected.connect(_on_peer_disconnected)
func join(address: String) -> void:
var peer := ENetMultiplayerPeer.new()
peer.create_client(address, PORT)
multiplayer.multiplayer_peer = peer
multiplayer.connected_to_server.connect(func(): print("connected as ", multiplayer.get_unique_id()))
multiplayer.connection_failed.connect(func(): print("connection failed"))
multiplayer.server_disconnected.connect(func(): print("server gone"))
func _on_peer_connected(id: int) -> void:
print("peer joined: ", id)
func _on_peer_disconnected(id: int) -> void:
print("peer left: ", id)The server is always peer 1; clients get random positive ids. multiplayer.is_server() tells you which side you're on, and peer_connected / peer_disconnected fire on every peer when someone joins or leaves.
RPCs with @rpc
An RPC is an ordinary method with an annotation. Its arguments are, in this order for the last one:
| Argument | Values | Default |
|---|---|---|
| mode | "authority" (only the node's multiplayer authority may call it remotely) or "any_peer" |
"authority" |
| sync | "call_remote" (not run locally) or "call_local" (also run on the caller) |
"call_remote" |
| transfer mode | "unreliable", "unreliable_ordered", "reliable" |
"reliable" |
| channel | an integer, always last | 0 |
So a bare @rpc means @rpc("authority", "call_remote", "reliable", 0). You call an RPC with .rpc(args) (all peers) or .rpc_id(peer_id, args) (one peer):
extends CharacterBody2D
const SPEED := 200.0
var server_input := Vector2.ZERO # last input received from the owning client
func _ready() -> void:
# The player node is named after its peer id when the server spawns it ("2", "1843…").
# Movement stays server-authoritative; only input comes from the client.
set_multiplayer_authority(1)
func _physics_process(delta: float) -> void:
if str(multiplayer.get_unique_id()) == name: # this is my player
var dir := Input.get_vector("left", "right", "up", "down")
send_input.rpc_id(1, dir) # inputs to the server, every physics tick
if multiplayer.is_server():
velocity = server_input * SPEED
move_and_slide() # the server moves everyone
@rpc("any_peer", "call_local", "unreliable_ordered")
func send_input(dir: Vector2) -> void:
if not multiplayer.is_server():
return
var sender := multiplayer.get_remote_sender_id()
if str(sender) != name: # only the owner may steer this player
return
server_input = dir.limit_length(1.0) # never trust the client
@rpc("authority", "call_local", "reliable")
func announce_hit(damage: int) -> void:
print("%s took %d damage" % [name, damage]) # cosmetic, sent by the serverNotes:
"any_peer"is required for client → server calls, because by default the server is the authority of every node. Inside, checkmultiplayer.get_remote_sender_id()against the player the call claims to control."call_local"lets the listen-server host use the same code path as remote players: on the host,get_remote_sender_id()returns its own id (1) for a local call."unreliable_ordered"fits a stream of inputs or positions (late ones are dropped, never applied out of order). Use"reliable"for events that must arrive.set_multiplayer_authority(id)changes a node's authority (it doesn't propagate to children unless you passrecursive, which is the defaulttrue).is_multiplayer_authority()asks "do I own this node?". An alternative design gives each client authority over its own player node; that's simpler but trusts clients with their position.
Spawning and synchronizing without RPCs
MultiplayerSpawner watches one node (its spawn_path). When the authority adds an instance of a registered scene there (add_spawnable_scene() or the Auto Spawn List in the inspector), the spawner creates it on every peer; removing it despawns it everywhere. For instances that need setup data, set spawn_function and call spawn(data) on the authority. spawn_limit caps the count.
MultiplayerSynchronizer replicates properties of nodes under its root_path, from the multiplayer authority to other peers. You pick the properties in the editor's Replication panel, which edits its SceneReplicationConfig:
| Replication mode | Behaviour |
|---|---|
Always (REPLICATION_MODE_ALWAYS) |
sent every replication_interval (0 = each process frame), unreliable |
On Change (REPLICATION_MODE_ON_CHANGE) |
sent reliably, only when the value changes (delta_interval) |
| Never | not synced after spawn |
Each property can also be marked spawn (sent once with the spawn). Visibility is per peer: public_visibility, set_visibility_for(peer, visible) and add_visibility_filter(callable) give you basic interest management (see Interest Management).
# player.gd: the server owns the synchronizer, so positions flow server -> clients
func _enter_tree() -> void:
$MultiplayerSynchronizer.set_multiplayer_authority(1)
$MultiplayerSynchronizer.add_visibility_filter(_is_visible_to)
func _is_visible_to(peer_id: int) -> bool:
return peer_id == 1 or _distance_to_player(peer_id) < 800.0 # your own distance helperWeb exports
Browsers can't open raw UDP sockets, so a web build uses WebSocketMultiplayerPeer (create_server(port) on the server, create_client("wss://…") in the game) or WebRTCMultiplayerPeer with your own signalling. Everything above the peer (RPCs, spawners, synchronizers) stays the same. See WebSocket, WebRTC & Colyseus.
A model of the @rpc rules
What does Godot check when an RPC packet arrives? The model below runs the receiving side's checks for a few calls on a player node named "2" (server authority): is the method an RPC at all, does the mode allow this sender, and then your own sender check inside the function.
type Mode = 'authority' | 'any_peer';
interface RpcConfig { mode: Mode; sync: 'call_local' | 'call_remote'; transfer: string }
const SERVER = 1;
const node = { name: '2', authority: SERVER, x: 0 };
const rpcs: Record<string, RpcConfig> = {
send_input: { mode: 'any_peer', sync: 'call_local', transfer: 'unreliable_ordered' },
announce_hit: { mode: 'authority', sync: 'call_local', transfer: 'reliable' },
};
function receive(method: string, sender: number, arg: number): string {
const cfg = rpcs[method];
if (!cfg) return `refused: ${method} is not marked @rpc`;
if (cfg.mode === 'authority' && sender !== node.authority)
return `refused: ${method} is "authority" mode and peer ${sender} is not the authority`;
// From here on it is your code inside the function.
if (method === 'send_input') {
if (String(sender) !== node.name) return `ignored by game code: peer ${sender} can't steer player ${node.name}`;
const dir = Math.max(-1, Math.min(1, arg));
node.x += dir * 4;
return `ok: input ${arg} clamped to ${dir}, x = ${node.x}`;
}
return `ok: ${method}(${arg}) runs on this peer (${cfg.transfer})`;
}
const calls: [string, number, number][] = [
['send_input', 2, 1], // the owner steers right
['send_input', 2, 50], // a modded client sends a huge input
['send_input', 3, -1], // another client tries to steer player 2
['announce_hit', 3, 99], // a client fakes a server event
['announce_hit', 1, 25], // the server announces a hit
['give_gold', 2, 1000], // a method without @rpc
];
for (const [m, s, a] of calls) console.log(`${m.padEnd(12)} from ${s}: ${receive(m, s, a)}`);send_input from 2: ok: input 1 clamped to 1, x = 4
send_input from 2: ok: input 50 clamped to 1, x = 8
send_input from 3: ignored by game code: peer 3 can't steer player 2
announce_hit from 3: refused: announce_hit is "authority" mode and peer 3 is not the authority
announce_hit from 1: ok: announce_hit(25) runs on this peer (reliable)
give_gold from 2: refused: give_gold is not marked @rpc
The engine handles the first two layers (non-RPC methods and "authority" mode). Clamping inputs and checking who steers what is your code, on the server, every time.
Test yourself
What does a bare @rpc annotation mean in Godot 4?
@rpc("any_peer", "call_local", "unreliable", 0)@rpc("authority", "call_remote", "reliable", 0)- The method can't be called remotely
@rpc("authority", "call_local", "unreliable_ordered", 1)
A client must send its input to the server through an RPC on a node the server is authority of. Which mode does the method need?
- "authority"
- "any_peer"
- "call_local"
- No annotation
Which node replicates the creation and removal of player scenes to every peer?
- MultiplayerSynchronizer
- MultiplayerSpawner
- ENetMultiplayerPeer
- SceneReplicationConfig