using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
|
|
|
|
namespace Multiplayer
|
|
{
|
|
|
|
public class PlayersManager : MonoSingleton<PlayersManager>
|
|
{
|
|
[SerializeField]
|
|
public GameObject LocalPlayerPrefab;
|
|
|
|
[SerializeField]
|
|
public GameObject RemotePlayerPrefab;
|
|
|
|
public Dictionary<byte, PlayerData> Players = new Dictionary<byte, PlayerData>();
|
|
public PlayerData LocalPlayer;
|
|
|
|
private void Start()
|
|
{
|
|
RegisterHandlers();
|
|
|
|
PlayerData localPlayer = new PlayerData(ClientManager.Instance.ID, ClientManager.Instance.Name, Color.white);
|
|
localPlayer.isLocalPlayer = true;
|
|
Players.Add(localPlayer.ID, localPlayer);
|
|
LocalPlayer = localPlayer;
|
|
}
|
|
|
|
public void RegisterHandlers()
|
|
{
|
|
ClientManager.Instance.Client.RegisterHandler(PlayerMsgID.Position, RecievePosition);
|
|
ClientManager.Instance.Client.RegisterHandler(LoginMsgID.RemotePlayerJoin, OnRemotePlayerJoin);
|
|
ClientManager.Instance.Client.RegisterHandler(LoginMsgID.RemotePlayerExit, OnRemotePlayerLeave);
|
|
}
|
|
|
|
public void InstantiatePlayers()
|
|
{
|
|
foreach (PlayerData playerData in Players.Values)
|
|
{
|
|
if (playerData.isLocalPlayer)
|
|
playerData.Instantiate(LocalPlayerPrefab, transform);
|
|
else
|
|
playerData.Instantiate(RemotePlayerPrefab, transform);
|
|
}
|
|
}
|
|
|
|
public void DestroyPlayers()
|
|
{
|
|
foreach (PlayerData player in Players.Values)
|
|
if (player.gameObject != null)
|
|
Destroy(player.gameObject);
|
|
}
|
|
|
|
|
|
public void SendPosition(Vector3 position)
|
|
{
|
|
ClientManager.Instance.SendMessage(PlayerMsgID.Position, new VectorMsg(ClientManager.Instance.ID, position));
|
|
}
|
|
|
|
public void RecievePosition(NetworkMessage msg)
|
|
{
|
|
|
|
VectorMsg vectorMsg;
|
|
if (!Utility.ReadMessage<VectorMsg>(msg, out vectorMsg))
|
|
return;
|
|
|
|
if (Players.ContainsKey(vectorMsg.ID))
|
|
Players[vectorMsg.ID].SetPosition(vectorMsg.vector);
|
|
}
|
|
|
|
public void OnRemotePlayerJoin(NetworkMessage msg)
|
|
{
|
|
|
|
PlayerDataMsg playerMsg;
|
|
|
|
if (!Utility.ReadMessage<PlayerDataMsg>(msg, out playerMsg))
|
|
return;
|
|
|
|
if (Players.ContainsKey(playerMsg.ID))
|
|
Debug.Log(Players[playerMsg.ID].Name + ", trying to join twice");
|
|
|
|
PlayerData newPlayer = new PlayerData(playerMsg.ID, playerMsg.Name, playerMsg.Color);
|
|
Players.Add(playerMsg.ID, newPlayer);
|
|
}
|
|
|
|
public void OnRemotePlayerLeave(NetworkMessage msg)
|
|
{
|
|
PlayerMsg playerMsg;
|
|
|
|
if (!Utility.ReadMessage<PlayerMsg>(msg, out playerMsg))
|
|
return;
|
|
|
|
if (!Players.ContainsKey(playerMsg.ID))
|
|
Debug.Log("Unknown Player Left");
|
|
|
|
PlayerData leftPlayer = Players[playerMsg.ID];
|
|
Players.Remove(playerMsg.ID);
|
|
|
|
if (leftPlayer.gameObject != null)
|
|
Destroy(leftPlayer.gameObject);
|
|
}
|
|
|
|
}
|
|
}
|