Skip to content

Instantly share code, notes, and snippets.

@romainPechot
Created May 6, 2015 10:10
Show Gist options
  • Save romainPechot/2ea20c60f2867e509929 to your computer and use it in GitHub Desktop.
Save romainPechot/2ea20c60f2867e509929 to your computer and use it in GitHub Desktop.
Unity CSharp encapsulation float as Ratio (auto clamped, IS_COMPLETE ?, Reset(), etc).
using UnityEngine;
[System.Serializable]
public class Ratio
{
private float val = 0f;
public virtual float VALUE{get{return val;}}
public virtual bool IS_RESET{get{return val == 0f;}}
public virtual bool IS_COMPLETE{get{return val == 1f;}}
public bool IN_TRANSITION{get{return !IS_RESET && !IS_COMPLETE;}}
public void Set(float newVal)
{
val = Mathf.Clamp01(newVal);
}// Set()
public void Process(float delta)
{
Set(val + delta);
}// Process()
public float Lerp(float fromVal, float toVal)
{
return Mathf.Lerp(fromVal, toVal, VALUE);
}// Lerp()
public virtual void Reset(){Set(0f);}
public virtual void Complete(){Set(1f);}
}// Ratio
[System.Serializable]
public class CurvedRatio : Ratio
{
[SerializeField] private AnimationCurve curve = AnimationCurve.EaseInOut(0f, 0f, 1f, 1f);
public override float VALUE{get{return curve.Evaluate(base.VALUE);}}
}// CurvedRatio
[System.Serializable]
public class TimeRatio : CurvedRatio
{
// duration
[SerializeField] private float duration = 1f;
public float DURATION{get{return duration;}}
// reverse ?
[SerializeField] private bool isReverse = false;
public bool IS_REVERSE{get{return isReverse;}}
public override bool IS_COMPLETE
{
get
{
if(isReverse) return base.IS_COMPLETE;
else return base.IS_COMPLETE;
}
}
public override bool IS_RESET
{
get
{
if(isReverse) return base.IS_COMPLETE;
else return base.IS_RESET;
}
}
public void SetNormal(){SetReverse(false);}
public void SetReverse(){SetReverse(true);}
public void SetReverse(bool isReverse)
{
this.isReverse = isReverse;
}// SetReverse()
public override void Reset()
{
if(isReverse) base.Complete();
else base.Reset();
}// Reset()
public override void Complete()
{
if(isReverse) base.Reset();
else base.Complete();
}// Complete()
public void Process()
{
Process(GetDelta());
}// Process()
private float GetDelta()
{
if(isReverse) return GetDelta(-1f);
else return GetDelta(1f);
}// GetDelta()
private float GetDelta(float sign){return sign * Time.deltaTime / duration;}
}// TimeRatio : CurvedRatio
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment