Monster.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using UnityEngine;
  2. namespace Mirror.Examples.CCU
  3. {
  4. public class Monster : 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. // cache .transform for benchmark demo.
  13. // Component.get_transform shows in profiler otherwise.
  14. Transform tf;
  15. public override void OnStartServer()
  16. {
  17. tf = transform;
  18. start = tf.position;
  19. }
  20. [ServerCallback]
  21. void Update()
  22. {
  23. if (moving)
  24. {
  25. if (Vector3.Distance(tf.position, destination) <= 0.01f)
  26. {
  27. moving = false;
  28. }
  29. else
  30. {
  31. tf.position = Vector3.MoveTowards(tf.position, destination, speed * Time.deltaTime);
  32. }
  33. }
  34. else
  35. {
  36. float r = Random.value;
  37. if (r < movementProbability * Time.deltaTime)
  38. {
  39. Vector2 circlePos = Random.insideUnitCircle;
  40. Vector3 dir = new Vector3(circlePos.x, 0, circlePos.y);
  41. // set destination on random pos in a circle around start.
  42. // (don't want to wander off)
  43. destination = start + dir * movementDistance;
  44. moving = true;
  45. }
  46. }
  47. }
  48. }
  49. }