#include "script/wheels.lua"
#include "script/common.lua"
#include "script/explosion.lua"

function init()
	--Time Machine
	machine_up = false
	machine_pitch = false
	timemachine_body = FindBody("time_machine", true)
	wheels_lights = FindLights("shining", true)
	start_machine_transform = GetBodyTransform(timemachine_body)
	SetBodyDynamic(timemachine_body, false)
end

function tick(dt)
	if IsHandleValid(timemachine_body) then
		Machine_Float(dt)
		Floating_Dust()
	end
end

function Machine_Float(dt)
	machine_transform = GetBodyTransform(timemachine_body)
	if machine_up then
			machine_transform.pos[2] = machine_transform.pos[2] + 0.02*dt
		else
			machine_transform.pos[2] = machine_transform.pos[2] - 0.02*dt
	end
	if machine_pitch then
			machine_transform.rot[1] = machine_transform.rot[1] + 0.02*dt
		else
			machine_transform.rot[1] = machine_transform.rot[1] - 0.02*dt
	end
	SetBodyTransform(timemachine_body, machine_transform)
	if (machine_transform.pos[2] > start_machine_transform.pos[2] + 0.01 and machine_up) or (machine_transform.pos[2] < start_machine_transform.pos[2] - 0.01 and not machine_up) then
		machine_up = not machine_up
	end
	if machine_transform.rot[1] > start_machine_transform.rot[1] + 0.02 or machine_transform.rot[1] < start_machine_transform.rot[1] - 0.02 then
		machine_pitch = not machine_pitch
	end
end

function Floating_Dust()
	for i = 1, #wheels_lights do
		QueryRejectBody(timemachine_body)
		local wheelpos = GetLightTransform(wheels_lights[i]).pos
		local hit, dist = QueryRaycast(wheelpos, Vec(0, -1,0), 3)
		local pos = VecSub(wheelpos, VecScale(Vec(0,1,0), dist))
		if hit then
			ParticleReset()
			ParticleColor(0.8, 0.75, 0.7)
			ParticleRadius(0.2, 0.6)
			ParticleAlpha(1, 0, "easeout")
			ParticleDrag(0.2)
			local x = rnd(-0.1, 0.1)
			local y = rnd(-0.1, 0.1)
			local z = rnd(-0.1, 0.1)
			local d = VecNormalize(Vec(x, y, z))
			SpawnParticle(pos, VecScale(d, rnd(1,4)), rnd(0.3, 0.75))
		end
	end
end