quakeball/Assets/Scripts/Net/Instances/Server.cs

76 lines
2.7 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NeonTea.Quakeball.Net.Packets;
using NeonTea.Quakeball.TeaNet.Peers;
using NeonTea.Quakeball.TeaNet.Packets;
namespace NeonTea.Quakeball.Net.Instances {
public class Server : NetInstance {
private NetChaperone Net;
private Dictionary<ulong, NetPlayer> Players = new Dictionary<ulong, NetPlayer>();
private ulong PlayerIdCounter;
private NetPlayer LocalPlayer = new NetPlayer(ulong.MaxValue);
public override void Start(string address, int port, PeerMessageListener listener) {
if (Peer != null) {
return;
}
Peer = new Peer(Fingerprint);
Peer.MessageListener = listener;
Peer.Start(port);
Peer.RegisterProtocol(new GameProtocol(this));
Peer.StartListen(address, port);
Net = GameObject.FindGameObjectWithTag("Net").GetComponent<NetChaperone>();
GameObject obj = GameObject.FindGameObjectWithTag("Player");
LocalPlayer.Controlled = obj;
Players.Add(LocalPlayer.Id, LocalPlayer);
}
public override void Connected(Connection conn) {
foreach (NetPlayer p in Players.Values) {
if (p.Controlled == null) { // Not yet initialized, sending later.
continue;
}
SpawnPckt spawn = new SpawnPckt();
spawn.PlayerId = p.Id;
spawn.Location = p.Controlled.transform.position;
Peer.SendReliableLater(conn.uid, spawn);
}
NetPlayer RemotePlayer = new NetPlayer(PlayerIdCounter++);
Players.Add(RemotePlayer.Id, RemotePlayer);
SelfIdentPckt ident = new SelfIdentPckt();
ident.PlayerId = RemotePlayer.Id;
Peer.SendReliable(conn.uid, ident);
}
public override void Disconnected(Connection conn) {
}
public override void Handle(Connection conn, Packet packet) {
if (packet is SpawnPckt) {
SpawnPckt spawn = (SpawnPckt)packet;
if (Players[conn.uid].Controlled == null) {
GameObject obj = Net.SpawnPlayer(spawn.Location);
Players[conn.uid].Controlled = obj;
spawn = new SpawnPckt();
spawn.PlayerId = conn.uid;
spawn.Location = obj.transform.position;
SendReliableToAll(spawn);
}
}
}
public void SendReliableToAll(Packet packet) {
foreach (NetPlayer p in Players.Values) {
Peer.SendReliable(p.Id, packet);
}
}
}
}