Godot Version
4.5 Stable
Question
I’m trying to create a multiplayer game. Since this is my first multiplayer game I started with a simple LAN setup.
How it is supposed to work:
When host_button is pressed it calls DBNetwork.init_server() and when join_button is pressed it calls DBNetwork.init_client(). There’s also a host_and_join_button which tries to host the server and spawn in a player. This triggers the host_player_exists variable.
Code:
DBNetwork.gd:
extends Node
var network_peer : ENetMultiplayerPeer
var DEFAULT_PORT : int = 43500
var LOCAL_IP : String = "localhost"
var MAX_CLIENTS : int = 10
func init_server() -> void:
network_peer = ENetMultiplayerPeer.new()
network_peer.create_server(DEFAULT_PORT, MAX_CLIENTS)
multiplayer.multiplayer_peer = network_peer
print("DBNetwork: Server Hosted Successfully")
func init_client() -> void:
network_peer = ENetMultiplayerPeer.new()
network_peer.create_client(LOCAL_IP, DEFAULT_PORT)
multiplayer.multiplayer_peer = network_peer
print("DBNetwork: Client Created Successfully")
MultiplayerSpawner.gd:
extends MultiplayerSpawner
@export var player_scene : String
@export var host_player_exists : bool = false
func _ready() -> void:
multiplayer.peer_connected.connect(spawn_player)
func spawn_player(id: int) -> void:
if !multiplayer.is_server():
return
var player : CharacterBody3D = load(player_scene).instantiate()
if host_player_exists:
player.name = str(id+1)
else:
player.name = str(id)
get_node(spawn_path).call_deferred("add_child", player)
func _on_host_and_join_button_pressed() -> void:
if !host_player_exists:
spawn_player(1)
host_player_exists = true
else:
print("DystopianBots: Failed To Spawn Player! [Host Player Already Exists]")
Player.gd:
extends CharacterBody3D
@export var SPEED : float = 100.0
@export var camera_sensv : float = 1.0
func _enter_tree() -> void:
set_multiplayer_authority(int(name))
func _ready() -> void:
$playerNameLabel.set_text("Player "+str(name))
func _input(event: InputEvent) -> void:
if !is_multiplayer_authority():
return
## Camera Control Is Unfinished Ignore This
if event is InputEventMouseMotion:
var mouse_pos = get_viewport().get_mouse_position().normalized()
$head.rotation.y = rad_to_deg(mouse_pos.x) * camera_sensv
func _physics_process(delta: float) -> void:
if !is_multiplayer_authority():
return
## Movement Is Unfinished Ignore This
var dir : Vector2 = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down").normalized()
#var facing : Vector3 = -global_transform.basis.z
if is_on_floor():
velocity.x = dir.x * SPEED * delta
velocity.z = dir.y * SPEED * delta
else:
velocity.y -= 9.8 * delta
move_and_slide()
Problem:
It dosen’t work at all. Even though my code logic is fine (imo) and the tutorial I followed was followed correctly.
The Server Hosts and Client Joins successfully (No Debug Errors) but the player doesn’t spawn.
How do I fix this?