Home > database >  How can i apply normalization on vector3/float3 values with a magnitude bigger than 1?
How can i apply normalization on vector3/float3 values with a magnitude bigger than 1?

Time:09-27

I am trying to have some algorithm which calculates custom gravity. In order for it to work the way i want i want to clamp my input vector to (-1,-1,-1) or ( 1, 1, 1). If i use the normalize function it will turn into (0.6,0.6,0.6). I cannot just clamp this or the vector orientation would change.

My question is - Is there a builtin function to do is? Or do i need to just do the normalization math by myself?

CodePudding user response:

I don't think there's a built-in function for it.

Here's an idea of how to write one as an extension method:

public static class VectorX {
    public static Vector3 SquareNormalize (this Vector3 vector) {
        var bounds = new Bounds(Vector3.zero, Vector3.one * 2f);
        return bounds.ClosestPoint(vector);
    }
}

And to use it call:

myVector.SquareNormalize();

CodePudding user response:

I did it like this:

using Unity.Mathematics;
using static Unity.Mathematics.math;

public static class CustomMathHelper
{
    public static float3 ClampNormalize(float3 value, float normalizeLimit)
    {
        var maxValue = max(abs(value.x), max(abs(value.y), abs(value.z)));
        if (maxValue > abs(normalizeLimit))
        {
            var factor = (1 / maxValue) * abs(normalizeLimit);
            return new float3(factor * value.x, factor * value.y, factor * value.z);
        }

        return value;
    }
}

leaving question unresolved in case someone runs into a framework method that does this already

  • Related