I have never needed to do this before, and cannot find much information on it.
Is there any way to round each float in a Vector3 to the nearest power of 3?
e.g. : 3, 6, 9, 12, 15, 18, 21, 24…
So a Vector3 of (3.8f, 8.0f, 1.4f) would round to (3.0f, 9.0f, 0f)
The values you’ve listed aren’t powers but multiples, so this one usually helps:
int GetMultiple(float x, int multipleOf)
{
return ((int)((x / multipleOf) + 0.5f)) * multipleOf;
}
Note, that there are a few edge cases due to float precision, for example when:
x = (y + 0.5)*multipleOf where y is a integer
Example:
x = 10.5
You probably expect 12, but you may also get 9 if
(10.5/3 +0.5) is something like 3.49999 + 0.5 = 3.9999 (casted to an int it’s 3).