--Three examples on how to use the Spawn function

bananaSpawn = 0
bananaTimer = 0


function rnd(mi, ma)
	return math.random()*(ma-mi)+mi
end


function init()
	trashcanButton = FindShape("trashcan")
	trashcanPos = GetLocationTransform(FindLocation("trashcan")).pos
	
	bananaButton = FindShape("bananas")
	bananaPos = GetLocationTransform(FindLocation("bananas")).pos
	
	staircaseButton = FindShape("staircase")
	staircasePos = GetLocationTransform(FindLocation("staircase")).pos
	
	buttonSound = LoadSound("clickdown.ogg")
end


function tick(dt)
	--Trashcan
	if GetPlayerInteractShape() == trashcanButton and InputPressed("interact") then
		PlaySound(buttonSound)
		--Spawn prefab file into world at spawn position
		Spawn("MOD/prefab/trashcan.xml", Transform(trashcanPos))
	end

	--Banana fountain
	if GetPlayerInteractShape() == bananaButton and InputPressed("interact") then
		PlaySound(buttonSound)
		bananaSpawn = 30
		bananaTimer = 0
	end
	--If there are any bananas to spawn, do that ten times per second
	if bananaSpawn > 0 then
		bananaTimer = math.max(bananaTimer - dt, 0)
		if bananaTimer == 0 then
			--Generate XML for one banana and spawn it at spawn position
			local xml = "<body dynamic='true'><vox file='MOD/vox/banana.vox'/></body>"
			local entities = Spawn(xml, Transform(bananaPos))

			--Set velocity on spawned bodies (only one in this case)
			local vel = Vec(rnd(-2, 2), rnd(4, 8), rnd(-2, 2))
			for i=1, #entities do
				if GetEntityType(entities[i]) == "body" then
					SetBodyVelocity(entities[i], vel)
					SetBodyAngularVelocity(entities[i], Vec(rnd(-3,3), rnd(-3,3), rnd(-3,3)))
				end
			end
			
			--Decrease banana counter and set spawn cooldown
			bananaSpawn = bananaSpawn - 1
			bananaTimer = 0.1
		end
	end	
	
	--Staircase
	if GetPlayerInteractShape() == staircaseButton and InputPressed("interact") then
		PlaySound(buttonSound)
		--Add on step to the staircase. The third argument makes it possible to spawn static shapes.
		Spawn("<voxbox size='20 3 5'/>", Transform(staircasePos), true)
		--Offset spawn position for next step
		staircasePos = VecAdd(staircasePos, Vec(0, 0.3, -0.3))
	end
end
