Recently I needed to round a rotation value to increments of 45 degrees. Every once in a while I run into needing to do this and I always forget the trick to it, but it’s rather simple:
To round a number x to a multiple of another number n:
float x = 23.9;
int n = 45;
float result = round(x/n)*n;
// result = 45
Simply divide the number x by n, round it to the nearest integer, then multiply it by n.
And here are a couple Unity C# extensions I wrote so I can do this directly on float and Vector3 values:
using UnityEngine;
public static class MathExtensions {
// Round a floating point number to a multiple of n
// float f = 23;
// float rounded = f.RoundToN(45); // returns 45
public static float RoundToN(this float val, int n) {
return Mathf.RoundToInt(val / n) * n;
}
// Round a Vector3's values to multiples of n
// Vector3 v = new Vector3(12, 67, 187)
// Vector3 roundedv=v.RoundToN(45) // returns (0, 45, 180)
public static Vector3 RoundToN(this Vector3 val, int n) {
return new Vector3( Mathf.RoundToInt(val.x / n),
Mathf.RoundToInt(val.y / n),
Mathf.RoundToInt(val.z / n)) * n;
}
}