Search Unity

Flying Script

Discussion in 'Scripting' started by dimensioneater, May 30, 2012.

  1. dimensioneater

    dimensioneater

    Joined:
    May 26, 2012
    Posts:
    9
  2. TiG

    TiG

    Joined:
    Feb 28, 2011
    Posts:
    311
    Yes, its possible to make it. I recommend you to research flight physics and use rigidbodies and forces to translate it to Unity 3D.
     
  3. dimensioneater

    dimensioneater

    Joined:
    May 26, 2012
    Posts:
    9
    can you give me some script to start with?

    thank you for your reply
     
  4. TiG

    TiG

    Joined:
    Feb 28, 2011
    Posts:
    311
    Just search the forums for aircraft script or physics you can find materials to start with
     
  5. tmanallen

    tmanallen

    Joined:
    Nov 8, 2009
    Posts:
    395
    Here is an old vehicle samples script plane portion, it is written in jScript but it should be a great start for you:

    Code (csharp):
    1.  
    2. //Mass
    3. var mass = 1200;
    4.  
    5. //Force of the planes engine
    6. var engineForce = 10000.0;
    7.  
    8. //Toruqe coefficient for elevator (pitch)
    9. var elevator = 0.3;
    10.  
    11. //Base input for elevator (when no key is pressed),
    12. //so plane stays on one height without user input
    13. var elevatorCenterSetting = -0.25;
    14.  
    15. //Toruqe coefficient for ailerons (roll)
    16. var ailerons = 0.3;
    17.  
    18. //additional drag induced by air brake if present
    19. var brakeDrag = 0.0;
    20.  
    21. //drag along x,y and z directions
    22. var drag = Vector3(2.0,8.0,0.05);
    23.  
    24. //stabilizing drag along x,y and z axes, causing plane to face forward
    25. var stabilizingDrag = Vector3(2.0,1.0,0.0);
    26.  
    27. //ground brake and corner handling capabilities
    28. var groundBrakeAccel = 8;
    29. var groundCornerAccel = 6;
    30.  
    31. //child to rotate as propeller if available
    32. var propeller : Transform;
    33.  
    34. private var queryUserInput = true;
    35. private var pitchInput = 0.0;
    36. private var rollInput = 0.0;
    37. private var thrustInput = 0.0;
    38. private var steerVelo : float;
    39. private var wheels;
    40. private var throttle : float;
    41. private var brake : float;
    42. private var rpmPitch = 0.0;
    43. private var grounded = false;
    44. private var propOriginalRotation : Quaternion;
    45. private var propSpin = 0.0;
    46.  
    47. function Start () {
    48.     //Destroy existing rigidbody, we don't want anyone to mess with it.
    49.     if(rigidbody)
    50.         Destroy(rigidbody);
    51.    
    52.     //setup rigidbody  
    53.     gameObject.AddComponent(Rigidbody);
    54.     rigidbody.mass = mass;
    55.     rigidbody.angularDrag = 0.5;
    56.     rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
    57.  
    58.     //start engine noise
    59.     audio.loop = true;
    60.     audio.Play();
    61.  
    62.     wheels = transform.GetComponentsInChildren(WheelCollider);
    63.    
    64.     if(wheels.Length == 0)
    65.         Debug.Log("Add some wheel colliders for ground control");
    66.  
    67.     for(w in wheels)
    68.     {
    69.         //we use our own simple physics for ground control
    70.         w.forwardFriction.stiffness = 0;
    71.         w.sidewaysFriction.stiffness = 0;
    72.     }
    73.    
    74.     if(propeller != null)
    75.         propOriginalRotation=propeller.localRotation;
    76. }
    77.  
    78. //Functions to be used by external scripts
    79. //controlling the plane if required
    80. //===================================================================
    81.  
    82. //return a status string for the vehicle
    83. function GetStatus(gui : GUIText) {
    84.     gui.text="v="+(rigidbody.velocity.magnitude * 3.6).ToString("f1")
    85.         + "km/h \nthrottle="+(throttle*100).ToString("f0")
    86.         +"%\naltitude="+(transform.position.y).ToString("f1")+"m";
    87. }
    88.  
    89. //return an information string for the vehicle
    90. function GetControlString(gui : GUIText) {
    91.     gui.text="Use arrow keys to control the plane,\nA/Z for throttle control,\nspace for brake.";
    92. }
    93.  
    94. //Setup main camera to follow vehicle
    95. function SetupCamera() {
    96.     if(Camera.main.GetComponent(SmoothFollow) != null)
    97.         Camera.main.GetComponent(SmoothFollow).enabled=false;
    98.     Camera.main.transform.localRotation=Quaternion.identity;
    99.     Camera.main.transform.localPosition=Vector3(0,4,-19);
    100.     Camera.main.transform.parent=transform;
    101. }
    102.  
    103. //Enable or disable user controls
    104. function SetEnableUserInput(enableInput)
    105. {
    106.     queryUserInput=enableInput;
    107. }
    108.  
    109. //Plane physics
    110. //======================================================================
    111.  
    112. //Check if plane is on ground
    113. function GroundCheck () {
    114.     grounded=false;
    115.     for( w in wheels )
    116.         if(w.isGrounded)
    117.             grounded = true;
    118. }
    119.  
    120. //very basic physics for moving the plane around on the ground
    121. //uses similar simplified model used for the handling in the car script.
    122. function GroundPhysics () {
    123.     var velo=rigidbody.velocity;
    124.  
    125.     var dir=transform.TransformDirection(Vector3.forward);
    126.     var flatDir=Vector3.Normalize(new Vector3(dir.x,0,dir.z));
    127.     var flatVelo=new Vector3(velo.x,0,velo.z);
    128.     var brakeForce=-flatVelo.normalized*brake*rigidbody.mass*groundBrakeAccel;
    129.  
    130.     flatDir*=flatVelo.magnitude;
    131.     var rev=Vector3.Dot(flatVelo,flatDir)>0?1:-1;
    132.     flatDir*=rev;
    133.     var diff=(flatVelo-flatDir).magnitude;
    134.     var cornerAccel=groundCornerAccel;
    135.     if(cornerAccel>diff)cornerAccel=diff;
    136.     var cornerForce=-(flatVelo-flatDir).normalized*cornerAccel*rigidbody.mass;
    137.     cornerSlip=Mathf.Pow(cornerAccel/groundCornerAccel,3);
    138.    
    139.     rigidbody.AddForce(brakeForce+cornerForce);
    140.    
    141.     var fVelo=velo.magnitude;
    142.     var veloSteer=((15/(2*fVelo+1))+1);
    143.     var maxRotSteer=0.5*Time.fixedDeltaTime*(1-0.8*cornerSlip);
    144.     var veloFactor=fVelo<1.0?fVelo:Mathf.Pow(fVelo,0.1);
    145.     var steerVeloInput=rev*rollInput*veloFactor*0.5*Time.fixedDeltaTime;
    146.     if(fVelo<0.1)
    147.         steerVeloInput=0;
    148.     if(steerVeloInput>steerVelo)
    149.     {
    150.         steerVelo+=0.02*Time.fixedDeltaTime*veloSteer;
    151.         if(steerVeloInput<steerVelo)
    152.             steerVelo=steerVeloInput;
    153.     }
    154.     else
    155.     {
    156.         steerVelo-=0.02*Time.fixedDeltaTime*veloSteer;
    157.         if(steerVeloInput>steerVelo)
    158.             steerVelo=steerVeloInput;
    159.     }
    160.     steerVelo=Mathf.Clamp(steerVelo,-maxRotSteer,maxRotSteer); 
    161.     transform.Rotate(Vector3.up*steerVelo*57.295788);  
    162. }
    163.  
    164. //physics for moving the plane through the air
    165. function AirPhysics () {
    166.  
    167.     //engine force
    168.     rigidbody.AddForce(transform.forward*engineForce*throttle);
    169.    
    170.     //wings and drag
    171.     forwardVelo = Vector3.Dot(rigidbody.velocity,transform.forward);
    172.     sqrVelo = forwardVelo*forwardVelo;
    173.  
    174.     dragDirection = transform.InverseTransformDirection(rigidbody.velocity);
    175.     dragAndBrake = drag+Vector3(0,0,brakeDrag*brake);
    176.     dragForces = -Vector3.Scale(dragDirection,dragAndBrake)*rigidbody.velocity.magnitude;
    177.     rigidbody.AddForce(transform.TransformDirection(dragForces));
    178.  
    179.     //stabilization (to keep the plane facing into the direction it's moving)
    180.     stabilizationForces = -Vector3.Scale(dragDirection,stabilizingDrag)*rigidbody.velocity.magnitude;
    181.     rigidbody.AddForceAtPosition(transform.TransformDirection(stabilizationForces),transform.position-transform.forward*10);
    182.     rigidbody.AddForceAtPosition(-transform.TransformDirection(stabilizationForces),transform.position+transform.forward*10);
    183.        
    184.     //elevator
    185.     rigidbody.AddTorque(transform.right*sqrVelo*elevator*(pitchInput+elevatorCenterSetting));  
    186.  
    187.     //ailerons
    188.     if(!grounded)
    189.         rigidbody.AddTorque(-transform.forward*sqrVelo*ailerons*rollInput);
    190.     //rudder
    191. //  rigidbody.AddTorque(transform.up*sqrVelo*rudder*inputAxes.x);  
    192.  
    193.     //sound
    194.     rpmPitch=Mathf.Lerp(rpmPitch,throttle,Time.deltaTime*0.2);
    195.     audio.pitch=1.0+1.0*rpmPitch;
    196.     audio.volume=0.4+throttle;
    197.    
    198.     //prop
    199.     if(propeller != null)
    200.     {
    201.         propMotion=Mathf.Clamp(Time.deltaTime*rpmPitch*360*50,0,43);
    202.         propSpin = Mathf.Repeat( propSpin+propMotion , 360);
    203.         propeller.localRotation=Quaternion.Euler( 0,0,propSpin)*propOriginalRotation;  
    204.         propeller.renderer.material.SetColor("_BlurColor",Color(1,1,1,rpmPitch));  
    205.     }
    206. }
    207.  
    208. function FixedUpdate () {
    209.     //query input axes if necessarry
    210.     pitchInput = 0.0;
    211.     rollInput = 0.0;
    212.     thrustInput = 0.0;
    213.     if(queryUserInput)
    214.     {
    215.         pitchInput = Input.GetAxis("Vertical");
    216.         rollInput = Input.GetAxis("Horizontal");
    217.         thrustInput = Input.GetAxis("Thrust");
    218.     }
    219.  
    220.     //check if plane is on ground
    221.     GroundCheck();
    222.    
    223.     //update throttle  brake
    224.     throttle=Mathf.Clamp01(throttle + thrustInput * Time.deltaTime * 0.3);
    225.     brake=Input.GetButton("Jump")?1.0:0.0;
    226.    
    227.     //Air Physics
    228.     AirPhysics();
    229.    
    230.     //Ground Physics if on ground
    231.     if(grounded)
    232.         GroundPhysics();
    233. }
    234.  
    235. //Destroy Airplane if crashed into something
    236. function OnCollisionEnter(collision : Collision) {
    237.     //Only crashed when touching something with the wings, wheels should not crash
    238.     if(collision.contacts[0].thisCollider.tag=="DestructiveCollider")
    239.         BroadcastMessage("ApplyDamage",Mathf.Infinity,SendMessageOptions.DontRequireReceiver);
    240. }
    241.  
    242. //Called by DamageReceiver if plane crashed
    243. function Detonate()
    244. {
    245.     //no more flying
    246.     enabled = false;
    247.                
    248.     //destroy wheels
    249.     for( w in wheels )
    250.         w.gameObject.active=false;
    251.                    
    252.     //Mark object no longer a target for homing missiles.
    253.     if(tag=="MissileTarget")
    254.         tag="";
    255.  
    256.     //turn off engine
    257.     audio.volume=0;
    258.     if(propeller != null)
    259.         propeller.renderer.material.SetColor("_BlurColor",Color(1,1,1,0)); 
    260. }
    261.  
    262. @script RequireComponent (AudioSource)
    263.  
    264.  
     

    Attached Files:

  6. dimensioneater

    dimensioneater

    Joined:
    May 26, 2012
    Posts:
    9
  7. noah4477

    noah4477

    Joined:
    Aug 31, 2012
    Posts:
    1
    Not to be digging up an old post ive trying using this on an airplane but I get a lot of errors any help?
     
  8. nockieboy

    nockieboy

    Joined:
    Jul 7, 2012
    Posts:
    48
    Sorry to resurrect this again (it's not that old though!) but I've been trying to use this script in a test scene. Aside from calibrating the thrust and rigidbody weight to match the model's scale, I'm having a big issue with the physics.

    The aircraft is jittering/shuddering immensely. In level flight, the aircraft looks as though it's occupying three different rotations in the y-axis, all within about 15 degrees of 'normal', and the aircraft is oscillating between them faster than I can see.

    I'm sure this is an issue to do with the rigidbody physics and the way the script is applying forces perhaps, but I've tried many different settings, including rigidbody interpolation (all three settings) to see if they are the cause of the problem, but no luck. :?

    I've searched the forums and the only stuff I can find to do with sort of jittering are regarding character controllers.

    Can anyone shed a little light on this please? ;)
     
  9. BSBalazs

    BSBalazs

    Joined:
    Jul 5, 2013
    Posts:
    8
    This is a good script, but I also have problem with the airplane.

    The aircraft is jittering/shuddering immensely.

    Anybody have a solution? or another easy working script?
     
  10. quy17114729

    quy17114729

    Joined:
    May 5, 2016
    Posts:
    3
    Did you complete this script.
    Can you share with me?
     
  11. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    @quy17114729 the respondents in this thread haven't logged into the forum for over a year (if not more)...
     
  12. quy17114729

    quy17114729

    Joined:
    May 5, 2016
    Posts:
    3
    :( Do you have it? Or a script to control an aircarft
     
  13. tmanallen

    tmanallen

    Joined:
    Nov 8, 2009
    Posts:
    395
    Hey everyone, if you are still looking at this thread, and it has been a long time, just let me know so I can try to help..