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.

75 lines
2.2 KiB

6 years ago
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. namespace Multiplayer
  6. {
  7. public class PlayerServerManager
  8. {
  9. private ServerManager ServerManager;
  10. public PlayerServerManager(ServerManager ServerManager)
  11. {
  12. this.ServerManager = ServerManager;
  13. RegisterHandlers();
  14. }
  15. private void RegisterHandlers()
  16. {
  17. ServerManager.Server.RegisterHandler(PlayerMsgID.Position, RecievePosition);
  18. ServerManager.Server.RegisterHandler(PlayerMsgID.QueryPosition, QueryPosition);
  19. }
  20. private void RecievePosition(NetworkMessage msg)
  21. {
  22. VectorMsg vectorMsg;
  23. if (!Utility.ReadMessage<VectorMsg>(msg, out vectorMsg))
  24. return;
  25. if (!ServerManager.AllPlayers.ContainsKey(vectorMsg.ID))
  26. {
  27. Debug.Log("Recieved position from unknown player");
  28. return;
  29. }
  30. Player player = ServerManager.AllPlayers[vectorMsg.ID];
  31. player.Position = vectorMsg.vector;
  32. foreach(Player otherPlayer in ServerManager.AllPlayers.Values)
  33. {
  34. if (otherPlayer.Equals(player))
  35. continue;
  36. otherPlayer.Connection.Send(PlayerMsgID.Position, vectorMsg);
  37. }
  38. }
  39. private void QueryPosition(NetworkMessage msg)
  40. {
  41. PlayerMsg playerMsg;
  42. if (!Utility.ReadMessage<PlayerMsg>(msg, out playerMsg))
  43. return;
  44. if (!ServerManager.AllPlayers.ContainsKey(playerMsg.ID))
  45. {
  46. Debug.Log("Recieved query from unknown player");
  47. return;
  48. }
  49. Player player = ServerManager.AllPlayers[playerMsg.ID];
  50. foreach (Player otherPlayer in ServerManager.AllPlayers.Values)
  51. {
  52. if (otherPlayer.Equals(player))
  53. continue;
  54. VectorMsg vectorMsg = new VectorMsg(otherPlayer.ID, otherPlayer.Position);
  55. player.Connection.Send(PlayerMsgID.Position, vectorMsg);
  56. }
  57. }
  58. }
  59. }