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.

106 lines
3.0 KiB

5 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. ServerManager.Server.RegisterHandler(PlayerMsgID.Vegetable, PickUpVeg);
  20. }
  21. private void RecievePosition(NetworkMessage msg)
  22. {
  23. VectorMsg vectorMsg;
  24. if (!Utility.ReadMessage<VectorMsg>(msg, out vectorMsg))
  25. return;
  26. if (!ServerManager.AllPlayers.ContainsKey(vectorMsg.ID))
  27. {
  28. Debug.Log("Recieved position from unknown player");
  29. return;
  30. }
  31. Player player = ServerManager.AllPlayers[vectorMsg.ID];
  32. player.Position = vectorMsg.vector;
  33. foreach(Player otherPlayer in ServerManager.AllPlayers.Values)
  34. {
  35. if (otherPlayer.Equals(player))
  36. continue;
  37. otherPlayer.Connection.Send(PlayerMsgID.Position, vectorMsg);
  38. }
  39. }
  40. private void QueryPosition(NetworkMessage msg)
  41. {
  42. PlayerMsg playerMsg;
  43. if (!Utility.ReadMessage<PlayerMsg>(msg, out playerMsg))
  44. return;
  45. if (!ServerManager.AllPlayers.ContainsKey(playerMsg.ID))
  46. {
  47. Debug.Log("Recieved query from unknown player");
  48. return;
  49. }
  50. Player player = ServerManager.AllPlayers[playerMsg.ID];
  51. foreach (Player otherPlayer in ServerManager.AllPlayers.Values)
  52. {
  53. if (otherPlayer.Equals(player))
  54. continue;
  55. VectorMsg vectorMsg = new VectorMsg(otherPlayer.ID, otherPlayer.Position);
  56. player.Connection.Send(PlayerMsgID.Position, vectorMsg);
  57. }
  58. }
  59. private void PickUpVeg(NetworkMessage msg)
  60. {
  61. VegMsg vegMsg;
  62. if (!Utility.ReadMessage<VegMsg>(msg, out vegMsg))
  63. return;
  64. if (!ServerManager.AllPlayers.ContainsKey(vegMsg.ID))
  65. {
  66. Debug.Log("Recieved Veg from unknown player");
  67. return;
  68. }
  69. Player player = ServerManager.AllPlayers[vegMsg.ID];
  70. foreach (Player otherPlayer in ServerManager.AllPlayers.Values)
  71. {
  72. if (otherPlayer.Equals(player))
  73. continue;
  74. otherPlayer.Connection.Send(PlayerMsgID.Vegetable, vegMsg);
  75. }
  76. }
  77. }
  78. }