Created
September 20, 2024 01:39
-
-
Save keenanwoodall/9434d153363a4bbaf18b65499851d832 to your computer and use it in GitHub Desktop.
Animation Rigging Distance Constraint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DistanceConstraint : RigConstraint<DistanceConstraint.Job, DistanceConstraint.Data, DistanceConstraint.Binder> | |
{ | |
public struct Job : IWeightedAnimationJob | |
{ | |
public FloatProperty jobWeight { get; set; } | |
public ReadOnlyTransformHandle source; | |
public ReadWriteTransformHandle target; | |
public Vector3 initialTargetLocalPos; | |
public float distance; | |
public void ProcessRootMotion(AnimationStream stream){} | |
public void ProcessAnimation(AnimationStream stream) | |
{ | |
var totalWeight = jobWeight.Get(stream); | |
if (totalWeight <= 0f) | |
return; | |
target.SetLocalPosition(stream, initialTargetLocalPos); | |
var sourcePos = source.GetPosition(stream); | |
var targetPos = target.GetPosition(stream); | |
var currentOffset = targetPos - sourcePos; | |
var currentDirection = currentOffset.normalized; | |
var newTargetPos = sourcePos + currentDirection * distance; | |
target.SetPosition(stream, newTargetPos); | |
} | |
} | |
[System.Serializable] | |
public struct Data : IAnimationJobData | |
{ | |
[SyncSceneToStream] | |
public Transform source; | |
[SyncSceneToStream] | |
public Transform target; | |
public bool IsValid() => true; | |
public void SetDefaultValues() | |
{ | |
} | |
} | |
public class Binder : AnimationJobBinder<Job, Data> | |
{ | |
public override Job Create(Animator animator, ref Data data, Component component) | |
{ | |
var job = new Job | |
{ | |
source = ReadOnlyTransformHandle.Bind(animator, data.source), | |
target = ReadWriteTransformHandle.Bind(animator, data.target), | |
distance = Vector3.Distance(data.target.position, data.source.position), | |
initialTargetLocalPos = data.target.localPosition, | |
}; | |
return job; | |
} | |
public override void Destroy(Job job) | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment