Player.cs 2.7 KB

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