PlayerEntity.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System.Collections.Generic;
  2. using System.Numerics;
  3. using System.Text.Json;
  4. using BubbleSocketCore.Input;
  5. namespace BubbleSocketCore.Simulation.Entity
  6. {
  7. public class PlayerEntity : IEntity
  8. {
  9. private int id;
  10. private int connectionHashCode;
  11. private string color;
  12. private Vector3 position = new Vector3(20, 20, 0);
  13. private Vector3 velocity = new Vector3(0, 0, 0);
  14. private Vector3 acceleration = new Vector3(0, 0, 0);
  15. private float speed = 0.1f;
  16. public PlayerEntity(int hashCode, string playerColor)
  17. {
  18. connectionHashCode = hashCode;
  19. color = playerColor;
  20. }
  21. public int GetId()
  22. {
  23. return id;
  24. }
  25. public void SetId(int entityId)
  26. {
  27. id = entityId;
  28. }
  29. public Dictionary<string, object> Serialize()
  30. {
  31. return new Dictionary<string, object> {
  32. {"id", id},
  33. {"color", color},
  34. {"position", ToList(position)},
  35. {"velocity", ToList(velocity)},
  36. {"acceleration", ToList(acceleration)},
  37. {"speed", speed}
  38. };
  39. }
  40. private List<object> ToList(Vector3 vector)
  41. {
  42. return new List<object> {
  43. vector.X,
  44. vector.Y,
  45. vector.Z
  46. };
  47. }
  48. override public string ToString()
  49. {
  50. return JsonSerializer.Serialize(Serialize());
  51. }
  52. public IEntity ApplyInputs(int elapsedTick, List<PlayerInput> inputs)
  53. {
  54. var playerClone = (PlayerEntity)Clone();
  55. inputs.ForEach(input =>
  56. {
  57. switch ((InputList)input.type)
  58. {
  59. case InputList.UP:
  60. playerClone.acceleration.Y = input.value == 1 ? -1 * playerClone.speed : 0;
  61. break;
  62. case InputList.DOWN:
  63. playerClone.acceleration.Y = input.value == 1 ? 1 * playerClone.speed : 0;
  64. break;
  65. case InputList.LEFT:
  66. playerClone.acceleration.X = input.value == 1 ? -1 * playerClone.speed : 0;
  67. break;
  68. case InputList.RIGHT:
  69. playerClone.acceleration.X = input.value == 1 ? 1 * playerClone.speed : 0;
  70. break;
  71. }
  72. });
  73. return playerClone;
  74. }
  75. public IEntity Clone()
  76. {
  77. var clonedPlayer = new PlayerEntity(connectionHashCode, color);
  78. clonedPlayer.id = id;
  79. clonedPlayer.acceleration.X = acceleration.X;
  80. clonedPlayer.acceleration.Y = acceleration.Y;
  81. clonedPlayer.acceleration.Z = acceleration.Z;
  82. clonedPlayer.velocity.X = velocity.X;
  83. clonedPlayer.velocity.Y = velocity.Y;
  84. clonedPlayer.velocity.Z = velocity.Z;
  85. clonedPlayer.position.X = position.X;
  86. clonedPlayer.position.Y = position.Y;
  87. clonedPlayer.position.Z = position.Z;
  88. clonedPlayer.speed = speed;
  89. return clonedPlayer;
  90. }
  91. }
  92. }