--TumbleGems
if (tumblegems_initialized) then return end -- Check if the script has already been run

freeslot("MT_BLUEEMERALD", "MT_PURPEMERALD", "MT_REDEMERALD", "MT_WHITEMERALD", "MT_AQUAEMERALD", "MT_GRENEMERALD", "MT_YELLEMERALD", "MT_IVOCOIN")

local function Tumblegem(special, toucher)
	if (toucher and (toucher.momx or toucher.momy))
		special.momx = toucher.momx
		special.momy = toucher.momy
		special.momz = P_AproxDistance(toucher.momx, toucher.momy)/4
		if (toucher.momz > 0)
			special.momz = $1 + toucher.momz/8;
		end
		special.state = special.info.seestate
	end
	return true
end

addHook("TouchSpecial", Tumblegem, MT_BLUEEMERALD)
addHook("TouchSpecial", Tumblegem, MT_REDEMERALD)
addHook("TouchSpecial", Tumblegem, MT_WHITEMERALD)
addHook("TouchSpecial", Tumblegem, MT_AQUAEMERALD)
addHook("TouchSpecial", Tumblegem, MT_PURPEMERALD)
addHook("TouchSpecial", Tumblegem, MT_YELLEMERALD)
addHook("TouchSpecial", Tumblegem, MT_GRENEMERALD)
addHook("TouchSpecial", Tumblegem, MT_IVOCOIN)

local STOPSPEED = FRACUNIT
local function EmeraldThinker(mo)
    if (abs(mo.momx) < FixedMul(STOPSPEED, mo.scale)
        and abs(mo.momy) < FixedMul(STOPSPEED, mo.scale)
        and abs(mo.momz) < FixedMul(STOPSPEED*3, mo.scale))
    then
        mo.momx, mo.momy, mo.momz = 0,0,0
        mo.state = mo.info.spawnstate
    end
    mo.friction = 95*FRACUNIT/100
end

addHook("MobjThinker", EmeraldThinker, MT_BLUEEMERALD)
addHook("MobjThinker", EmeraldThinker, MT_REDEMERALD)
addHook("MobjThinker", EmeraldThinker, MT_GRENEMERALD)
addHook("MobjThinker", EmeraldThinker, MT_WHITEMERALD)
addHook("MobjThinker", EmeraldThinker, MT_AQUAEMERALD)
addHook("MobjThinker", EmeraldThinker, MT_PURPEMERALD)
addHook("MobjThinker", EmeraldThinker, MT_YELLEMERALD)
addHook("MobjThinker", EmeraldThinker, MT_IVOCOIN)

rawset(_G, "tumblegems_initialized", true) -- The script ran, don't run it again