MoveFromToWithTransform.cs 990 B

123456789101112131415161718192021222324252627282930313233343536
  1. using UnityEngine;
  2. using System.Collections;
  3. public class MoveFromToWithTransform : MonoBehaviour {
  4. public Transform from;
  5. public Transform to;
  6. public float speed = 4f;
  7. public bool lookAt = false;
  8. public Vector3 offset = Vector3.zero;
  9. public bool autoDestroy = true;
  10. void OnEnable()
  11. {
  12. if (from != null)
  13. transform.position = from.TransformPoint(offset);
  14. if (lookAt && to != null)
  15. transform.LookAt(to);
  16. }
  17. void Update()
  18. {
  19. if (to != null)
  20. {
  21. Vector3 targetPosition = to.TransformPoint(offset);
  22. transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * speed);
  23. if (autoDestroy && transform.position.FEqual(targetPosition, 1e-2f))
  24. {
  25. gameObject.Destroy();
  26. return;
  27. }
  28. else if (lookAt)
  29. transform.LookAt(to);
  30. }
  31. }
  32. }