CCDBendGoal.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace RootMotion.FinalIK
  5. {
  6. /// <summary>
  7. /// Bend goal object for CCDIK. Add this to a GameObject you wish CCD to bend towards.
  8. /// </summary>
  9. public class CCDBendGoal : MonoBehaviour
  10. {
  11. public CCDIK ik;
  12. [Range(0f, 1f)] public float weight = 1f;
  13. private void Start()
  14. {
  15. ik.solver.OnPreUpdate += BeforeIK;
  16. }
  17. private void BeforeIK()
  18. {
  19. if (!enabled) return;
  20. float w = ik.solver.IKPositionWeight * weight;
  21. if (w <= 0f) return;
  22. Vector3 firstBonePos = ik.solver.bones[0].transform.position;
  23. Vector3 lastBonePos = ik.solver.bones[ik.solver.bones.Length - 1].transform.position;
  24. // Rotating the CCD chain towards this gameobject before it solves so it rolls in from that direction
  25. Quaternion f = Quaternion.FromToRotation(lastBonePos - firstBonePos, transform.position - firstBonePos);
  26. if (w < 1f) f = Quaternion.Slerp(Quaternion.identity, f, w);
  27. ik.solver.bones[0].transform.rotation = f * ik.solver.bones[0].transform.rotation;
  28. }
  29. private void OnDestroy()
  30. {
  31. if (ik != null) ik.solver.OnPreUpdate -= BeforeIK;
  32. }
  33. }
  34. }