local function a(a,k,V,l)local n=a:pointToObjectSpace(k)local C=n.Unit local T=n.Magnitude local L=forwardV3:Cross(-C)local i=math.acos(-C.Z)local N=a*(fromAxisAngle(L,i)):inverse()if T<math.max(l,V)-math.min(l,V)then return N*CF(0,0,(math.max(l,V)-math.min(l,V))-T),-hpi,pi elseif T>V+l then return N,hpi,0 else local a=-math.acos(((-(l*l)+V*V)+T*T)/((2*V)*T))local k=math.acos(((l*l-V*V)+T*T)/((2*l)*T))return N,hpi-a,-(k-a)end end
--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--
--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--
--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--
--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--
--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--

local function solveLegIK(o, t, l0, l1) -- Does the major math
	-- Make the position local relative to the origin
	local l = o:pointToObjectSpace(t) -- World space to local space
	local lu = l.Unit -- Get normalized unit for future math

	local m = l.Magnitude -- Get the length from the position to the target

	-- Make a CFrame pointing from the shoulder position directing to the second position
	local x = forwardV3:Cross(-lu) -- Cross the forward vector with the negative of the normalized unit
	local g = math.acos(-lu.Z) -- Get the arc-cosine of the negative normalized unit
	local p = o * fromAxisAngle(x, g):inverse() -- Get the IK plane

	-- In a right-triangle, we have the hypotenuse and the two shorter legs.
	-- In a right triangle, the hypotenuse is side "c," and the legs are a and b.
	-- This information will be helpful later on.

	if m < math.max(l1, l0) - math.min(l1, l0) then
		-- If c is between the lengths of a and b then return an offsetted plane so that one of the lengths reaches the goal,
		-- but the other length is folded so it looks natural
		-- This cacluation is done when a position comes before the end of the leg, and may look a bit... odd

		return p * CF(0, 0, math.max(l1, l0) - math.min(l1, l0) - m), -hpi, pi
	elseif m > l0 + l1 then
		-- If c > a + b then return flat angles and an offsetted plane which reaches its target
		-- Basically, this make the leg flat if there is nothing to place it on

		return p, hpi, 0
	else
		-- Otherwise, use the law of cosines
		-- This is going to be all cases where the leg actually bends

		local a1 = -math.acos((-(l1 * l1) + (l0 * l0) + (m * m)) / (2 * l0 * m))
		local a2 = math.acos(((l1 * l1) - (l0 * l0) + (m * m)) / (2 * l1 * m))
		return p, hpi - a1, -(a2 - a1)
	end
end
