You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.8 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. namespace Multiplayer
  6. {
  7. public class PlayersManager : MonoSingleton<PlayersManager>
  8. {
  9. [SerializeField]
  10. public GameObject LocalPlayerPrefab;
  11. [SerializeField]
  12. public GameObject RemotePlayerPrefab;
  13. public Dictionary<byte, GameObject> RemotePlayers = new Dictionary<byte, GameObject>();
  14. public GameObject LocalPlayer;
  15. private void Start()
  16. {
  17. OnGameStart();
  18. }
  19. public void OnGameStart()
  20. {
  21. ClientManager.Instance.Client.RegisterHandler(PlayerMsgID.Position, RecievePosition);
  22. InstantaiateLocalPlayer();
  23. }
  24. public void InstantaiateLocalPlayer()
  25. {
  26. LocalPlayer = GameObject.Instantiate(LocalPlayerPrefab,transform);
  27. LocalPlayer.transform.position = Vector3.zero;
  28. ClientManager.Instance.SendMessage(PlayerMsgID.QueryPosition);
  29. }
  30. public void InstantiateRemotePlayer(byte playerID)
  31. {
  32. RemotePlayers.Add(playerID, Instantiate(RemotePlayerPrefab,transform));
  33. }
  34. public void SendPosition(Vector3 position) {
  35. ClientManager.Instance.SendMessage(PlayerMsgID.Position, new VectorMsg(ClientManager.Instance.ID, position));
  36. }
  37. public void RecievePosition(NetworkMessage msg)
  38. {
  39. VectorMsg vectorMsg;
  40. if (!Utility.ReadMessage<VectorMsg>(msg, out vectorMsg))
  41. return;
  42. if (!RemotePlayers.ContainsKey(vectorMsg.ID))
  43. InstantiateRemotePlayer(vectorMsg.ID);
  44. RemotePlayers[vectorMsg.ID].transform.position = vectorMsg.vector;
  45. }
  46. }
  47. }