84 lines
1.8 KiB
C#
84 lines
1.8 KiB
C#
using RootMotion.FinalIK;
|
|
using UnityEngine;
|
|
|
|
[RequireComponent(typeof(CCDIK))]
|
|
public class RodIK : MonoBehaviour
|
|
{
|
|
[SerializeField]
|
|
private CCDIK ik;
|
|
|
|
[SerializeField]
|
|
private Transform tipBone;
|
|
|
|
[Header("Creation")]
|
|
[Tooltip("Use this variable to assign IK automation from button")]
|
|
[SerializeField]
|
|
private Transform boneIKRoot;
|
|
|
|
public float action = 5f;
|
|
|
|
public float minBendWeight = 0.01f;
|
|
|
|
public float maxBendWeight = 1f;
|
|
|
|
private Transform bendTarget;
|
|
|
|
private float tension;
|
|
|
|
private float currentWeight;
|
|
|
|
private float tensionMomentum;
|
|
|
|
private void Start()
|
|
{
|
|
ik.fixTransforms = false;
|
|
ik.solver.SetIKPositionWeight(0.001f);
|
|
ik.solver.FixTransforms();
|
|
ik.solver.Update();
|
|
float num = 0f;
|
|
float num2 = 1f / (float)ik.solver.bones.Length / 2f;
|
|
ik.solver.tolerance = 0f;
|
|
ik.solver.maxIterations = 1;
|
|
IKSolver.Bone[] bones = ik.solver.bones;
|
|
for (int i = 0; i < bones.Length; i++)
|
|
{
|
|
bones[i].weight = 0.1f;
|
|
num += num2;
|
|
}
|
|
}
|
|
|
|
public void SetIkWeight(float value)
|
|
{
|
|
tension = value;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
tensionMomentum = Mathf.Lerp(tensionMomentum, tension, Time.deltaTime * 15f * action);
|
|
float iKPositionWeight = Mathf.Lerp(minBendWeight, maxBendWeight, tensionMomentum);
|
|
ik.solver.SetIKPositionWeight(iKPositionWeight);
|
|
if (bendTarget != null)
|
|
{
|
|
Vector3.Lerp(tipBone.position, bendTarget.position, tension);
|
|
ik.solver.SetIKPosition(bendTarget.position);
|
|
}
|
|
ik.solver.FixTransforms();
|
|
ik.solver.Update();
|
|
}
|
|
|
|
public void SetIKTarget(Transform target)
|
|
{
|
|
bendTarget = target;
|
|
}
|
|
|
|
private void SetRodIKBones()
|
|
{
|
|
ik = GetComponent<CCDIK>();
|
|
Transform[] componentsInChildren = boneIKRoot.GetComponentsInChildren<Transform>();
|
|
foreach (Transform bone in componentsInChildren)
|
|
{
|
|
ik.solver.AddBone(bone);
|
|
}
|
|
}
|
|
}
|