-----------------------------------------------------------------------------
--  File     : /mods/4DC_V0.8/projectiles/RocketCannon/RocketCannon_script.lua
--
--  Author(s): EbolaSoup, Resin Smoker, Optimus Prime, Vissroid, Domino
--
--  Summary  : UEF Rocket Cannon Projectile
--
--  Note     : Based off concepts created by Eddy
--
--  Copyright © 2011 4DC_V0.8  All rights reserved.
-----------------------------------------------------------------------------

local TRocketCannonProjectile = import('/mods/4DC_V0.8/lua/4d_projectiles.lua').TRocketCannon
local Explosion = import('/lua/defaultexplosions.lua')
local RandomFloat = import('/lua/utilities.lua').GetRandomFloat

TDRocketCannon01 = Class(TRocketCannonProjectile) {

    OnCreate = function(self)   
        TRocketCannonProjectile.OnCreate(self)
        self:SetCollisionShape('Sphere', 0, 0, 0, 1.0)
        self:ForkThread(self.SetTurnRateByDist)   
    end,
        
    SetTurnRateByDist = function(self)
        local trigger = false
        local startDst = {}
        table.insert( startDst, self:GDTT() )
        while not self:BeenDestroyed() and self:GetTrackingTarget() do  
            local rate = math.ceil( (self.Data.Radius * math.pi) / math.floor( math.sqrt( self:GDTT() ) ) )                          
            if self:GDTT() <= 10 and not trigger then
                trigger = true
                self:ForkThread(self.Spread)
            elseif self:GDTT() < ( startDst[1] * 0.25) then
                self:SetTurnRate(rate)
            end
            WaitTicks(2)           
        end               
    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,
    
    Spread = function(self)
        -- Fan the missiles out around the target
        local angle = ( 2 * math.pi ) / self.Data.PPF
        local pos = self:GetCurrentTargetPosition()  
        xVec = pos[1] + ( math.sin( self.Data.Number * angle ) ) * 1.5 -- self.Data.Spread
        zVec = pos[3] + ( math.cos( self.Data.Number * angle ) ) * 1.5 -- self.Data.Spread 
        local gPos = GetSurfaceHeight( xVec, zVec )
        local modpos = {xVec, gPos, zVec}        
        -- Set the new ground target
        self:SetNewTargetGround(modpos)                                
    end,                 
        
    OnImpact = function(self, TargetType, targetEntity)
        if not self:BeenDestroyed() then
            if TargetType == 'Terrain' then 
                local size = RandomFloat(0.5, 1.0)
                Explosion.CreateScorchMarkDecal(self, size, self:GetArmy())
            end	
        end 
        TRocketCannonProjectile.OnImpact( self, TargetType, targetEntity )
    end,
}    
TypeClass = TDRocketCannon01