RandomDirectionMover.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// Every X seconds, rotates the light to face a new random direction.
  6. /// Used by the ZED Dark Room example scene and called by RandomDirLightManager.cs.
  7. /// </summary>
  8. public class RandomDirectionMover : MonoBehaviour
  9. {
  10. /// <summary>
  11. /// How long the light takes to point at a new location.
  12. /// </summary>
  13. [Tooltip("How long the light takes to point at a new location. ")]
  14. public float timeToPoint = 0.1f;
  15. /// <summary>
  16. /// Points the object in a new, random direction.
  17. /// Gets called by RandomDirLightManager.cs.
  18. /// </summary>
  19. /// <returns></returns>
  20. public IEnumerator NewDirection()
  21. {
  22. Vector3 startdir = transform.localRotation * Vector3.forward;
  23. Vector3 randdir = new Vector3(Random.Range(0f, 2f) - 1f, Random.Range(0f, .25f) - .125f, Random.Range(0f, 2f) - 1f); //Weighted towards horizon to make it more likely to be visible
  24. float angledif = Mathf.Abs(Vector3.Angle(startdir, randdir)); //How we know how quickly to rotate each frame, and when to stop
  25. Quaternion targetrot = Quaternion.FromToRotation(startdir, randdir);
  26. for(float t = 0; t < timeToPoint; t += Time.deltaTime)
  27. {
  28. transform.localRotation = Quaternion.RotateTowards(transform.localRotation, targetrot, angledif / timeToPoint * Time.deltaTime);
  29. yield return null;
  30. }
  31. }
  32. }