AceField/Scripts/Logic/World.cs

78 lines
2.0 KiB
C#
Raw Normal View History

2024-08-05 11:08:28 +00:00
using Godot;
2024-08-07 15:01:57 +00:00
namespace AceField.Scripts.Logic;
2024-08-05 11:08:28 +00:00
public partial class World : Node2D
{
[Export] public PackedScene PlayerScene;
2024-08-08 07:20:09 +00:00
public void StartGame(string currentPlayerName = null)
2024-08-05 11:08:28 +00:00
{
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"))
2024-08-08 07:20:09 +00:00
AddPlayer(1, currentPlayerName);
2024-08-05 11:08:28 +00:00
}
public override void _ExitTree()
{
if (!Multiplayer.IsServer())
return;
Multiplayer.PeerDisconnected -= RemovePlayer_Adaptor;
Multiplayer.PeerConnected -= AddPlayer_Adaptor;
}
2024-08-08 09:10:48 +00:00
private static string BuildPlayerName(int id)
=> $"Player#{id}";
2024-08-05 11:08:28 +00:00
private void AddPlayer_Adaptor(long id)
=> AddPlayer((int)id);
private void RemovePlayer_Adaptor(long id)
=> RemovePlayer((int)id);
2024-08-08 07:20:09 +00:00
private void AddPlayer(int id, string name = null)
2024-08-05 11:08:28 +00:00
{
2024-08-08 07:20:09 +00:00
var player = PlayerScene.Instantiate<Player>();
player.PlayerId = id;
2024-08-05 11:08:28 +00:00
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);
2024-08-08 07:20:09 +00:00
player.PlayerName = name;
2024-08-05 11:08:28 +00:00
AddChild(player, true);
}
private void RemovePlayer(int id)
{
var name = BuildPlayerName(id);
if (!HasNode(name))
return;
GetNode(name).QueueFree();
}
2024-08-08 07:20:09 +00:00
public Player GetCurrentPlayer()
{
foreach(var child in GetChildren())
{
if (child is Player { IsCurrentPlayer: true } player)
{
return player;
}
}
return null;
}
2024-08-05 11:08:28 +00:00
}