66 lines
1.7 KiB
C#
66 lines
1.7 KiB
C#
using Godot;
|
|
|
|
namespace AceField.Scripts.Logic;
|
|
|
|
public partial class World : Node2D
|
|
{
|
|
[Export] public PackedScene PlayerScene;
|
|
|
|
public void StartGame()
|
|
{
|
|
if (!Multiplayer.IsServer())
|
|
return;
|
|
|
|
// Handling player connect / disconnect after this client connected
|
|
Multiplayer.PeerDisconnected += RemovePlayer_Adaptor;
|
|
Multiplayer.PeerConnected += AddPlayer_Adaptor;
|
|
|
|
// Handling player connected before this client
|
|
foreach (var id in Multiplayer.GetPeers())
|
|
AddPlayer(id);
|
|
|
|
// Add this client as a player if client isn't a dedicated server
|
|
if (!OS.HasFeature("dedicated_server"))
|
|
AddPlayer(1);
|
|
}
|
|
|
|
public override void _ExitTree()
|
|
{
|
|
if (!Multiplayer.IsServer())
|
|
return;
|
|
|
|
Multiplayer.PeerDisconnected -= RemovePlayer_Adaptor;
|
|
Multiplayer.PeerConnected -= AddPlayer_Adaptor;
|
|
}
|
|
|
|
private string BuildPlayerName(int id)
|
|
{
|
|
return $"Player#{id}";
|
|
}
|
|
|
|
private void AddPlayer_Adaptor(long id)
|
|
=> AddPlayer((int)id);
|
|
|
|
private void RemovePlayer_Adaptor(long id)
|
|
=> RemovePlayer((int)id);
|
|
|
|
private void AddPlayer(int id)
|
|
{
|
|
var player = PlayerScene.Instantiate<AceField.Scripts.Player>();
|
|
player.SetPlayerId(id);
|
|
var position = Vector2.FromAngle(GD.Randf() * 2 * Mathf.Pi);
|
|
player.Position = new Vector2(position.X * 5f * GD.Randf(), position.Y * 5f * GD.Randf());
|
|
player.Name = BuildPlayerName(id);
|
|
|
|
AddChild(player, true);
|
|
}
|
|
|
|
private void RemovePlayer(int id)
|
|
{
|
|
var name = BuildPlayerName(id);
|
|
if (!HasNode(name))
|
|
return;
|
|
|
|
GetNode(name).QueueFree();
|
|
}
|
|
} |