Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

Hey, do you know how to make 3D multiplayer in Godot 4?

  1. User

    Hey, do you know how to make 3D multiplayer in Godot 4?

  2. Assistant

    Yes! Creating a 3D multiplayer game in Godot 4 involves several steps, including setting up your 3D scene, implementing networking using Godot’s high-level multiplayer API, synchronizing player states, and handling multiplayer-specific logic.

    Here’s a high-level overview to get you started with 3D multiplayer in Godot 4:

    1. Understand Godot’s Multiplayer API

    Godot 4 uses a high-level networking system based on the SceneTree multiplayer API, which allows you to set up either a server or client and synchronize nodes using RPCs (Remote Procedure Calls).

    2. Set up Your 3D Scene

    Create your 3D scene — for example, a Character scene with a player model, camera, and collision. You can base it on CharacterBody3D for player movement.

    3. Enable Multiplayer in your Project

    No special plugin is needed, it’s built-in.

    4. Create a Network Manager

    Create a script to handle hosting or joining games, connection management, and player spawning.

    extends Node
    
    var is_server = false
    var peer : SceneMultiplayerPeer
    
    func start_server(port=12345):
        var server = NetworkedMultiplayerENet.new()
        server.create_server(port)
        get_tree().multiplayer.peer = server
        is_server = true
        print("Server started on port %d" % port)
        get_tree().connect("network_peer_connected", self, "_on_peer_connected")
        get_tree().connect("network_peer_disconnected", self, "_on_peer_disconnected")
        get_tree().connect("connected_to_server", self, "_on_connected")
        get_tree().connect("connection_failed", self, "_on_connection_failed")
        get_tree().connect("server_disconnected", self, "_on_server_disconnected")
    
    func connect_to_server(ip, port=12345):
        var client = NetworkedMultiplayerENet.new()
        client.create_client(ip, port)
        get_tree().multiplayer.peer = client
        is_server = false
    
    func _on_peer_connected(id):
        print("Peer connected: ", id)
        if is_server:
            # Spawn a player for the connected peer.
            spawn_player(id)
    
    func _on_peer_disconnected(id):
        print("Peer disconnected: ", id)
        # Remove the player instance associated with that peer
    
    func _on_connected():
        print("Connected to server")
    
    func _on_connection_failed():
        print("Failed to connect to server")
    
    func _on_server_disconnected():
        print("Disconnected from server")
    
    func spawn_player(peer_id):
        # This should instance a player scene and set its multiplayer authority
        var player_scene = preload("res://player.tscn")
        var player = player_scene.instantiate()
        player.multiplayer.authority = peer_id
        add_child(player)
        player.name = "Player_%d" % peer_id
    

    5. Create Your Player Scene with Network Synchronization

    Your player should have a script responsible for handling movement and synchronization. Use @rpc annotations for functions that should be called remotely and multiplayer.authority to determine who can control the node.

    Example player movement with networking:

    extends CharacterBody3D
    
    @export var speed : float = 5.0
    
    func _physics_process(delta):
        if multiplayer.is_server() or multiplayer.get_unique_id() == multiplayer.authority:
            var input_dir = Vector3.ZERO
            if Input.is_action_pressed("move_forward"):
                input_dir.z -= 1
            if Input.is_action_pressed("move_backward"):
                input_dir.z += 1
            if Input.is_action_pressed("move_left"):
                input_dir.x -= 1
            if Input.is_action_pressed("move_right"):
                input_dir.x += 1
            
            input_dir = input_dir.normalized()
            
            velocity.x = input_dir.x * speed
            velocity.z = input_dir.z * speed
            velocity.y += -9.8 * delta  # gravity
    
            move_and_slide()
    
            # Send position update to others
            rpc_unreliable("sync_position", global_transform)
    
    @rpc(any_peer, unreliable)
    func sync_position(new_transform : Transform3D):
        if multiplayer.get_unique_id() != multiplayer.authority:
            global_transform = new_transform
    

    6. Testing Multiplayer

    • Run one instance as a server (start_server()).
    • Run other instances as clients (connect_to_server()).
    • You’ll be able to see player instances moving on each peer.

    Tips:

    • Use rpc or rpc_unreliable for sending network messages.
    • Use multiplayer.authority to assign ownership of player nodes.
    • Minimize the data you replicate to reduce bandwidth.
    • Implement smoothing/interpolation on clients for smooth movement.
    • Use NetworkedMultiplayerENet for reliable UDP networking; you can also explore WebSocket if needed.

    If you want, I can provide a sample minimal Godot project or more detailed code examples for specific parts like player interpolation or state synchronization. Let me know!

  3. User

    Look, look, look, I saw it very, very many times on different sites. I need one thing: I am making a game, so I can choose the server that I play on. Server has a name and code. The public servers should be listed in "public list". Private can be found in "the private server field code entry".

  4. Assistant

    Got it! You want a server browser system with:

    • A list of public servers (each with a name and a code),
    • And a field to enter a private server's code to connect directly.

    This is commonly done with a "master server" or a simple central server that keeps track of available public servers, or by having a custom server list stored somewhere.


    How to implement this with Godot 4 (Concept + Example):


    Overview

    1. Server registration: When a server starts, it registers itself with your "master server" or a simple server list backend.
    2. Client gets the list: Clients ask this master server for the current public servers and display them.
    3. Client joins server: Clients can either click a public server or enter a private code to connect.

    Option A - Using a Backend (Recommended for real multiplayer games)

    1. Create a Master Server (can be simple HTTP server or use third-party services)

    • The master server stores a list of active public servers (name, IP, code).
    • Servers send “heartbeats” to it so it knows they are online.
    • Clients download this list on launch or on refresh.

    2. In Godot: Fetch server list from master server via HTTP

    • Use HTTPRequest node to GET the current list of public servers.
    • Display them in UI.

    3. Join server via IP / port or use code

    • Map server code to IP:port so your client knows where to connect.

    Option B - For simpler local or ad-hoc testing (no backend)

    • Hardcode some server names + IPs/codes in a JSON file or dictionary inside your project.
    • Display from local data.
    • Users enter code to find server info from local data or a static dictionary.

    Here's a minimal example of Option A — Godot TCP + HTTP Master List


    Master server concept (simplified)

    • Runs on a known URL (could be a website, or local server).
    • Supports these routes:
    RouteMethodData
    /serversGETReturns list of public servers
    /register_serverPOSTServer sends its info (name, IP, code) to be added

    Godot Client example: Fetch and display server list and join one

    extends Control
    
    @onready var http = $HTTPRequest
    @onready var server_list_container = $ServerListContainer  # e.g. VBoxContainer
    
    const MASTER_SERVER_URL = "https://your-master-server.com/servers"
    
    func _ready():
        refresh_server_list()
    
    func refresh_server_list():
        http.request(MASTER_SERVER_URL, [], false, HTTPClient.METHOD_GET)
    
    func _on_HTTPRequest_request_completed(result, response_code, headers, body):
        if response_code == 200:
            var servers = JSON.parse(body.get_string_from_utf8()).result
            show_servers(servers)
        else:
            print("Failed to fetch server list: %d" % response_code)
    
    func show_servers(servers):
        server_list_container.clear_children()
        for srv in servers:
            var btn = Button.new()
            btn.text = srv["name"] + " (" + srv["code"] + ")"
            btn.pressed.connect(() => join_server(srv["ip"], srv["port"]))
            server_list_container.add_child(btn)
    
    func join_server(ip, port):
        # Logic to start multiplayer connection
        print("Connecting to server %s:%d" % [ip, port])
        # e.g.
        var peer = NetworkedMultiplayerENet.new()
        peer.create_client(ip, port)
        get_tree().multiplayer.peer = peer
    

    Private Server Join Interaction

    @onready var private_code_field = $PrivateCodeField
    @onready var join_private_btn = $JoinPrivateButton
    
    func _on_JoinPrivateButton_pressed():
        var code = private_code_field.text.strip_edges()
        if code == "":
            print("Please enter a server code")
            return
        # Call another HTTP endpoint to get server info by code:
        var url = "https://your-master-server.com/server_by_code?code=%s" % code
        http.request(url, [], false, HTTPClient.METHOD_GET)
    
    func _on_HTTPRequest_request_completed(result, response_code, headers, body):
        if response_code == 200:
            var data = JSON.parse(body.get_string_from_utf8())
            if data.result:
                var server = data.result
                join_server(server.ip, server.port)
            else:
                print("Server code not found!")
        else:
            print("Error fetching server info")
    

    Summary

    • You need a master server backend storing servers (name, ip, port, code).
    • Servers register themselves there each time they start.
    • Clients fetch this list for public servers.
    • Clients lookup private server code against that backend.
    • Then clients connect via ENet to chosen server.

    Without a backend?

    • Just hardcode a dictionary of servers where keys are codes.
    • Use them to populate your list or find private servers.

    If you want I can help you build a simple Godot server list backend in e.g. Python Flask or Node.js and guide the full cycle, or help with just the Godot side.

    Would that be helpful?