Inverse Interpolate#
Math / Algebra / Inverse Interpolate
Can Read
Cannot Write
Description#
Determines where a value lies between two points
Code#
using System;
using UnityEngine;
using VisualScript.Icons;
namespace VisualScript.Runtime
{
[Get]
[Title("Inverse Interpolate")]
[Category("Math/Algebra/Inverse Interpolate")]
[Description("Determines where a value lies between two points")]
[Image(typeof(IconInterpolate), ColorTheme.Type.Yellow, typeof(BadgeArrowLeft))]
[Keywords("Lerp", "Linear", "Step", "Ratio", "Normal", "Normalize")]
[Serializable]
public class TypeNumberMathInverseInterpolate : TypeNumber
{
private const double Epsilon = float.Epsilon;
[SerializeField] private GetNumber m_Min = new GetNumber();
[SerializeField] private GetNumber m_Max = new GetNumber();
[SerializeField] private GetNumber m_Value = new GetNumber();
[SerializeField] private GetBool m_Clamp = new GetBool();
public override double GetPreview(GameObject source) =>
InverseLerp(
this.m_Min.GetPreview(source),
this.m_Max.GetPreview(source),
this.m_Value.GetPreview(source),
this.m_Clamp.GetPreview(source)
);
public override double Get(Args args)
{
double min = this.m_Min.Get(args);
double max = this.m_Max.Get(args);
double value = this.m_Value.Get(args);
bool clamp = this.m_Clamp.Get(args);
return InverseLerp(min, max, value, clamp);
}
private static double InverseLerp(double min, double max, double value, bool clamp)
{
double result = Math.Abs(min - max) > Epsilon
? (value - min) / (max - min)
: 0.0;
return clamp ? Math.Clamp(result, 0.0, 1.0) : result;
}
public override string ToString()
{
return $"Inverse Lerp between {this.m_Min} to {this.m_Max} for {this.m_Value}";
}
protected override SubscriptionMode Subscription => SubscriptionMode.OnChange;
}
}