PitchOscillator.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// Makes an object slide on its X axis according to the AnimationCurve specified.
  6. /// Used in the ZED Dark Room example scene to make lights sweep back and forth.
  7. /// </summary>
  8. public class PitchOscillator : MonoBehaviour
  9. {
  10. /// <summary>
  11. /// The path it takes to oscillate. Makes it simple to set a pattern in the Inspector.
  12. /// </summary>
  13. [Tooltip("The path it takes to oscillate. Makes it simple to set a pattern in the Inspector. ")]
  14. public AnimationCurve animationCurve;
  15. /// <summary>
  16. /// How long a full oscillation lasts (from start to finish of animationCurve).
  17. /// </summary>
  18. [Tooltip("How long a full oscillation lasts (from start to finish of animationCurve). ")]
  19. public float secondsPerOscillation = .95f;
  20. /// <summary>
  21. /// Scales the values in animationCurve, since it's difficult to specify values outside -1 and 1 in the Inspector.
  22. /// </summary>
  23. [Tooltip("Scales the values in animationCurve, since it's difficult to specify values outside -1 and 1 in the Inspector. ")]
  24. public float distanceScale = 2;
  25. /// <summary>
  26. /// How long through the animation it has played.
  27. /// Incremented by Time.deltaTime / distanceScale each Update().
  28. /// </summary>
  29. private float timer = 0f;
  30. /// <summary>
  31. /// Cache for the starting position, so oscillations can be done relative to it after it moves.
  32. /// </summary>
  33. private Vector3 startposition; //In local space
  34. // Use this for initialization
  35. void Start ()
  36. {
  37. startposition = transform.localPosition;
  38. }
  39. // Update is called once per frame
  40. void Update ()
  41. {
  42. //Update the timer and restart the animationCurve if finished.
  43. timer += Time.deltaTime;
  44. if(timer >= secondsPerOscillation)
  45. {
  46. timer = timer % secondsPerOscillation;
  47. }
  48. //Move the light according to the curve.
  49. float newxpos = animationCurve.Evaluate(timer / secondsPerOscillation) * distanceScale;
  50. transform.localPosition = startposition + transform.localRotation * Vector3.right * newxpos;
  51. }
  52. }