Player.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using UnityEngine;
  2. namespace Mirror.Examples.CCU
  3. {
  4. public class Player : NetworkBehaviour
  5. {
  6. public Vector3 cameraOffset = new Vector3(0, 40, -40);
  7. // automated movement.
  8. // player may switch to manual movement any time
  9. [Header("Automated Movement")]
  10. public bool autoMove = true;
  11. public float autoSpeed = 2;
  12. public float movementProbability = 0.5f;
  13. public float movementDistance = 20;
  14. bool moving;
  15. Vector3 start;
  16. Vector3 destination;
  17. [Header("Manual Movement")]
  18. public float manualSpeed = 10;
  19. // cache .transform for benchmark demo.
  20. // Component.get_transform shows in profiler otherwise.
  21. Transform tf;
  22. public override void OnStartLocalPlayer()
  23. {
  24. tf = transform;
  25. start = tf.position;
  26. // make camera follow
  27. Camera.main.transform.SetParent(transform, false);
  28. Camera.main.transform.localPosition = cameraOffset;
  29. }
  30. public override void OnStopLocalPlayer()
  31. {
  32. // free the camera so we don't destroy it too
  33. Camera.main.transform.SetParent(null, true);
  34. }
  35. void AutoMove()
  36. {
  37. if (moving)
  38. {
  39. if (Vector3.Distance(tf.position, destination) <= 0.01f)
  40. {
  41. moving = false;
  42. }
  43. else
  44. {
  45. tf.position = Vector3.MoveTowards(tf.position, destination, autoSpeed * Time.deltaTime);
  46. }
  47. }
  48. else
  49. {
  50. float r = Random.value;
  51. if (r < movementProbability * Time.deltaTime)
  52. {
  53. // calculate a random position in a circle
  54. float circleX = Mathf.Cos(Random.value * Mathf.PI);
  55. float circleZ = Mathf.Sin(Random.value * Mathf.PI);
  56. Vector2 circlePos = new Vector2(circleX, circleZ);
  57. Vector3 dir = new Vector3(circlePos.x, 0, circlePos.y);
  58. // set destination on random pos in a circle around start.
  59. // (don't want to wander off)
  60. destination = start + dir * movementDistance;
  61. moving = true;
  62. }
  63. }
  64. }
  65. void ManualMove()
  66. {
  67. float h = Input.GetAxis("Horizontal");
  68. float v = Input.GetAxis("Vertical");
  69. Vector3 direction = new Vector3(h, 0, v);
  70. transform.position += direction.normalized * (Time.deltaTime * manualSpeed);
  71. }
  72. static bool Interrupted() =>
  73. Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0;
  74. void Update()
  75. {
  76. if (!isLocalPlayer) return;
  77. // player may interrupt auto movement to switch to manual
  78. if (Interrupted()) autoMove = false;
  79. // move
  80. if (autoMove) AutoMove();
  81. else ManualMove();
  82. }
  83. }
  84. }