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.

61 lines
1.7 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. }
  29. public void InstantiateRemotePlayer(byte playerID)
  30. {
  31. RemotePlayers.Add(playerID, Instantiate(RemotePlayerPrefab,transform));
  32. }
  33. public void SendPosition(Vector3 position) {
  34. ClientManager.Instance.SendMessage(PlayerMsgID.Position, new VectorMsg(ClientManager.Instance.ID, position));
  35. }
  36. public void RecievePosition(NetworkMessage msg)
  37. {
  38. VectorMsg vectorMsg;
  39. if (!Utility.ReadMessage<VectorMsg>(msg, out vectorMsg))
  40. return;
  41. if (!RemotePlayers.ContainsKey(vectorMsg.ID))
  42. InstantiateRemotePlayer(vectorMsg.ID);
  43. RemotePlayers[vectorMsg.ID].transform.position = vectorMsg.vector;
  44. }
  45. }
  46. }