5 // Created by Benjamin Sherratt on 04/05/2021.
6 // Copyright © 2021 SKFX Ltd. All rights reserved.
12 namespace JurassicTween.Internal {
13 class Context : IDisposable {
14 private Component component;
15 private IComponentStateCaptor componentStateCaptor;
16 private ComponentState startState;
18 private TweenParameters tweenParameters;
20 public Context(Component component, float time, TweenParameters tweenParameters) {
21 this.component = component;
22 componentStateCaptor = component.GetStateCaptor();
23 startState = componentStateCaptor.GetComponentState(component);
26 this.tweenParameters = tweenParameters;
29 public void Dispose() {
30 ComponentState endState = componentStateCaptor.GetComponentState(component);
32 ComponentStateDelta delta = componentStateCaptor.GenerateComponentStateDelta(startState, endState);
34 Animation animation = component.gameObject.GetComponent<Animation>();
35 if (animation == null) {
36 animation = component.gameObject.AddComponent<Animation>();
39 string currentClipName = "jurassicTween";
40 AnimationClip animationClip = animation.GetClip(currentClipName);
41 if (animationClip == null) {
42 animationClip = new AnimationClip();
43 animationClip.legacy = true;
44 animationClip.name = currentClipName;
45 animation.AddClip(animationClip, animationClip.name);
48 foreach (string key in delta.rangeByAnimationKey.Keys) {
49 ComponentStateDelta.Range range = delta.rangeByAnimationKey[key];
52 switch (tweenParameters.interpolation) {
53 case TweenParameters.Interpolation.Linear:
54 curve = AnimationCurve.Linear(0, range.start, time, range.end);
57 case TweenParameters.Interpolation.EaseInOut:
58 curve = AnimationCurve.EaseInOut(0, range.start, time, range.end);
61 case TweenParameters.Interpolation.CustomCurve:
62 curve = new AnimationCurve();
63 foreach (Keyframe referenceKeyframe in tweenParameters.customCurve.keys) {
64 Keyframe keyframe = new Keyframe(
65 Mathf.Lerp(0.0f, time, referenceKeyframe.time),
66 Mathf.Lerp(range.start, range.end, referenceKeyframe.value),
67 referenceKeyframe.inTangent,
68 referenceKeyframe.outTangent,
69 referenceKeyframe.inWeight,
70 referenceKeyframe.outWeight);
71 curve.AddKey(keyframe);
76 throw new Exception("We shouldn't be here");
79 animationClip.SetCurve("", component.GetType(), key, curve);
82 animation.Play(animationClip.name);