-- Updating the "frame". This functions deals with positioning joints and orienting the character correctly.

function frame(mousePosition)
	if not mobileShouldTrack then return end

	local char = player.Character

	if char.Humanoid:GetState() ~= Enum.HumanoidStateType.Swimming then
		local head = char.Head
		local root = char.HumanoidRootPart
		local torso, arm

		if char.Humanoid.RigType == Enum.HumanoidRigType.R6 then
			torso = char.Torso
			arm = char["Right Arm"]
		else
			torso = char.UpperTorso
			arm = char.RightUpperArm
		end

		local toMouse = (mousePosition - head.Position).unit
		local angle = math.acos(toMouse:Dot(Vector3.new(0, 1, 0)))
		local neckAngle = angle

		-- Limit how much the head can tilt down. Too far and the head looks unnatural
		if math.deg(neckAngle) > 110 then
			neckAngle = math.rad(110)
		end

		if char.Humanoid.RigType == Enum.HumanoidRigType.R6 then
			neck.C0 = CFrame.new(0,1,0) * CFrame.Angles(math.pi - neckAngle,math.pi,0)
		else
			neck.C0 = CFrame.new(0, 0.84, 0) * CFrame.Angles(math.pi/2 - neckAngle, 0, 0)
		end

		-- Calculate horizontal rotation
		local fromArmPos = torso.Position + torso.CFrame:vectorToWorldSpace(Vector3.new(torso.Size.X/2 + arm.Size.X/2, torso.Size.Y/2 - arm.Size.Z/2, 0))
		local toMouseArm = ((mousePosition - fromArmPos) * Vector3.new(1,0,1)).unit
		local look = (torso.CFrame.lookVector * Vector3.new(1,0,1)).unit
		local lateralAngle = math.acos(toMouseArm:Dot(look))

		if lateralAngle ~= lateralAngle then
			lateralAngle = saveAngle
		else
			saveAngle = lateralAngle
		end

		-- Check for rogue math
		if tostring(lateralAngle) == "-1.#IND" then
			lateralAngle = 0
		end

		-- Handle case where character is sitting down
		if char.Humanoid:GetState() == Enum.HumanoidStateType.Seated then
			local cross = root.CFrame.lookVector:Cross(toMouseArm)
			if lateralAngle > math.pi/2 then
				lateralAngle = math.pi/2
			end
			if cross.Y < 0 then
				lateralAngle = -lateralAngle
			end
		end

		-- Turn shoulder to point to mouse
		if char.Humanoid.RigType == Enum.HumanoidRigType.R6 then
			shoulder.C0 = CFrame.new(1, 0.5, 0) * CFrame.Angles(math.pi/2 - angle, math.pi/2 + lateralAngle, 0)
		else
			shoulder.C0 = CFrame.new(1.25, 0.5, 0) * CFrame.Angles(math.pi/2 - angle, lateralAngle, 0)
		end

		-- If not sitting then aim torso laterally towards mouse
		if not amISitting(char) then
			root.CFrame = CFrame.new(
				root.Position,
				root.Position + (Vector3.new(mousePosition.X, root.Position.Y, mousePosition.Z) - root.Position).unit)
		end
	end
end
