Okay, let's create a basic Peer-to-Peer (P2P) multiplayer example in Godot 4.4.
Concept:
- P2P: No central server. One player acts as the "host" (similar to a server function but not strictly required). Other players connect directly to the host's IP address.
- Synchronization: We'll synchronize the position of players. When one player moves, that movement is sent to all other connected players.
- Authority: In P2P, we often rely on the "host" or designate specific peers as authoritative for certain actions or entities. Here, we'll let the player instance that represents a specific peer control its own movement and broadcast its position. The host will manage spawning players.
- RPCs: We'll use Godot's built-in Remote Procedure Calls (
rpc) to send messages (like position updates) between peers.
Project Setup:
- Create a new Godot Project: Open Godot 4.4 and create a new project.
- Create Scenes:
Player.tscn: This will represent a player character.
Main.tscn: This will be our main game scene, handling UI, connections, and spawning players.
1. Player.tscn Setup
- Root Node: Create a
CharacterBody2D node. Rename it Player.
- Why CharacterBody2D? It's designed for character movement and handles collisions well.
- Add Sprite: Add a
Sprite2D node as a child of Player.
- In the Inspector, assign a texture (e.g., the default Godot icon
icon.svg). You might want to scale it down.
- Add Collision: Add a
CollisionShape2D node as a child of Player.
- In the Inspector, create a new
BoxShape2D (or CapsuleShape2D) for the Shape property. Adjust its size to roughly match the sprite.
- Add Label (Optional): Add a
Label node as a child of Player.
- Position it slightly above the sprite. We'll use this to display the player's ID.
- Attach Script: Create a new script for the
Player node (Player.gd).
Player.gd Script:
extends CharacterBody2D
# Network variables
var peer_id: int = 0
# Movement variables
@export var speed: float = 150.0
var input_vector: Vector2 = Vector2.ZERO
# Called when the node enters the scene tree for the first time.
func _ready():
# Set the label to the peer ID if it's set
if $Label:
$Label.text = str(peer_id)
# Make label only visible to the owner if needed, or just show for debugging
if multiplayer.get_unique_id() != peer_id:
# Maybe disable label for non-owners or style differently
pass
else:
# Add a small offset if desired
$Label.position.y -= 30
# Get input only if this player instance is controlled by the local client
func _unhandled_input(event):
# Check if this player node has authority (is controlled by the local client)
if multiplayer.is_multiplayer_authority():
if event.is_action_pressed("ui_left") or event.is_action_pressed("move_left"):
input_vector.x -= 1
if event.is_action_pressed("ui_right") or event.is_action_pressed("move_right"):
input_vector.x += 1
if event.is_action_pressed("ui_up") or event.is_action_pressed("move_up"):
input_vector.y -= 1
if event.is_action_pressed("ui_down") or event.is_action_pressed("move_down"):
input_vector.y += 1
# --- Handle releasing keys ---
# Note: This needs better input handling (e.g., using _input and storing state)
# For simplicity, we check current state in _physics_process instead of relying solely on press/release events here.
# Update input vector based on current state (better than just press)
input_vector = Vector2.ZERO # Reset each frame before checking state
if Input.is_action_pressed("move_left"): input_vector.x -= 1
if Input.is_action_pressed("move_right"): input_vector.x += 1
if Input.is_action_pressed("move_up"): input_vector.y -= 1
if Input.is_action_pressed("move_down"): input_vector.y += 1
# Normalize diagonal movement
if input_vector.length() > 1:
input_vector = input_vector.normalized()
# Tell other peers about our intended movement (or let them calculate)
# We will use physics process to send the actual position after moving
# A more robust system might send input commands instead of positions
# Movement logic, runs only for the player instance controlled by the local client
func _physics_process(delta):
# --- Input Handling (better place for state checking) ---
if multiplayer.is_multiplayer_authority():
var current_input = Vector2.ZERO
if Input.is_action_pressed("move_left"): current_input.x -= 1
if Input.is_action_pressed("move_right"): current_input.x += 1
if Input.is_action_pressed("move_up"): current_input.y -= 1
if Input.is_action_pressed("move_down"): current_input.y += 1
if current_input.length() > 1:
current_input = current_input.normalized()
input_vector = current_input
# Calculate velocity
velocity = input_vector * speed
# Move the character
move_and_slide()
# Send our new position to other peers via RPC
# The rpc() function automatically sends to all connected peers.
rpc("update_player_state", global_position, rotation) # Include rotation if needed
else:
# If not the authority, we just smoothly move towards the networked position
# For simplicity here, we'll directly set it in the RPC function below,
# but interpolation would be smoother.
pass
# RPC function to update the state of this player node for all clients
# The 'call_local' flag ensures it also runs locally if the caller has authority
@rpc("any_peer", "call_local", 0) # Call on all peers, including self
func update_player_state(new_position: Vector2, new_rotation: float):
# Only update if we are NOT the one controlling this player instance
if not multiplayer.is_multiplayer_authority():
# Direct update (can cause jitter). Interpolation/smoothing is better.
global_position = new_position
rotation = new_rotation
# Update the label to show the authoritative ID if it changed
if $Label and $Label.text != str(peer_id):
$Label.text = str(peer_id)
# If we ARE the authority, this function was also called locally.
# We can ignore the parameters as our state was already updated in _physics_process.
# Function to be called by the main scene to set the player ID/authority
func set_network_id(id: int):
peer_id = id
if $Label:
$Label.text = str(peer_id)
# Set the authority for this node. This determines who controls it.
# 0 means no authority (only relevant for the server if it has authority)
# A specific ID means only that peer can control it.
set_multiplayer_authority(id)
Input Setup:
Go to Project -> Project Settings -> Input Map.
Add the following actions if they don't exist:
move_left (Key: A)
move_right (Key: D)
move_up (Key: W)
move_down (Key: S)
(Note: ui_left, ui_right, etc. are usually mapped to arrow keys by default)
2. Main.tscn Setup
- Root Node: Create a
Node (or Node2D) as the root. Rename it Main.
- Add UI Elements: Add a
Control node as a child (this will be our UI container).
- Add a
VBoxContainer inside the Control node.
- Add the following inside the
VBoxContainer:
Label (Status Label): Text="Status: Disconnected"
LineEdit (IP Address): Placeholder="Enter IP Address (e.g., 127.0.0.1)"
Button (Host Button): Text="Host"
Button (Join Button): Text="Join"
- Add Player Container: Add a
Node2D as a child of Main. Rename it PlayersContainer. This is where player instances will be added.
- Attach Script: Create a new script for the
Main node (Main.gd).
Main.gd Script:
extends Node
# --- Configuration ---
const PORT = 7777 # Port for P2P connection
const MAX_PLAYERS = 4 # Maximum number of peers allowed (including host)
const PLAYER_SCENE_PATH = "res://Player.tscn" # Path to our Player scene
# --- Scene References ---
@onready var status_label = $Control/VBoxContainer/Label
@onready var ip_address_input = $Control/VBoxContainer/LineEdit
@onready var host_button = $Control/VBoxContainer/HostButton
@onready var join_button = $Control/VBoxContainer/JoinButton
@onready var players_container = $PlayersContainer
# --- Networking Variables ---
var player_scene: PackedScene
var players: Dictionary = {} # Stores player nodes, keyed by peer ID
# --- Initialization ---
func _ready():
# Load the player scene
player_scene = load(PLAYER_SCENE_PATH)
if player_scene == null:
printerr("Failed to load Player scene at: ", PLAYER_SCENE_PATH)
return
# Connect button signals
host_button.pressed.connect(_on_host_pressed)
join_button.pressed.connect(_on_join_pressed)
# Set initial UI state
status_label.text = "Status: Idle"
ip_address_input.text = "127.0.0.1" # Default to localhost
# Set up the global multiplayer API
# NOTE: In Godot 4, the multiplayer object is accessed via get_tree().multiplayer
# We don't create a peer directly here, but when buttons are pressed.
# Hide Join UI initially until host is pressed
ip_address_input.visible = false
join_button.visible = false
# --- Host Logic ---
func _on_host_pressed():
status_label.text = "Status: Hosting..."
host_button.disabled = true
join_button.disabled = true
ip_address_input.disabled = true
# Create a ENet multiplayer peer
var peer = ENetMultiplayerPeer.new()
var error = peer.create_server(PORT, MAX_PLAYERS)
if error != OK:
printerr("Error creating server: ", error)
status_label.text = "Status: Failed to host!"
# Re-enable buttons if failed
host_button.disabled = false
join_button.disabled = false
ip_address_input.disabled = false
return
# Assign the peer to the global multiplayer singleton
get_tree().multiplayer.multiplayer_peer = peer
# Connect signals for network events
peer.peer_connected.connect(_on_player_connected)
peer.peer_disconnected.connect(_on_player_disconnected)
# Add the host player (ID 1)
spawn_player(1) # Host is always ID 1
status_label.text = "Status: Hosting. Waiting for players..."
print("Server started on port ", PORT)
# Show IP address to connect to
# You might need to find your actual IP if others connect over a network
# os.get_localip() might work, or use ipconfig/ifconfig
status_label.text += "\nConnect with IP: " + get_ip_address_for_connection()
# --- Join Logic ---
func _on_join_pressed():
var ip_addr = ip_address_input.text.strip_edges()
if ip_addr.is_empty():
printerr("IP address cannot be empty.")
return
status_label.text = "Status: Connecting to %s..." % ip_addr
host_button.disabled = true
join_button.disabled = true
ip_address_input.disabled = true
# Create a ENet multiplayer peer
var peer = ENetMultiplayerPeer.new()
# Create a connection to the specified IP and port
var error = peer.create_connection(ip_addr, PORT)
if error != OK:
printerr("Error connecting: ", error)
status_label.text = "Status: Connection failed!"
# Re-enable buttons if failed
host_button.disabled = false
join_button.disabled = false
ip_address_input.disabled = false
return
# Assign the peer to the global multiplayer singleton
get_tree().multiplayer.multiplayer_peer = peer
# Connect signals for network events
peer.connection_succeeded.connect(_on_connection_succeeded)
peer.connection_failed.connect(_on_connection_failed)
peer.server_disconnected.connect(_on_server_disconnected)
# We don't know our ID yet, it will be assigned upon connection success.
# --- Network Event Handlers ---
func _on_player_connected(id: int):
print("Player connected: ", id)
status_label.text = "Status: Player %d connected." % id
# Spawn a player instance for the newly connected peer
spawn_player(id)
# Tell the newly connected player about existing players
# Loop through players already in the game (including the host)
for existing_id in players:
if existing_id != id: # Don't tell the new player about themselves
rpc_id(id, "update_player_state", players[existing_id].global_position, players[existing_id].rotation)
# Optionally, send the ID so the new player can label them correctly
rpc_id(id, "set_network_id", existing_id) # This calls the function on the *new* player instance, setting *its* peer_id and authority
func _on_player_disconnected(id: int):
print("Player disconnected: ", id)
status_label.text = "Status: Player %d disconnected." % id
# Remove the player node from the scene and dictionary
if players.has(id):
var player_node = players[id]
players.erase(id)
player_node.queue_free()
func _on_connection_succeeded():
var assigned_id = get_tree().multiplayer.multiplayer_peer.get_unique_id()
print("Connection successful! Assigned ID: ", assigned_id)
status_label.text = "Status: Connected successfully."
# Spawn our own player instance
spawn_player(assigned_id)
# Hide Join UI elements now that we are connected
ip_address_input.visible = false
host_button.visible = false
join_button.visible = false
# Tell the server (host) about us if needed, or let the host handle discovery via _on_player_connected
func _on_connection_failed():
printerr("Connection failed.")
status_label.text = "Status: Connection failed."
# Re-enable buttons
host_button.disabled = false
join_button.disabled = false
ip_address_input.disabled = false
# Clear the multiplayer peer
get_tree().multiplayer.multiplayer_peer = null
func _on_server_disconnected():
print("Disconnected from server.")
status_label.text = "Status: Disconnected from host."
# Reset the multiplayer peer
get_tree().multiplayer.multiplayer_peer = null
# Clean up players
for id in players:
players[id].queue_free()
players.clear()
# Reset UI
ip_address_input.visible = true
host_button.visible = true
join_button.visible = true
host_button.disabled = false
join_button.disabled = false
ip_address_input.disabled = false
# --- Player Management ---
func spawn_player(id: int):
if player_scene == null:
printerr("Cannot spawn player, scene not loaded.")
return
var player_instance = player_scene.instantiate()
# Assign the network ID to the player instance script
player_instance.set_network_id(id)
# Add the player instance to the players container
players_container.add_child(player_instance)
# Store the player instance in our dictionary
players[id] = player_instance
# Set random position for fun (optional)
player_instance.global_position = Vector2(randi_range(50, 500), randi_range(50, 300))
# Helper to get IP (basic - may need adjustment for different networks)
func get_ip_address_for_connection() -> String:
# For local testing, 127.0.0.1 is usually sufficient.
# If testing on the same LAN, find your machine's LAN IP address
# (e.g., 192.168.1.X). You can find this using ipconfig (Windows)
# or ifconfig/ip addr (Linux/macOS).
# os.get_localip() can sometimes work but might not be the right IP
# for others on your network to connect to.
# Attempt to get local IP, fallback to localhost
var local_ip = ip_address_input.text # Use the entered IP or default
# You could try: var lan_ip = OS.get_localip()
# But be aware this might not be the IP others need to connect to.
return local_ip
How to Run:
- Build and Run (Host): Press F5 (or the Play button) to run the
Main.tscn. Click the "Host" button. The status label should update, showing the IP address (likely 127.0.0.1 if running locally).
- Build and Run (Second Instance): Run the project again (File -> New Project or duplicate the executable).
- Join: In the second instance, ensure the IP address field shows the correct IP address of the host instance (usually
127.0.0.1 for local testing). Click "Join".
- Play: You should now see two player characters (the Godot icon). Use WASD or Arrow keys in each window to move the corresponding player. Their movements should be mirrored on the other window.
Explanation:
-
Main.gd:
- Handles UI interactions (Host/Join buttons).
- Creates an
ENetMultiplayerPeer.
create_server() starts listening for connections (Host).
create_connection() attempts to connect to another peer (Join).
get_tree().multiplayer.multiplayer_peer = peer assigns the created peer to Godot's global networking singleton. This makes signals like peer_connected available.
_on_player_connected(id): When a new player joins the host, this function is called. It spawns a Player scene instance for that new player using spawn_player(id) and tells the new player about existing players using RPCs (rpc_id).
spawn_player(id): Instantiates the Player.tscn, sets its network ID using player_instance.set_network_id(id), adds it to the scene tree under PlayersContainer, and stores it in the players dictionary. Crucially, set_network_id calls set_multiplayer_authority(id) on the player node.
_on_connection_succeeded(): Called when a joining client successfully connects. It spawns the player locally and hides connection UI.
rpc("update_player_state", ...): Called from the Player.gd script (by the authoritative player) to send its state to all other peers.
rpc_id(id, "set_network_id", ...): Called by the host to tell a specific new peer about an existing player.
rpc_id(id, "update_player_state", ...): Called by the host to tell a specific new peer about the state of an existing player.
-
Player.gd:
set_network_id(id): This function is called by Main.gd after instantiation. It sets the peer_id variable and, most importantly, calls set_multiplayer_authority(id).
is_multiplayer_authority(): Returns true only for the peer whose ID matches the authority set for this specific player node instance.
- Input Handling (
_physics_process): Only the player instance where is_multiplayer_authority() is true processes input and moves using move_and_slide().
- State Synchronization (
_physics_process): After moving, the authoritative player calls to broadcast its new position to everyone.
Important Considerations & Next Steps:
- NAT Traversal: This example only works if players are on the same network or if one player has a publicly accessible IP address and has forwarded the chosen port (PORT=7777 in this case). For connections over the internet between arbitrary users, you'll need techniques like STUN/TURN servers or libraries like LiteLoaderP2P.
- Host Advantage: The host controls its own input and state directly. Other clients rely on the host's broadcast. This can lead to slight discrepancies. True P2P often involves more complex state reconciliation or specific rules about who is authoritative for what.
- Smoothing/Interpolation: Directly setting the position in
update_player_state can look jerky. Implement interpolation (moving smoothly towards the networked position over time) for a better visual experience.
- Error Handling: Add more robust error checks for network operations.
- Game State: Synchronizing just position is basic. You'll need RPCs for actions like shooting, collecting items, health changes, etc.
- Player Identification: Ensure the
set_network_id correctly sets the authority for each player instance. If the host spawns players for others, the host needs to call rpc_id(new_peer_id, "set_network_id", player_id) targeting the player instance on the new peer. The provided code handles this by calling a function on the Main node which then correctly sets up the player.
- Scene Replication: When a player joins late, they need to know about all existing players. The current code handles this by sending
update_player_state and set_network_id RPCs to the new player for all existing players.