-- Set up an on-screen thumbstick control:

local function ThumbstickSetup(frame, callback)
	local stick = frame:WaitForChild("Stick")
	local btn = frame:WaitForChild("Button")
	
	local btnDown = false
	
	-- Calculate relative position of thumbstick when dragged to screen position "pos":
	local function TouchDragged(pos)
		local x = (pos.X - frame.AbsolutePosition.X)
		local y = (pos.Y - frame.AbsolutePosition.Y)
		x = (x < 0 and 0 or x > frame.AbsoluteSize.X and frame.AbsoluteSize.X or x)
		y = (y < 0 and 0 or y > frame.AbsoluteSize.Y and frame.AbsoluteSize.Y or y)
		local ratioX = ((x / frame.AbsoluteSize.X) - 0.5) * 2
		local ratioY = -((y / frame.AbsoluteSize.Y) - 0.5) * 2
		stick.Position = UDim2.new(0, x, 0, y)
		callback(ratioX, ratioY)
	end
	
	local function StartTouch(pos)
		btnDown = true
		TouchDragged(pos)
		btn.Size = UDim2.new(10, 0, 10, 0)
	end
	
	local function StopTouch(pos)
		btnDown = false
		stick:TweenPosition(UDim2.new(0.5, 0, 0.5, 0), "Out", "Quint", 0.15, true)
		btn.Size = UDim2.new(1, 0, 1, 0)
		callback(0, 0)
	end
	
	btn.InputChanged:Connect(function(input)
		if (btnDown and input.UserInputType == Enum.UserInputType.Touch) then
			TouchDragged(input.Position)
		end
	end)
	
	btn.MouseButton1Down:Connect(function(x, y)
		StartTouch(Vector3.new(x, y, 0))
	end)
	
	btn.InputEnded:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.Touch then
			StopTouch(input.Position)
		end
	end)
end -- ThumbstickSetup()