@name Flight_Quat
@inputs     W A S D Rolly UnRolly Fly Hover
@outputs    Ve:vector TarA:quaternion 
@persist    EE:entity
@trigger 
@model models/hunter/plates/plate1x1.mdl



runOnTick(1)
Speed = 400

if ( S ){ W = -1 }
if ( D ){ A = -1 }
if ( UnRolly ){ Rolly = -1 }

Enabled = owner():keyReload() | Fly | Hover

if ( first() ){
    
    EE = entity()
    TarA = quat( entity() )
    
    EE:setMass(5000)
    
    Ps = EE:getConstraints()
    rangerPersist(1)
    rangerHitWater(0)
    rangerDefaultZero(0)
    rangerFilter(Ps)    
        
}

    
    #Calculate ground distance for hover awesomeness

if (Enabled) {
    
    
    DownRange = rangerOffset(200, EE:pos(), vec(0,0,-1) )
    DNorm = DownRange:hitNormal()
    DPos = DownRange:position()
    
    GDist = EE:pos():distance(DPos)
        
    #Dampen movement    
    EE:applyForce( -EE:vel() * EE:mass() )
    
    if ( GDist < 50 ){ EE:applyForce( vec(0,0,1) * EE:mass() * 20  )  }
    
        
    if (Fly ){ EE:applyForce( EE:forward() * EE:mass() * Speed )  }
    
    PitchMod = W * -1
    RollMod = A * -1 
    YawMod = Rolly
    
    PitchQuat = qRotation( TarA:right(), PitchMod )
    YawQuat = qRotation( TarA:up(), YawMod )
    RollQuat = qRotation( TarA:forward(), RollMod )
    
    TarA = ( PitchQuat * YawQuat*RollQuat) * TarA
        
    CurA = quat(entity() )
    
    
    Ve = entity():toLocal( rotationVector(TarA/CurA) +entity():pos() ) * 150 
        
    EE:applyTorque( (Ve  -12*EE:angVelVector()) * entity():inertia()   )    
    
    #EE:applyAngForce( ang( 50 * W * EE:mass() , 100 * A  * EE:mass() ,  100 * -A * EE:mass() ) )
    
 }  
    



