-- Flame
-- A small Homing Attack mockup.
-- Single Target

addHook("ThinkFrame", do
	for p in players.iterate
		if not p.mo then return end
		local mo = p.mo

		-- Find a tracer to home in on if jumping
		-- Show a little marker if one is visible
		if mo.tracer
		and mo.tracer.valid then
			if (p.flhoming)
			or ((p.pflags & PF_JUMPED) and (mo.z > mo.tracer.z)) 
			and (mo.tracer.health > 0) then
				if (p == consoleplayer) then -- Only show the marker for YOU
					P_SpawnLockOn(p, mo.tracer, S_LOCKON1)
				end
			else
				L_SetTracer(mo, nil)
			end
		else
			L_SetTracer(mo, L_Look4Target(mo, 3*RING_DIST/4))
		end

		-- Homing Action
		p.flhoming = $ or 0
		if (p.flhoming > 0)
			-- Squish the sprite
			mo.spritexscale = max(FRACUNIT * 3/4, min($ - FRACUNIT/90, FRACUNIT))
			mo.spriteyscale = max(FRACUNIT, min($ + FRACUNIT/90, FRACUNIT*4/3))
			if P_IsObjectOnGround(mo) 
			or (mo.eflags & MFE_JUSTHITFLOOR) 
			or (mo.tracer and mo.tracer.valid) and (mo.tracer.health <= 0) then
				L_SetTracer(mo, nil)
				p.flhoming = 0
				mo.momz = $>>1
				return -- Don't process anything else
			end
			
			if mo.tracer and mo.tracer.valid then
				L_HomingAttackXY(mo, mo.tracer) -- Home in
				P_SetObjectMomZ(mo, -2*gravity, true)
				P_SpawnGhostMobj(mo) -- Spawn a ghost trail behind you
			end
			
			-- Decrease tic timer by one
			p.flhoming = $ - 1
		else
			-- Unsquish the sprite. Don't make the math too complex...
			mo.spritexscale = ($ < FRACUNIT) and $ + FRACUNIT/25 or FRACUNIT
			mo.spriteyscale = ($ > FRACUNIT) and $ - FRACUNIT/25 or FRACUNIT
		end
	end
end)

addHook("AbilitySpecial", function(p)
	if not p.mo then return end
	local mo = p.mo

	if not (p.charability == CA_THOK)
	and not (p.charability == CA_HOMINGTHOK) 
	and not (p.charability == CA_DOUBLEJUMP) then return false end -- Not an ability we want to override
	
	if (mo.tracer and mo.tracer.valid) then -- Not a valid tracer from the previous tic	
		if p.flhoming then return true end -- Not already homing in on a target
		-- We actually don't want the player to do anything if they're already homing
		
		-- Homing trigger
		if not (mo.state == S_PLAY_ROLL) then mo.state = S_PLAY_ROLL end
		S_StartSoundAtVolume(mo, sfx_s3k47, 170)
		S_StartSoundAtVolume(mo, sfx_zoom, 140)
		--P_SetObjectMomZ(mo, p.actionspd/7, false)
		local dist = abs(FixedHypot(target.x - mo.x, target.y - mo.y))/20
		P_SetObjectMomZ(mo, dist, false)
		
		-- Start homing in!
		p.flhoming = 2*TICRATE -- Only home in for 2 seconds before getting 'tired'
		--p.pflags = $ | PF_THOKKED
		return true
	else
		return false
	end
end)