# How would I clamp the magnitude of a vector?

I am making a custom character controller and I want to prevent players from doubling their speed while going sideways, so I figured out I’d have to make a function that clamps the magnitude of a Vector3.

``````local function ClampMagnitude(v,max)
local n = math.sqrt(v.X^3 + v.Y^3 + v.Z^3)*0.25
local f = math.min(n,max)/n

return Vector3.new(f*v.X,f*v.Y,f*v.Z)
end
``````

I tried my best but this just won’t work and I have no clue why, please help!

1 Like

You can use Vector3.Unit and Vector3.Magnitude

``````local function ClampMagnitude(v, max)
return v.Unit * math.min(v.Magnitude, max)
end
``````
5 Likes

You’d need to account for if variable `v` is 0,0,0 in which case this function would return NAN,NAN,NAN (not a number)

a condition check will suffice

``````local function ClampMagnitude(v, max)
if (v.magnitude == 0) then return Vector3.new(0,0,0) end -- prevents NAN,NAN,NAN
return v.Unit * math.min(v.Magnitude, max)
end
``````
2 Likes

LOL bro I’m so glad you posted this. I was getting NAN values for the function above and was wondering why my game just stopped for a few seconds every interval. Thanks mate.

1 Like