ProjectDDD/Packages/SLUnity/SLUI/SLUILayoutScale.cs

98 lines
2.5 KiB
C#
Raw Normal View History

using UnityEngine;
using UnityEngine.UI;
namespace Superlazy.UI
{
public class SLUILayoutScale : SLUIOnOffTransition
{
public float onDuration = 0.3f;
public float offDuration = 0.3f;
public Vector2 startSize = Vector2.one;
public Vector2 endSize = Vector2.zero;
private float currentTime;
private LayoutElement layoutElement;
protected override void Validate()
{
layoutElement = GetComponent<LayoutElement>();
}
protected override void Init()
{
if (currentState == false)
{
currentTime = 0;
}
else
{
currentTime = 1;
}
var current = currentTime == 1 ? startSize : endSize;
layoutElement.preferredWidth = current.x;
layoutElement.preferredHeight = current.y;
}
protected override bool OnUpdate(bool forceUpdate = false)
{
var result = false;
if (currentState)
{
if (onDuration == 0)
{
currentTime = 1;
}
else
{
currentTime += Time.unscaledDeltaTime / onDuration;
}
if (currentTime >= 1.0f)
{
currentTime = 1.0f;
result = true;
}
}
else
{
if (offDuration == 0)
{
currentTime = 0;
}
else
{
currentTime -= Time.unscaledDeltaTime / offDuration;
}
if (currentTime <= 0.0f)
{
currentTime = 0.0f;
result = true;
}
}
var ease = currentTime == 1.0f ? 1 :
currentState ? 1 - Mathf.Pow(2, -10 * currentTime)
: Mathf.Pow(2, -10 * (1 - currentTime));
var current = Vector2.Lerp(endSize, startSize, ease);
layoutElement.preferredWidth = current.x;
layoutElement.preferredHeight = current.y;
return result;
}
protected override void ForceDisable()
{
currentTime = 0.0f;
layoutElement.preferredWidth = endSize.x;
layoutElement.preferredHeight = endSize.y;
}
}
}