-----------------------------------------------------------------------------
--  File     : /mods/4DC_V0.8/projectiles/napalm_missile/napalm_missile_script.lua
--
--  Author(s): EbolaSoup, Resin Smoker, Optimus Prime, Vissroid 
--
--  Special Thanks to : Exavier_Macbeth
--
--  Summary  : Terran Napalm Missile
--
--  Copyright © 2011 4DC_V0.8  All rights reserved.
-----------------------------------------------------------------------------

-- Misc Local files
local NapalmMissileProjectile = import('/mods/4DC_V0.8/lua/4d_projectiles.lua').NapalmMissileProjectile
local RandomFloat = import('/lua/utilities.lua').GetRandomFloat
local Explosion = import('/lua/defaultexplosions.lua')

Napalm_Missile = Class(NapalmMissileProjectile) {

    PolyTrail = '/effects/emitters/default_polytrail_06_emit.bp',
        
    OnCreate = function(self)   
        NapalmMissileProjectile.OnCreate(self)
        self:SetCollisionShape('Sphere', 0, 0, 0, 1.0)
        self.Army = self:GetArmy()
        self.MyTarget = self:GetTrackingTarget()
        self.BP = self:GetBlueprint() 
        self:ForkThread(self.UpdateMeshThread)   
    end,
    
    GDTT = function(self) -- Get Distance To Target (2 Vector comparison)
        local mpos = self:GetPosition()    
        local tpos = self:GetCurrentTargetPosition()
        local dist = VDist2(mpos[1], mpos[3], tpos[1], tpos[3])
        return math.floor(dist)
    end,  
    
    UpdateMeshThread = function(self)
        if not self:BeenDestroyed() then  
            WaitSeconds(0.5)          
            if not self:BeenDestroyed() then
                -- Change mesh so fins show
                self:SetMesh('/mods/4DC_V0.8/projectiles/napalm_missile/napalm_missile_UnPacked01_mesh')
                -- Polytrails offset to wing tips
                CreateTrail(self, -1, self.Army, self.PolyTrail ):OffsetEmitter(0.075, -0.05, 0.25)
                CreateTrail(self, -1, self.Army, self.PolyTrail ):OffsetEmitter(-0.085, -0.055, 0.25)
                CreateTrail(self, -1, self.Army, self.PolyTrail ):OffsetEmitter(0, 0.09, 0.25) 
                self:ForkThread(self.SetTurnRateByDist)     
            end
        end 
    end,         
     
    SetTurnRateByDist = function(self)
        while not self:BeenDestroyed() do 
            -- Allow for a smooth arc    
            local rate = math.ceil( (self.Data.Radius * math.pi) / math.floor( math.sqrt( self:GDTT() ) ) )                          
            self:SetTurnRate(rate)            
            WaitTicks(4)           
        end                
    end,  
           
    OnImpact = function(self, TargetType, targetEntity)
        if not self:BeenDestroyed() then
            if TargetType == 'Terrain' then 
                local size = RandomFloat(0.75,1.5)
                Explosion.CreateScorchMarkDecal(self, size, self.Army)
            end	
        end 
        NapalmMissileProjectile.OnImpact( self, TargetType, targetEntity )
    end,

}
TypeClass = Napalm_Missile