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

#Downloaded from sicklebrick.com
#Code snippets based on Techni's quaternion based flight device here:
#http://www.wiremod.com/forum/finished-contraptions/14446-fully-3d-mouse-controlled-flight.html#post138320

runOnTick(1)
Speed = 400

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

if ( owner():keyReload() ){ Hover = 1  }

Enabled = Fly | Hover

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

    
    #Calculate ground distance for hover awesomeness

if (Enabled) {
    
    if ( Hover ){
        DownRange = rangerOffset(250, EE:pos(), EE:up() * -1 )
    }else{
        DownRange = rangerOffset(250, EE:pos(), vec(0,0,-1) )    
    }
    
    
    #Dampen movement    
    EE:applyForce( -EE:vel() * EE:mass() )    
    
    if ( DownRange:hit() ){
        
        DNorm = DownRange:hitNormal()
        DPos = DownRange:position()
    
        GDist = EE:pos():distance(DPos)
        if ( GDist < 50 ){ EE:applyForce( EE:up() * EE:mass() * 20  )  }
            
        if (!Hover ){
             if ( DNorm:x() > 0.9 | DNorm:y() > 0.9 ){ DNorm = vec(0,0,1) }
        }
        
    
    }else{
        
        DNorm = vec(0,0,1)
    
    }
        

    
    
    
        
    if (Fly ){ EE:applyForce( EE:forward() * EE:mass() * Speed )  }
    
    PitchMod = W * -1
    RollMod = A * -1
    YawMod = Rolly
        
    #PitchQuat = qRotation( entity():right(), PitchMod )
    #YawQuat = qRotation( entity():up(), YawMod )    
    #RollQuat = qRotation( entity():forward(), RollMod )
    #QuatCumber = PitchQuat * YawQuat * RollQuat
    
    
    #TarA =  QuatCumber * TarA
    
    Ang = DNorm:cross(entity():forward() ):normalized():cross(DNorm)
    TarA=quat(Ang,DNorm) 
    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() ) )
    
 }  
    



