diff --git a/game.tscn b/game.tscn index 522e1bd..2e7a0d6 100644 --- a/game.tscn +++ b/game.tscn @@ -30,6 +30,7 @@ PlayerScene = ExtResource("2_iv2f7") [node name="Players" type="Node3D" parent="."] [node name="Local" parent="Players" instance=ExtResource("2_iv2f7")] +IsLocal = true [node name="OutlineViewportContainer" type="SubViewportContainer" parent="."] material = SubResource("ShaderMaterial_ke1l3") diff --git a/player/Player.cs b/player/Player.cs index dfb9b4e..9f36703 100644 --- a/player/Player.cs +++ b/player/Player.cs @@ -1,7 +1,18 @@ public partial class Player : CharacterBody3D { - public bool IsLocal { get; set; } = true; - public int PeerId { get; set; } + [Export] public bool IsLocal { get; set; } + + public int PeerId { + get { + if (int.TryParse(Name, out var result)) return result; + throw new InvalidOperationException($"'{Name}' could not be parsed to PeerId"); + } + set { + if (value > 0) Name = value.ToString(); + else if (IsLocal) Name = "Local"; + else throw new InvalidOperationException("Non-local player can't have PeerId set to 0"); + } + } public MovementController Movement { get; private set; } public CameraController Camera { get; private set; } diff --git a/scripts/MultiplayerManager.cs b/scripts/MultiplayerManager.cs index 98ad785..f2052ef 100644 --- a/scripts/MultiplayerManager.cs +++ b/scripts/MultiplayerManager.cs @@ -16,6 +16,10 @@ public partial class MultiplayerManager : Node } + public Player GetPlayerByPeerId(int peerId) + => Players.GetNode(peerId.ToString()); + + public void Connect(string address, ushort port) { var peer = new ENetMultiplayerPeer(); @@ -41,7 +45,7 @@ public partial class MultiplayerManager : Node void OnMultiplayerReady() { var localId = Multiplayer.GetUniqueId(); - LocalPlayer.Name = localId.ToString(); + LocalPlayer.PeerId = localId; LocalPlayer.SetMultiplayerAuthority(localId); if (!Multiplayer.IsServer()) @@ -53,9 +57,10 @@ public partial class MultiplayerManager : Node void OnMultiplayerDisconnected() { - LocalPlayer.Name = "Local"; - foreach (var player in Players.GetChildren().Cast()) - if (!player.IsLocal) OnPeerDisconnected(player.PeerId); + foreach (var player in Players.GetChildren().Cast()) { + if (player.IsLocal) player.PeerId = 0; + else OnPeerDisconnected(player.PeerId); + } Multiplayer.MultiplayerPeer.Close(); Multiplayer.MultiplayerPeer = null; } @@ -65,8 +70,6 @@ public partial class MultiplayerManager : Node { var player = PlayerScene.Instantiate(); player.SetMultiplayerAuthority((int)peerId); - player.Name = peerId.ToString(); - player.IsLocal = false; player.PeerId = (int)peerId; Players.AddChild(player); PlayerJoined?.Invoke(player); @@ -74,7 +77,7 @@ public partial class MultiplayerManager : Node void OnPeerDisconnected(long peerId) { - var player = Players.GetNode(peerId.ToString()); + var player = GetPlayerByPeerId((int)peerId); PlayerLeft?.Invoke(player); player.QueueFree(); }