UserControlAI.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace RootMotion.Demos {
  4. /// <summary>
  5. /// User input for an AI controlled character controller.
  6. /// </summary>
  7. public class UserControlAI : UserControlThirdPerson {
  8. public Transform moveTarget;
  9. public float stoppingDistance = 0.5f;
  10. public float stoppingThreshold = 1.5f;
  11. public Navigator navigator;
  12. protected override void Start()
  13. {
  14. base.Start();
  15. navigator.Initiate(transform);
  16. }
  17. protected override void Update () {
  18. float moveSpeed = walkByDefault? 0.5f: 1f;
  19. // If using Unity Navigation
  20. if (navigator.activeTargetSeeking)
  21. {
  22. navigator.Update(moveTarget.position);
  23. state.move = navigator.normalizedDeltaPosition * moveSpeed;
  24. }
  25. // No navigation, just move straight to the target
  26. else
  27. {
  28. Vector3 direction = moveTarget.position - transform.position;
  29. float distance = direction.magnitude;
  30. Vector3 normal = transform.up;
  31. Vector3.OrthoNormalize(ref normal, ref direction);
  32. float sD = state.move != Vector3.zero ? stoppingDistance : stoppingDistance * stoppingThreshold;
  33. state.move = distance > sD ? direction * moveSpeed : Vector3.zero;
  34. state.lookPos = moveTarget.position;
  35. }
  36. }
  37. // Visualize the navigator
  38. void OnDrawGizmos()
  39. {
  40. if (navigator.activeTargetSeeking) navigator.Visualize();
  41. }
  42. }
  43. }