
local distance = {9999,9999,9999}
-- -- Flybot -- --
freeslot(
"MT_FLYBOT",
"S_FLYINIT", "S_FLYLOOK", "S_FLYMOVE","S_FLYSTOPPED",
"SPR_FLYB","sfx_flybo")

sfxinfo[sfx_flybo] = {
	singular = true,
	priority = 64,
	flags = SF_X4AWAYSOUND
}

mobjinfo[MT_FLYBOT] = {
	--$Category Broadside Cliffs
	--$Name Black Shooting Fly
	--$Sprite FLYBA1
	doomednum = 2300,
	radius = 24*FRACUNIT,
	height = 40*FRACUNIT,
	speed = 4*FRACUNIT,
	reactiontime = 2,
	spawnstate = S_FLYINIT,
	seestate = S_FLYMOVE,
	seesound = sfx_flybo,
	deathstate = S_XPLD_FLICKY,
	deathsound = sfx_pop,
	raisestate = MT_JETTBULLET,
	painchance = 1000,
	attacksound = sfx_trfire,
	mass = 100,
	flags = MF_SLIDEME|MF_ENEMY|MF_SPECIAL|MF_SHOOTABLE|MF_NOGRAVITY
}

states[S_FLYINIT] = {
	sprite = SPR_FLYB, frame = A, tics = 1, nextstate = S_FLYLOOK}
	
states[S_FLYLOOK] = {
	sprite = SPR_FLYB, frame = A, tics = 10, action = A_Look, var1 = 0+5000<<16, var2 = 1, nextstate = S_FLYLOOK}
	
states[S_FLYSTOPPED] = {
	sprite = SPR_FLYB, frame = A, tics = 175, nextstate = S_FLYLOOK}

states[S_FLYMOVE] = {
	sprite = SPR_FLYB, frame = A, tics = 7, action = none, nextstate = S_FLYMOVE}
	
addHook("MobjThinker", function(mob)
	if mob.state == S_FLYLOOK then
		return
	end
	
	local fly_position_test = true
	
	if (mob.state == S_FLYINIT) then
		mob.shoot_timer = 0
	else
		if abs(mob.momz) > 1*FRACUNIT then
			mob.momz = mob.momz/2
		end
		
		if (abs(mob.momx) > 2*FRACUNIT or abs(mob.momy) > 2*FRACUNIT) then
			fly_position_test = P_CheckPosition(mob,mob.x+(mob.momx*2),mob.y+(mob.momy*2),mob.z)
		end
	end
	
	if mob.state == S_FLYMOVE and not(mob.target == nil) then
		local remainder = mob.tics % 2
		
		if remainder == 0 then
			distance[0] = abs(mob.target.x-mob.x)/FRACUNIT
			distance[1] = abs(mob.target.y-mob.y)/FRACUNIT
			distance[2] = abs(mob.target.z-mob.z)/FRACUNIT
		end
		
		if distance[2] > 256 then
			return
		end
		
		--manual animation handling (to reduce state count and state changes)--
		local fly_animator = {A,A,B,B,C,C,B,B}
		mob.frame = fly_animator[(mob.tics%7)+1]
		
		if mob.shoot_timer > 0 then
			mob.shoot_timer = mob.shoot_timer + 1
		end
		
		if (distance[0] < 2500 or distance[1] < 2500) then
			if (mob.shoot_timer == 0 and mob.momx < 10 and mob.momy < 10) then
				A_FaceTarget(mob)
			end
				
			if (distance[0] > (256+distance[2]) or distance[1] > (256+distance[2])) then
				A_PlaySeeSound(mob)
				A_Thrust(mob,20,1)
			else
				A_ForceStop(mob,0)
				
				if mob.shoot_timer == 0
					mob.shoot_timer = 1
				end
			end
		end
				
		if mob.shoot_timer == 15 then
			A_ShootBullet(mob)	
		elseif mob.shoot_timer >= 70 then
			A_Thrust(mob,20,1)
			A_PlaySeeSound(mob)
		end
		
		if fly_position_test == false then
			mob.state = S_FLYSTOPPED
			A_ForceStop(mob,0)
		end
	end
	
	if mob.state == S_FLYSTOPPED and mob.tics == 1 then
		mob.shoot_timer = 0
		A_ChangeAngleRelative(mob,180,180)
	end
end
,MT_FLYBOT)