using UnityEngine;using UnityEngine.Experimental.Director;
namespace ws.winx.unity.components {
public class CrossFadeMixerPlayable : CustomAnimationPlayable {
private float m_TransitionDuration = 1.0f;
private float m_TransitionTime = 0.0f;
private float m_TransitionStart = 0.0f;
private bool m_InTransition = false;
private AnimationMixerPlayable mixer;
private enum FreePort {
PORT0 = 0, PORT1 }
private FreePort __freePort;
private float __frameDuration;
public CrossFadeMixerPlayable() {
mixer = AnimationMixerPlayable.Create();
Playable.Connect(mixer, this);
mixer.AddInput(Playable.Null);
mixer.AddInput(Playable.Null);
__freePort = FreePort.PORT0;
}
public void Play(AnimationClipPlayable animationClipPlayable) {
this.Crossfade(animationClipPlayable,0f); }
public void Crossfade(AnimationClipPlayable animationPlayable, float transitionDuration, int frameRate = 30) {
m_TransitionTime = 0.0f;
__frameDuration = 1f / frameRate;
Playable playable = mixer.GetInput((int)__freePort);
if (playable != Playable.Null) {
playable.time = 0f;
playable.state = PlayState.Paused;
Playable.Disconnect(mixer, (int)__freePort); }
//Connect to free port
Playable.Connect(animationPlayable, mixer, 0, (int)__freePort);
animationPlayable.time = 0f;
animationPlayable.state = PlayState.Playing;
//UPGRADES //make dynamic transition value equal duration of current playable to finish??? //transitionDuration=(1f-(float)(playable1.time-(int)playable1.time))*playable1.CastTo<AnimationClipPlayable>().clip.length; //if this duration is longer then new playable then shift start of transition for the amount of difference
if ( __freePort == FreePort.PORT0) {
__freePort = FreePort.PORT1;
}
else {
__freePort = FreePort.PORT0;
}
m_TransitionDuration = transitionDuration;
m_InTransition = true;
Debug.Log("Time at start:" + m_TransitionTime + " duration:" + m_TransitionDuration);
}
public override void PrepareFrame(FrameData info) {
if (m_InTransition) {
if (m_TransitionTime <= m_TransitionDuration)
{
m_TransitionTime += __frameDuration;// Time.time - m_TransitionStart;
float weight = Mathf.Clamp01(m_TransitionTime / m_TransitionDuration);
mixer.SetInputWeight(1 - (int)__freePort, weight);
mixer.SetInputWeight((int)__freePort, 1.0f - weight);
Debug.Log("Transition time update:" + m_TransitionTime); }
else {
mixer.RemoveInput((int)__freePort);
m_InTransition = false;
Debug.Log("Transition end at:" + m_TransitionTime); }
Debug.Log(this.ToString()); }
}
public override string ToString() {
string info = string.Empty;
info += " crossfade layer mixer time:" + mixer.time;
for (int i = 0; i < mixer.inputCount; i++) {
Playable playable = mixer.GetInput(i);
if (playable != Playable.Null) {
info += "\n Port:" + i + " State:" + playable.state + " time:" + ((float)(playable.time - (int)playable.time)) + " weight:" + mixer.GetInputWeight(i) + " clip:" + playable.CastTo<AnimationClipPlayable>().clip; } else {
info += "\n Port:" + i + " Empty!"; }
}
return info; }
}
}
No comments:
Post a Comment