--Sawblade lua
--by Callmore

-- Simple enemy that bounces back and forth between two walls.
-- As it is an enemy, the block enemy flags will also force it to bounce.
-- The speed of the object can be ajusted using the speed setting
-- on the mobjinfo

if (sawblade_initialized) then return end -- Check if the script has already been run
freeslot("MT_SAWBLABE", -- Object
		 "S_SAWBLABE", -- State
		 "SPR_SAWD", -- Sprite
		 "SFX_SAWBSU") -- Sound effect

-- State and sprite should be updated to match whatever was freeslotted
-- More states can be added since it is just used for animation
states[S_SAWBLABE] = {SPR_SAWD, A|FF_PAPERSPRITE|FF_ANIMATE, -1, nil, 1, 2, S_SAWBLABE}

mobjinfo[MT_SAWBLABE] = {
	doomednum = 3760, -- Change this if you modify to a number below 4095 to avoid conflicts
	spawnstate = S_SAWBLABE, -- Should match the state that was freeslotted
	spawnhealth = 1000, -- Should be 1000 to prevent the enemy dying
	radius = 64*FRACUNIT, -- Diameter is 2*radius
	height = 128*FRACUNIT,
	speed = 4, -- Speed of object in fracunits per frame
	flags = MF_SPECIAL|MF_ENEMY,
}

local function sawbladeThink(mo)
	if not mo.sb_init then
		mo.sb_init = true
		mo.sb_currentmovement = false
		mo.sb_startangle = mo.angle
	end
	
	local xdir = FixedMul(cos(mo.sb_startangle), mapobjectscale)
	local ydir = FixedMul(sin(mo.sb_startangle), mapobjectscale)
	
	local didMove
	if mo.sb_currentmovement then
		didMove = P_TryMove(mo, mo.x - (xdir * mo.info.speed), mo.y - (ydir * mo.info.speed))
	else
		didMove = P_TryMove(mo, mo.x + (xdir * mo.info.speed), mo.y + (ydir * mo.info.speed))
	end
	if not didMove then
		mo.sb_currentmovement = not $
		mo.angle = mo.sb_startangle + (mo.sb_currentmovement and ANGLE_180 or 0)
	end
	
	-- This will make the a sound play every second from the sawblade
	-- Change the sfx_ to match the sound that you freeslotted
	--   or whatever sound you want to play
	if (leveltime % 35) == 0 then
		S_StartSound(mo, SFX_SAWBSU)
	end
end
addHook("MobjThinker", sawbladeThink, MT_SAWBLABE)

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