Skip to content

Instantly share code, notes, and snippets.

@Broxzier
Last active April 14, 2023 15:33
Show Gist options
  • Select an option

  • Save Broxzier/b0247a677ea8776c3b96d1295b4ff0b7 to your computer and use it in GitHub Desktop.

Select an option

Save Broxzier/b0247a677ea8776c3b96d1295b4ff0b7 to your computer and use it in GitHub Desktop.
Normalized Sigmoid and Tweakable Curve
/// <summary>
/// Returns the value for X on a curve going through {-1,-1}, {0,0} and {1,1}.
/// The shape of the curve is determined by the second argument.
/// A negative value makes the curve flat at 0, a positive constant makes it steep at 0.
/// </summary>
/// <param name="x">Position to read from the curve; Domain: (-1,1)</param>
/// <param name="curve">Constant to shape the curve; Domain: (-1,1)</param>
/// <returns>The value of the curve at X.</returns>
public static float NormalizedSigmoid(float x, float curve)
{
x = Mathf.Clamp(x, -1f, 1f);
curve = Mathf.Clamp(curve, -1f, 1f);
return (x - x * curve) / (curve - Mathf.Abs(x) * 2f * curve + 1f);
}
/// <summary>
/// Returns the value for X on a curve determined by the constants k, j and l.
/// The shape of the curve always starts at {0,0} and ends at {1,1}.
/// j and l determine the fixed point's location, and k determines the slope at this point.
/// Graph: https://www.desmos.com/calculator/0bdawyhnvy
/// </summary>
/// <param name="x">Position to read from the curve; Domain: (0,1)</param>
/// <param name="k">Slope of the curve at the fixed point; Domain: (-1,1)</param>
/// <param name="j">X position of fixed point; Domain: (-1,1)</param>
/// <param name="l">Y position of fixed point; Domain: (-1,1)</param>
/// <returns>The value of the curve at X.</returns>
public static float NormalizedCurve(float x, float k, float j, float l)
{
// Sanitize input
x = Mathf.Clamp01(x);
k = Mathf.Clamp(k, -1f, 1f);
j = Mathf.Clamp(j, -1f, 1f);
l = Mathf.Clamp(l, -1f, 1f);
float warpedX = NormalizedSigmoid(x, j);
float slanted = NormalizedSigmoid(warpedX * 2 - 1, k);
float warpedY = NormalizedSigmoid(slanted / 2 + 0.5f, -l);
return warpedY;
}
/// <summary>
/// Uses the normalized curve to create a sigmoid curve by flipping it for the negative input, extending the domain into the negative to -1.
/// </summary>
/// <param name="x">Position to read from the curve; Domain: (-1,1)</param>
/// <param name="k">Slope of the curve at the fixed point; Domain: (-1,1)</param>
/// <param name="j">X position of fixed point; Domain: (-1,1)</param>
/// <param name="l">Y position of fixed point; Domain: (-1,1)</param>
/// <returns></returns>
public static float NormalizedSigmoidTuned(float x, float k, float j, float l)
{
x = Mathf.Clamp(x, -1f, 1f);
return Mathf.Sign(x) * NormalizedCurve(Mathf.Abs(x), k, j, l);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment