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.

63 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. public GameObject LocalPlayerPrefab;
  10. public GameObject RemotePlayerPrefab;
  11. public Vector3 mapTop;
  12. public Vector3 mapBot;
  13. private Dictionary<byte, GameObject> RemotePlayers = new Dictionary<byte, GameObject>();
  14. private GameObject PlayerObject;
  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. Vector3 startPos = new Vector3(Random.Range(mapBot.x, mapTop.x), Random.Range(mapBot.y, mapTop.y), Random.Range(mapBot.z, mapTop.z));
  27. PlayerObject = GameObject.Instantiate(LocalPlayerPrefab);
  28. PlayerObject.transform.position = startPos;
  29. }
  30. public void InstantiateRemotePlayer(byte playerID)
  31. {
  32. RemotePlayers.Add(playerID, Instantiate(RemotePlayerPrefab));
  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. }