OscillateRotation.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class OscillateRotation : MonoBehaviour
  5. {
  6. /// <summary>
  7. /// Curve that defines the pattern we rotate the transform over time.
  8. /// </summary>
  9. [Tooltip("Curve that defines the pattern we rotate the transform over time.")]
  10. public AnimationCurve rotateCurve = new AnimationCurve(new Keyframe[5]
  11. {
  12. new Keyframe(0, 0, 5, 5),
  13. new Keyframe(0.25f, 1, 0, 0),
  14. new Keyframe(0.5f, 0, -5, -5),
  15. new Keyframe(0.75f, -1, 0, 0),
  16. new Keyframe(1, 0, 5, 5)
  17. });
  18. /// <summary>
  19. /// How far the transform rotates on points on the curve equal to 1 or -1. (Technically not "max" but more intuitive than "normalized" or something.)
  20. /// </summary>
  21. [Tooltip("How far the transform rotates on points on the curve equal to 1 or -1. (Technically not 'max' but more intuitive than 'normalized' or something.)")]
  22. public float maxDegrees = 20f;
  23. /// <summary>
  24. /// How long it takes for a full cycle, ie. playing through rotateCurve all the way.
  25. /// </summary>
  26. [Tooltip("How long it takes for a full cycle, ie. playing through rotateCurve all the way.")]
  27. public float cycleTimeSeconds = 2f;
  28. /// <summary>
  29. /// Timer that keeps track of where we are in the rotateCurve at any given moment.
  30. /// </summary>
  31. private float cycleTimer = 0f;
  32. /// <summary>
  33. /// True to rotate on the X axis.
  34. /// </summary>
  35. [Space(5)]
  36. [Tooltip("True to rotate on the X axis.")]
  37. public bool rotateOnX = false;
  38. /// <summary>
  39. /// True to rotate on the Y axis.
  40. /// </summary>
  41. [Tooltip("True to rotate on the Y axis.")]
  42. public bool rotateOnY = false;
  43. /// <summary>
  44. /// True to rotate on the Z axis.
  45. /// </summary>
  46. [Tooltip("True to rotate on the Z axis.")]
  47. public bool rotateOnZ = true;
  48. public Vector3 startRotationEulers;
  49. // Use this for initialization
  50. void Start ()
  51. {
  52. startRotationEulers = transform.localRotation.eulerAngles;
  53. }
  54. // Update is called once per frame
  55. void Update ()
  56. {
  57. cycleTimer += Time.deltaTime;
  58. if (cycleTimer > cycleTimeSeconds) cycleTimer %= cycleTimeSeconds;
  59. float rotateamount = rotateCurve.Evaluate(cycleTimer / cycleTimeSeconds) * maxDegrees;
  60. float xfinal = rotateOnX ? startRotationEulers.x + rotateamount : transform.localEulerAngles.x;
  61. float yfinal = rotateOnY ? startRotationEulers.y + rotateamount : transform.localEulerAngles.y;
  62. float zfinal = rotateOnZ ? startRotationEulers.z + rotateamount : transform.localEulerAngles.z;
  63. transform.localEulerAngles = new Vector3(xfinal, yfinal, zfinal);
  64. }
  65. }