Easier way to find the range between objects?

I"ve created a function that returns the range between 2 parts from their Position. Considering how long it is, I immediately smelled spaghetti, and am wondering what the correct way of finding the range between 2 objects is?

Here is the code in question:

local function findRange(origin, destination)
	if typeof(origin) == "Vector3" and typeof(destination) == "Vector3" then
		--first we abs everything
		origin = Vector3.new(math.abs(origin.X), math.abs(origin.Y) ,math.abs(origin.Z))
		destination = Vector3.new(math.abs(destination.X), math.abs(destination.Y) ,math.abs(destination.Z))
		
		--subtract to acquire range
		local range = origin - destination
		range = Vector3.new(math.abs(range.X), math.abs(range.Y), math.abs(range.Z))
		
		--solve right triangle with 2 sides(X and Z), no angles			
		local angle_K  = math.atan(math.tan(range.X, range.Z))
		local magnitude_2D = range.X / math.cos(angle_K)
		
		--solve ANOTHER right triangle with 2 sides(final_range and Y), no angles
		local angle_V = math.atan(math.tan(range.Y, magnitude_2D))
		local magnitude_final = magnitude_2D / math.cos(angle_V)
		
		--now we have absolutely and undoubtedly found range in the most effective way possible :)))))
		return magnitude_final
	end
end

You could just use Magnitude
Like this
local range = (Position2 - Position1).Magnitude

1 Like

I’m not clear why you need to keep doing abs etc.

Range = (position2 - position1).Magnitude

Beat me to it. But glad we both said the same thing.

The other replies are correct, but for what it’s worth if you wanted to go the math route, you would want to use the Pythagorean theorem for this, which actually works in 3+ dimensions.

math.sqrt( (x1-x2)^2 + (y1+y2)^2 + (z1-z2)^2 )

The square of any number is positive so we don’t need to use abs and we don’t care about which vector is 1 and which one is 2. This is what the other comments’ code does behind the scenes. This is the same as (vector1 - vector2).Magnitude, albeit slightly slower just because we’re recreating an existing C++ function in Lua.

2 Likes

Thank you to everyone for the replies. I wasn’t sure if I would be using magnitude right, but it turned out right.

The other replies are correct, but for what it’s worth if you wanted to go the math route, you would want to use the Pythagorean theorem for this, which actually works in 3+ dimensions.

Thank you, can’t believe I didn’t think of that while building that function :smiley:

1 Like