GameCrew AIEarly access
Sign in
Godot 4gameplayRevision 1 · Compile-verified pattern

Solo-First Multiplayer Rooms, Shared State & Host Migration with GameNet in Godot 4

Updated

Browser-ready multiplayer in Godot 4 using the studio's GameNet autoload: solo-first host authority, 60 Hz interpolated avatars, host-validated events and shared world state, seamless host migration, and deterministic GameNet.sim() PlayMode tests.

  • multiplayer
  • networking
  • rooms
  • lobby
  • co-op
  • rp
  • avatars
  • interpolation
  • host-migration
  • gamenet

No demo.

When to Use (and When Not To)

Use GameNet (Assets/CCGD/net/game_net.gd) for every Godot 4 game declaring "multiplayer" in game.json — including open-world city roleplay hubs, co-op exploration adventures, party arenas, and shared racing tracks.

Never instantiate WebSocketPeer, ENetMultiplayerPeer, WebRTCMultiplayerPeer, or SceneMultiplayer manually: the studio's web shell already provides room codes, invite URLs (#room=CODE), seat resumption, and WebSocket relay transport directly to GameNet.

Mathematical & Algorithmic Core

  1. Solo-First Host Authority: Offline or alone in a room, GameNet.is_host() is true and GameNet.players() contains [GameNet.me()] (slot = 0). Keep all authoritative timers, job payouts, pickups, and NPC spawns behind if GameNet.is_host(): and push compact dictionary patches through GameNet.set_state({...}).
  2. 20 Hz Delta Poses / 60 Hz Interpolated Avatars: Call GameNet.set_my_pose(global_position, rotation.y, anim_state) inside _physics_process. GameNet.bind_avatar(world_root, factory) automatically spawns, interpolates along shortest angular delta Δpsi ∈ [-π, π), and frees remote peer nodes.
  3. Host-Authoritative Claims + Automatic Host Migration: Guests request shared mutations via GameNet.send_event("claim_job", {"id": id}, "host"). Connect GameNet.on_host_change so if Peer 1 closes their tab, the newly promoted host seamlessly continues stepping shared world simulation from the current GameNet.state().

Engine Implementation

Shared Room Jobs & Avatar Sync (Assets/Game/net/coop_world_sync.gd)

class_name CoopWorldSync
extends Node

@export var player_path: NodePath
@export var avatars_root_path: NodePath
@export var spawn_points: Array[NodePath] = []

var _player: Node3D
var _avatars_root: Node3D
var _claimed_jobs: Dictionary = {}
var _scores: Dictionary = {}

func _ready() -> void:
	_player = get_node_or_null(player_path) as Node3D
	_avatars_root = get_node_or_null(avatars_root_path) as Node3D
	_place_at_spawn_slot(GameNet.spawn_index())

	if _avatars_root != null:
		GameNet.bind_avatar(_avatars_root, _build_remote_avatar)

	GameNet.on_event("claim_job", _on_claim_job_request)
	GameNet.on_state(_on_room_state_changed)
	GameNet.on_host_change(_on_host_changed)

	if GameNet.is_host():
		GameNet.set_state({"claimed_jobs": {}, "scores": {}})

func _physics_process(_delta: float) -> void:
	if _player != null:
		var anim := "idle"
		if _player.has_method("get_anim_state"):
			anim = str(_player.call("get_anim_state"))
		GameNet.set_my_pose(_player.global_position, _player.rotation.y, anim)

func request_complete_job(job_id: String, reward: int) -> void:
	if GameNet.is_host():
		_apply_job_claim(job_id, reward, str(GameNet.me().get("id", "1")))
	else:
		GameNet.send_event("claim_job", {"id": job_id, "reward": reward}, "host")

func _on_claim_job_request(data: Variant, from_peer: Dictionary) -> void:
	if not GameNet.is_host() or not (data is Dictionary):
		return
	var d := data as Dictionary
	var job_id := str(d.get("id", ""))
	var reward := clampi(int(d.get("reward", 0)), 0, 500)
	if job_id.is_empty():
		return
	_apply_job_claim(job_id, reward, str(from_peer.get("id", "")))

func _apply_job_claim(job_id: String, reward: int, peer_key: String) -> void:
	if _claimed_jobs.has(job_id):
		return
	_claimed_jobs[job_id] = peer_key
	_scores[peer_key] = int(_scores.get(peer_key, 0)) + reward
	GameNet.set_state({
		"claimed_jobs": _claimed_jobs.duplicate(),
		"scores": _scores.duplicate(),
	})
	GameNet.send_event("job_done_fx", {"id": job_id, "by": peer_key}, "all")

func _on_room_state_changed(state: Dictionary, _patch: Dictionary) -> void:
	var remote_claimed: Variant = state.get("claimed_jobs", null)
	if remote_claimed is Dictionary:
		_claimed_jobs = (remote_claimed as Dictionary).duplicate()
	var remote_scores: Variant = state.get("scores", null)
	if remote_scores is Dictionary:
		_scores = (remote_scores as Dictionary).duplicate()

func _on_host_changed(now_host: bool) -> void:
	if now_host:
		GameNet.set_state({
			"claimed_jobs": _claimed_jobs.duplicate(),
			"scores": _scores.duplicate(),
		})

func _build_remote_avatar(peer: Dictionary) -> Node3D:
	var root := Node3D.new()
	var body := MeshInstance3D.new()
	var mesh := CapsuleMesh.new()
	mesh.radius = 0.34
	mesh.height = 1.65
	body.mesh = mesh
	body.position.y = 0.82
	var mat := StandardMaterial3D.new()
	mat.albedo_color = GameNet.color_for(peer)
	mat.roughness = 0.45
	body.material_override = mat
	root.add_child(body)
	return root

func _place_at_spawn_slot(slot: int) -> void:
	if _player == null or spawn_points.is_empty():
		return
	var node := get_node_or_null(spawn_points[absi(slot) % spawn_points.size()]) as Node3D
	if node != null:
		_player.global_transform = node.global_transform

Performance & Platform Traps

  • Never Block Startup on a Lobby Screen: Players click Play expecting immediate world interaction; solo mode runs locally with GameNet.is_host() == true until they join or invite friends via the shell's room button.
  • Avoid Per-Frame set_state Calls: Publish set_state only when discrete world truth changes (or at <= 10 Hz for shared moving NPCs/vehicles); player movement already rides the dedicated 20 Hz pose stream.
  • Deterministic Multi-Peer PlayMode Coverage: Always add a GameTest script using GameNet.sim() that adds a peer, checks interpolated GameNet.pose_of(peer.id), validates a guest-to-host event, and exercises sim.drop_host().

Verification Checklist

  1. Verify solo play starts immediately with zero network errors when GameNet.active() is false.
  2. In Assets/Game/Tests/play/, run GameNet.sim() with a remote peer and confirm pose_of, set_state, and drop_host() host promotion all pass deterministically.
  3. Confirm remote avatars remain grounded and free of physics collision fights with the local player.

Official references

  • Glenn Fiedler (Gaffer on Games — State Synchronization & Snapshot Interpolation)
  • GameCrew Godot 4 GameNet Specification

More Godot 4 games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Godot 4 games here look like.

Fernlight — Raise a carved whistle to your lips in a fog-drowned forest, coax a glowing bird onto your open hand, and point to send it off to light the dark.
Plays in VR

Fernlight

Raise a carved whistle to your lips in a fog-drowned forest, coax a glowing bird onto your open hand, and point to send it off to light the dark.

More Godot 4 techniques

physics

Arcade Raycast Vehicle Physics, Enter/Exit Driving & Modular City RP Loop in Godot 4 →

Crisp 4-wheel raycast spring-damper vehicle physics on RigidBody3D in Godot 4 with controllable drifting, seamless CharacterBody3D enter/exit driving handoff, and MultiMeshInstance3D modular city/traffic loops that hold 60 fps in WebGL.

physics

CharacterBody3D Slopes, Snap & Coyote Jump in Godot 4 →

Crisp Godot 4 CharacterBody3D locomotion combining floor_snap_length, apex hang gravity, jump-cut, coyote time, and zero-arg move_and_slide.

vr

Physical 6DoF VR Hand Interactions, Throw Windows & Spatial Comfort in Godot 4 →

Physical 6DoF VR hand interactions in Godot 4 using GameXR and XRInteract: the kit's articulated hands (controller-posed and hand-tracked, pinch and grab with hysteresis, power/pinch/sphere grip poses), near-grab + distance-pull cones, 6-step sliding-window throws, snap holsters, 3D buttons, teleport + smooth + seated comfort, and flat+VR parity.

water

Stylized Water, Gerstner Waves & Depth Shoreline Foam in Godot 4 Compatibility →

Godot 4.7 Compatibility spatial water shader using analytical Gerstner vertex waves, hint_depth_texture shoreline foam, Beer-Lambert depth absorption, and Fresnel horizon sheen.

Read via free MCP — or sign in to add techniques & beta test

Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.

Connect via MCP