OrbitingBody.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace Funly.SkyStudio
  5. {
  6. [ExecuteInEditMode]
  7. public class OrbitingBody : MonoBehaviour
  8. {
  9. private Transform m_PositionTransform;
  10. public Transform positionTransform {
  11. get {
  12. if (m_PositionTransform == null) {
  13. m_PositionTransform = this.transform.Find("Position");
  14. }
  15. return m_PositionTransform;
  16. }
  17. }
  18. private RotateBody m_RotateBody;
  19. public RotateBody rotateBody {
  20. get {
  21. if (m_RotateBody == null) {
  22. Transform t = positionTransform;
  23. if (!t) {
  24. Debug.LogError("Can't return rotation body without a position transform game object");
  25. return null;
  26. }
  27. m_RotateBody = t.GetComponent<RotateBody>();
  28. }
  29. return m_RotateBody;
  30. }
  31. }
  32. // Position of the orbiting body.
  33. private SpherePoint m_SpherePoint = new SpherePoint(0, 0);
  34. public SpherePoint Point
  35. {
  36. get { return m_SpherePoint; }
  37. set
  38. {
  39. if (m_SpherePoint == null)
  40. {
  41. m_SpherePoint = new SpherePoint(0, 0);
  42. }
  43. else
  44. {
  45. m_SpherePoint = value;
  46. }
  47. m_CachedWorldDirection = m_SpherePoint.GetWorldDirection();
  48. LayoutOribit();
  49. }
  50. }
  51. // Direction to orbiting body.
  52. private Vector3 m_CachedWorldDirection = Vector3.right;
  53. public Vector3 BodyGlobalDirection { get { return m_CachedWorldDirection; } }
  54. private Light m_BodyLight;
  55. public Light BodyLight
  56. {
  57. get {
  58. if (m_BodyLight == null) {
  59. m_BodyLight = transform.GetComponentInChildren<Light>();
  60. if (m_BodyLight != null)
  61. {
  62. // Reset in case it was rotated from older prefab or developer.
  63. m_BodyLight.transform.localRotation = Quaternion.identity;
  64. }
  65. }
  66. return m_BodyLight;
  67. }
  68. }
  69. public void ResetOrbit() {
  70. LayoutOribit();
  71. m_PositionTransform = null;
  72. }
  73. public void LayoutOribit()
  74. {
  75. transform.position = Vector3.zero;
  76. transform.rotation = Quaternion.identity;
  77. transform.forward = BodyGlobalDirection * -1.0f;
  78. }
  79. void OnValidate()
  80. {
  81. LayoutOribit();
  82. }
  83. }
  84. }