Player.cs 3.1 KB

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