local body = 0
local jumpTimer = 0.0
local lifeTime = 0.0

local dead = false

isStart = GetBoolParam("IsStart", false)

function init()
	body = FindBody("tumbleweed")
	bodyPos = GetBodyTransform(body)
	if not isStart then
		SetBodyDynamic(body, false)
		SetBodyActive(body, false)
	end
	lifeTime = math.random(15, 30)
	
	snd = LoadLoop("MOD/sound/tumbleweed-loop.ogg")
end

function tick()
	
end

function update(dt)
	if lifeTime > 0 then
		lifeTime = lifeTime - dt
	end

	if not HasTag("tumbleweedfree") then
		local transform = GetBodyTransform(body)

		if lifeTime <= 0.0 and VecLength(VecSub(GetPlayerPos(), transform.pos)) > 50 and not IsBodyVisible(body, 130) then
			SetTag(body, "tumbleweedfree")
			if not isStart then
				SetBodyTransform(body, bodyPos)
				SetBodyDynamic(body, false)
				SetBodyActive(body, false)
				lifeTime = math.random(15, 30)
			else
				Delete(body)
			end
		end

		local windVec = GetWindVelocity(transform.pos)

		if VecLength(windVec) == 0.0 then
			windVec = Vec(1, 0.6, 1)
		end

		jumpTimer = jumpTimer + dt
		if jumpTimer > 0.25 + (math.random() / 5) then
			jumpTimer = 0.0
			windVec[2] = windVec[2] * 0.2
			local accel = windVec
			PlayLoop(snd, transform.pos, 0.3)
			local velocity = GetBodyVelocity(body)

			local frictionKoef = -0.3
			local friction = VecScale(velocity, frictionKoef)
			friction[2] = 0.0
			accel = VecAdd(accel, friction)
			velocity = VecAdd(accel, velocity)
			
			SetBodyVelocity(body, velocity)
		end
	end
end