local MAIN_SKIN= "deltarunequeen"
local DROP_OBJ_ATTR= MAIN_SKIN..'dropped_obj'

if not this_template_allocation_run_only_once_give_a_unique_name_deltarunequeen then
	rawset(_G, "this_template_allocation_run_only_once_give_a_unique_name_deltarunequeen", true)
	
	freeslot("MT_DROPPED_QUEEN")
	freeslot("S_DROPPED_QUEEN")
end

addHook("TouchSpecial", function(special, toucher)
	if (toucher and (toucher.momx or toucher.momy)) then
		special.momx = toucher.momx
		special.momy = toucher.momy
		special.momz = P_AproxDistance(toucher.momx, toucher.momy)/4
		if (toucher.momz > 0) then
			special.momz = $1 + toucher.momz/8;
		end
	end
	return true
end, MT_DROPPED_QUEEN)

addHook("MobjThinker", function(mo)
	local target = mo.target
	if not(target and target.valid and target.player and
			target.skin==MAIN_SKIN and
			(target.player.kartstuff[k_spinouttimer] or target.player.playerstate==PST_DEAD)
		)
	then
		P_RemoveMobj(mo)
		return
	end
end, MT_DROPPED_QUEEN)

local function spawn_object(player)
	local dropped_object= P_SpawnMobj(player.mo.x, player.mo.y, player.mo.z+40*FRACUNIT, MT_DROPPED_QUEEN)
	dropped_object.target= player.mo
    dropped_object.friction = 60*FRACUNIT/100
	dropped_object.color= player.skincolor
	P_SpawnShadowMobj(dropped_object)
end

addHook("ThinkFrame", do
	for player in players.iterate do
		if (not player.mo) or player.mo.skin~=MAIN_SKIN then continue end
		
		if (player.kartstuff[k_spinouttimer] or player.playerstate==PST_DEAD)
				and (not player[DROP_OBJ_ATTR])
		then
			player[DROP_OBJ_ATTR]= true
			spawn_object(player)
		elseif not (player.kartstuff[k_spinouttimer] or player.playerstate==PST_DEAD)
			and player[DROP_OBJ_ATTR]
		then
			player[DROP_OBJ_ATTR]= nil
		end
	end
end)