MonsterMovement.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using UnityEngine;
  2. namespace Mirror.Examples.Benchmark
  3. {
  4. public class MonsterMovement : NetworkBehaviour
  5. {
  6. public float speed = 1;
  7. public float movementProbability = 0.5f;
  8. public float movementDistance = 20;
  9. bool moving;
  10. Vector3 start;
  11. Vector3 destination;
  12. public override void OnStartServer()
  13. {
  14. start = transform.position;
  15. }
  16. [ServerCallback]
  17. void Update()
  18. {
  19. if (moving)
  20. {
  21. if (Vector3.Distance(transform.position, destination) <= 0.01f)
  22. {
  23. moving = false;
  24. }
  25. else
  26. {
  27. transform.position = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime);
  28. }
  29. }
  30. else
  31. {
  32. float r = Random.value;
  33. if (r < movementProbability * Time.deltaTime)
  34. {
  35. Vector2 circlePos = Random.insideUnitCircle;
  36. Vector3 dir = new Vector3(circlePos.x, 0, circlePos.y);
  37. Vector3 dest = transform.position + dir * movementDistance;
  38. // within move dist around start?
  39. // (don't want to wander off)
  40. if (Vector3.Distance(start, dest) <= movementDistance)
  41. {
  42. destination = dest;
  43. moving = true;
  44. }
  45. }
  46. }
  47. }
  48. }
  49. }