Anyone know of a better way to clamp the distance between two vectors?

Does anyone know of a more intuitive way to do the same thing this function does? Basically, if the distance between the two vectors exceeds a certain distance, it will clamp it to the nearest point within the acceptable distance.

local function ClampDistanceBetweenVectors(V1, V2, Max)
    return V2 + ((V1-V2).Unit * math.min((V1 - V2).Magnitude,  Max))
end
2 Likes

Yeah, swapping V2 and V1 in your calculations. The typical distance formula is

v2 - v1

which makes your implementation look like it’s not clamping the distance from the center to the outside, but the distance from the outside to the center - of course those are exactly equivalent, but realizing and understanding that is just a tiny bit more mental friction that makes the code harder to understand.

Beyond that, you can only make it more readable by making it more verbose, e.g. by introducing a distance variable, clamping that, and then calculating the clamped position using the clamped dist distance.

tl;dr: no it’s perfectly readable

Thank you! Here is the updated function for anyone in the future needing it.

local function ClampDistanceBetweenVectors(V1, V2, Max) -- V1 is origin.
	return V1 + ((V2 - V1).Unit * math.min((V2 - V1).Magnitude,  Max))
end
2 Likes

thanks brah

i gotta meet the tirty character limit, so youre a sigma