Skip to content

Instantly share code, notes, and snippets.

@drZool
Last active April 30, 2020 20:35
Show Gist options
  • Select an option

  • Save drZool/73faa74c389a714968d2c9c07ba10ace to your computer and use it in GitHub Desktop.

Select an option

Save drZool/73faa74c389a714968d2c9c07ba10ace to your computer and use it in GitHub Desktop.
Commonly used math functions not included in unity
using UnityEngine;
using System.Collections;
public static class MathUtils
{
public const float TAU = Mathf.PI * 2;
public static float MoveTowards (float current, float goal, float amount)
{
var delta = goal - current;
if (delta < 0) {
if (-delta < amount)
return goal;
return current - amount;
}
if (delta < amount)
return goal;
return current + amount;
}
public static double Clamp01 (double d)
{
if (d < 0)
return 0;
if (d > 1)
return 1;
return d;
}
public static float ClampRotation (float angle, float minAngle, float maxAngle)
{
if (angle > 180)
angle -= 360;
if (minAngle > 180)
minAngle -= 360;
if (maxAngle > 180)
maxAngle -= 360;
return Mathf.Clamp (angle, minAngle, maxAngle);
}
}
@ilovelinux
Copy link
Copy Markdown

@drZool
Copy link
Copy Markdown
Author

drZool commented Apr 30, 2020

Clamp01 exists since Unity 5.2: https://docs.unity3d.com/520/Documentation/ScriptReference/Mathf.html πŸ˜‰

Yes and it's great, however this version supports the double type, which Unity's doesn't.
Stay Safe!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment