-
Notifications
You must be signed in to change notification settings - Fork 0
/
Level.cs
66 lines (54 loc) · 1.43 KB
/
Level.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using Godot;
using System.Diagnostics;
public partial class Level : Node2D
{
const float SpawnRandom = 5.0f;
private Node Players => GetNode<Node>("Players");
public override void _Ready()
{
Trace.WriteLine("Level loaded");
if (!Multiplayer.IsServer()) return;
Multiplayer.PeerConnected += AddPlayer;
Multiplayer.PeerDisconnected += RemovePlayer;
SpawnConnectedPlayers();
SpawnLocalPlayer();
}
public override void _ExitTree()
{
if (!Multiplayer.IsServer())
return;
Multiplayer.PeerConnected -= AddPlayer;
Multiplayer.PeerDisconnected -= RemovePlayer;
}
private void SpawnConnectedPlayers()
{
foreach (var id in Multiplayer.GetPeers())
AddPlayer(id);
}
private void SpawnLocalPlayer()
{
if (!OS.HasFeature("dedicated_server"))
AddPlayer(1);
}
private void AddPlayer(long id)
{
var packedScene = (ResourceLoader.Load("res://Player.tscn") as PackedScene);
var character = (Player)packedScene?.Instantiate();
if (character == null)
{
OS.Alert("Cannot instantiate player.");
return;
}
Trace.WriteLine($"Adding player {id}");
character.Id = id;
character.Position = GetViewportRect().Size * GD.Randf();
character.Name = GetNameFromId(id);
Players.AddChild(character, true);
}
private static string GetNameFromId(long id) => $"{id}";
private void RemovePlayer(long id)
{
if (!Players.HasNode(GetNameFromId(id))) return;
Players.GetNode(GetNameFromId(id)).QueueFree();
}
}