local timer = 0.0
local timerMax = 10.0
local distToPlayerMax = 80
local triggers = {}

function init()
	local findTriggers = FindTriggers("tumbleweed_spawner")
	for _, trigger in pairs(findTriggers) do
		local min, max = GetTriggerBounds(trigger)
		triggers[trigger] = {
			position = GetTriggerTransform(trigger).pos, 
			min = min, 
			max = max
	}
	end
end

function tick(dt)
	timer = timer + dt
	if timer > timerMax then
		local validTriggers = {} 
		for trigger, properties in pairs(triggers) do 
			local distToPlayer = VecLength(VecSub(GetPlayerPos(), properties.position))
			if distToPlayer > distToPlayerMax then
				validTriggers[#validTriggers + 1] = {min = properties.min, max = properties.max}
			end
		end
		if #validTriggers == 0 then return end
		local entities = FindBodies("tumbleweedfree", true)
		for _, entity in pairs(entities) do
			local validTrigger = validTriggers[math.random(1, #validTriggers)]
			local positionSpawn = VecAdd(validTrigger.min, Vec(math.random() * (validTrigger.max[1] - validTrigger.min[1]), 0, math.random() * (validTrigger.max[3] - validTrigger.min[3])))
			if not QueryRaycast(positionSpawn, Vec(0, 1, 0), 1, 0.3)  then 
				SetBodyDynamic(entity, true)
				SetBodyActive(entity, true)
				SetBodyTransform(entity, Transform(positionSpawn))
				RemoveTag(entity, "tumbleweedfree")
				timer = 0.0
			end
		end
	end
end