--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 (crustapple_initialized) then return end -- Check if the script has already been run
freeslot("MT_CRUSTAPPLE", -- Object
		 "S_CRUSTAPPLE", -- State
		 "SPR_CRPN", -- Sprites
		 "SPR_CRPL")

-- 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_CRUSTAPPLE] = {SPR_CRPN, A|FF_ANIMATE, -1, nil, 7, 5, S_CRUSTAPPLE}

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

local function crustPineappleSpawn(mo)
	mo.scale = $*1
end

addHook("MobjSpawn", crustPineappleSpawn, MT_CRUSTAPPLE)

local function crustPineappleThink(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))
		mo.sprite = SPR_CRPN
	else
		didMove = P_TryMove(mo, mo.x + (xdir * mo.info.speed), mo.y + (ydir * mo.info.speed))
		mo.sprite = SPR_CRPL
	end
	if not didMove then
		mo.sb_currentmovement = not $
		mo.angle = mo.sb_startangle + (mo.sb_currentmovement and ANGLE_180 or 0)
	end
	
end
addHook("MobjThinker", crustPineappleThink, MT_CRUSTAPPLE)

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