SkeletonUtilityKinematicShadow.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. public class SkeletonUtilityKinematicShadow : MonoBehaviour
  5. {
  6. public bool hideShadow = true;
  7. public Transform parent;
  8. Dictionary<Transform, Transform> shadowTable;
  9. GameObject shadowRoot;
  10. void Start()
  11. {
  12. shadowRoot = (GameObject)Instantiate(gameObject);
  13. if (hideShadow)
  14. shadowRoot.hideFlags = HideFlags.HideInHierarchy;
  15. if (parent == null)
  16. shadowRoot.transform.parent = transform.root;
  17. else
  18. shadowRoot.transform.parent = parent;
  19. shadowTable = new Dictionary<Transform, Transform>();
  20. Destroy(shadowRoot.GetComponent<SkeletonUtilityKinematicShadow>());
  21. shadowRoot.transform.position = transform.position;
  22. shadowRoot.transform.rotation = transform.rotation;
  23. Vector3 scaleRef = transform.TransformPoint(Vector3.right);
  24. float scale = Vector3.Distance(transform.position, scaleRef);
  25. shadowRoot.transform.localScale = Vector3.one;
  26. var shadowJoints = shadowRoot.GetComponentsInChildren<Joint>();
  27. foreach (Joint j in shadowJoints)
  28. {
  29. j.connectedAnchor *= scale;
  30. }
  31. var joints = GetComponentsInChildren<Joint>();
  32. foreach (var j in joints)
  33. Destroy(j);
  34. var rbs = GetComponentsInChildren<Rigidbody>();
  35. foreach (var rb in rbs)
  36. Destroy(rb);
  37. var colliders = GetComponentsInChildren<Collider>();
  38. foreach (var c in colliders)
  39. Destroy(c);
  40. //match by bone name
  41. var shadowBones = shadowRoot.GetComponentsInChildren<SkeletonUtilityBone>();
  42. var bones = GetComponentsInChildren<SkeletonUtilityBone>();
  43. //build bone lookup
  44. foreach (var b in bones)
  45. {
  46. if (b.gameObject == gameObject)
  47. continue;
  48. foreach (var sb in shadowBones)
  49. {
  50. if (sb.GetComponent<Rigidbody>() == null)
  51. continue;
  52. if (sb.boneName == b.boneName)
  53. {
  54. shadowTable.Add(sb.transform, b.transform);
  55. break;
  56. }
  57. }
  58. }
  59. foreach (var b in shadowBones)
  60. Destroy(b);
  61. }
  62. void FixedUpdate()
  63. {
  64. shadowRoot.GetComponent<Rigidbody>().MovePosition(transform.position);
  65. shadowRoot.GetComponent<Rigidbody>().MoveRotation(transform.rotation);
  66. foreach (var pair in shadowTable)
  67. {
  68. pair.Value.localPosition = pair.Key.localPosition;
  69. pair.Value.localRotation = pair.Key.localRotation;
  70. }
  71. }
  72. }