MonsterMovement.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. transform.position = destination;
  24. moving = false;
  25. }
  26. else
  27. {
  28. transform.position = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime);
  29. }
  30. }
  31. else
  32. {
  33. float r = Random.value;
  34. if (r < movementProbability * Time.deltaTime)
  35. {
  36. Vector2 circlePos = Random.insideUnitCircle;
  37. Vector3 dir = new Vector3(circlePos.x, 0, circlePos.y);
  38. // set destination on random pos in a circle around start.
  39. // (don't want to wander off)
  40. destination = start + dir * movementDistance;
  41. moving = true;
  42. }
  43. }
  44. }
  45. }
  46. }