Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Flying Controller

Discussion in 'Physics' started by Luke E, Dec 23, 2014.

  1. Luke E

    Luke E

    Joined:
    Dec 11, 2014
    Posts:
    15
    How do I prevent my first person controller from flying? It, whenever I play, as soon as I press a button (like the down key), literally begins flying upwards. Help?
     
  2. Nubz

    Nubz

    Joined:
    Sep 22, 2012
    Posts:
    553
    Do you have your constraints set like this?
    This would at least keep you from playing superman LOL sorry I know its probably frustrating I just found it sort of funny.

    but then you wouldnt be able to jump either so idk
     

    Attached Files:

  3. Uberpete

    Uberpete

    Joined:
    Jan 16, 2014
    Posts:
    78
    You may want to modify the scripts...
     
  4. Luke E

    Luke E

    Joined:
    Dec 11, 2014
    Posts:
    15
    That certainly fixed the flying problem but now I just walk through the terrain and gravity doesn't seem to affect me now :mad:
     
  5. PJRM

    PJRM

    Joined:
    Mar 4, 2013
    Posts:
    290
    Luke,
    Post your movement script. That one which you press the button and it start flying.

    Just one question: Did you removed the gravity!?
     
  6. Luke E

    Luke E

    Joined:
    Dec 11, 2014
    Posts:
    15
    I don't believe I've moved the gravity...The Use Gravity box is checked..


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class FirstPersonCharacter : MonoBehaviour
    5. {
    6.     [SerializeField] private float runSpeed = 8f;                                       // The speed at which we want the character to move
    7.     [SerializeField] private float strafeSpeed = 4f;                                    // The speed at which we want the character to be able to strafe
    8.     [SerializeField] private float jumpPower = 5f;                                      // The power behind the characters jump. increase for higher jumps
    9.     #if !MOBILE_INPUT
    10.     [SerializeField] private bool walkByDefault = true;                                    // controls how the walk/run modifier key behaves.
    11.     [SerializeField] private float walkSpeed = 3f;                                      // The speed at which we want the character to move
    12.     #endif
    13.     [SerializeField] private AdvancedSettings advanced = new AdvancedSettings();        // The container for the advanced settings ( done this way so that the advanced setting are exposed under a foldout
    14.     [SerializeField] private bool lockCursor = true;
    15.  
    16.     [System.Serializable]
    17.     public class AdvancedSettings                                                       // The advanced settings
    18.     {
    19.         public float gravityMultiplier = 1f;                                            // Changes the way gravity effect the player ( realistic gravity can look bad for jumping in game )
    20.         public PhysicMaterial zeroFrictionMaterial;                                     // Material used for zero friction simulation
    21.         public PhysicMaterial highFrictionMaterial;                                     // Material used for high friction ( can stop character sliding down slopes )
    22.         public float groundStickyEffect = 5f;                                            // power of 'stick to ground' effect - prevents bumping down slopes.
    23.     }
    24.  
    25.     private CapsuleCollider capsule;                                                    // The capsule collider for the first person character
    26.     private const float jumpRayLength = 0.7f;                                           // The length of the ray used for testing against the ground when jumping
    27.     public bool grounded { get; private set; }
    28.     private Vector2 input;
    29.     private IComparer rayHitComparer;
    30.  
    31.     void Awake ()
    32.     {
    33.         // Set up a reference to the capsule collider.
    34.         capsule = collider as CapsuleCollider;
    35.         grounded = true;
    36.         Screen.lockCursor = lockCursor;
    37.         rayHitComparer = new RayHitComparer();
    38.     }
    39.  
    40.     void OnDisable()
    41.     {
    42.         Screen.lockCursor = false;
    43.     }
    44.  
    45.     void Update()
    46.     {
    47.         if (Input.GetMouseButtonUp(0))
    48.         {
    49.             Screen.lockCursor = lockCursor;
    50.         }
    51.     }
    52.  
    53.  
    54.     public void FixedUpdate ()
    55.     {
    56.         float speed = runSpeed;
    57.  
    58.         // Read input
    59. #if CROSS_PLATFORM_INPUT
    60.         float h = CrossPlatformInput.GetAxis("Horizontal");
    61.         float v = CrossPlatformInput.GetAxis("Vertical");
    62.         bool jump = CrossPlatformInput.GetButton("Jump");
    63. #else
    64.         float h = Input.GetAxis("Horizontal");
    65.         float v = Input.GetAxis("Vertical");
    66.         bool jump = Input.GetButton("Jump");
    67. #endif
    68.  
    69. #if !MOBILE_INPUT
    70.      
    71.         // On standalone builds, walk/run speed is modified by a key press.
    72.         // We select appropriate speed based on whether we're walking by default, and whether the walk/run toggle button is pressed:
    73.         bool walkOrRun =  Input.GetKey(KeyCode.LeftShift);
    74.         speed = walkByDefault ? (walkOrRun ? runSpeed : walkSpeed) : (walkOrRun ? walkSpeed : runSpeed);
    75.      
    76.         // On mobile, it's controlled in analogue fashion by the v input value, and therefore needs no special handling.
    77.      
    78.  
    79. #endif
    80.      
    81.         input = new Vector2( h, v );
    82.  
    83.         // normalize input if it exceeds 1 in combined length:
    84.         if (input.sqrMagnitude > 1) input.Normalize();
    85.      
    86.         // Get a vector which is desired move as a world-relative direction, including speeds
    87.         Vector3 desiredMove = transform.forward * input.y * speed + transform.right * input.x * strafeSpeed;
    88.      
    89.         // preserving current y velocity (for falling, gravity)
    90.         float yv = rigidbody.velocity.y;
    91.      
    92.         // add jump power
    93.         if (grounded && jump) {
    94.             yv += jumpPower;
    95.             grounded = false;
    96.         }
    97.      
    98.         // Set the rigidbody's velocity according to the ground angle and desired move
    99.         rigidbody.velocity = desiredMove + Vector3.up * yv;
    100.      
    101.         // Use low/high friction depending on whether we're moving or not
    102.         if (desiredMove.magnitude > 0 || !grounded)
    103.         {
    104.             collider.material = advanced.zeroFrictionMaterial;
    105.         } else {
    106.             collider.material = advanced.highFrictionMaterial;
    107.         }
    108.  
    109.      
    110.         // Ground Check:
    111.      
    112.         // Create a ray that points down from the centre of the character.
    113.         Ray ray = new Ray(transform.position, -transform.up);
    114.      
    115.         // Raycast slightly further than the capsule (as determined by jumpRayLength)
    116.         RaycastHit[] hits = Physics.RaycastAll(ray, capsule.height * jumpRayLength );
    117.         System.Array.Sort (hits, rayHitComparer);
    118.      
    119.      
    120.         if (grounded || rigidbody.velocity.y < jumpPower * .5f)
    121.         {
    122.             // Default value if nothing is detected:
    123.             grounded = false;
    124.             // Check every collider hit by the ray
    125.             for (int i = 0; i < hits.Length; i++)
    126.             {
    127.                 // Check it's not a trigger
    128.                 if (!hits[i].collider.isTrigger)
    129.                 {
    130.                     // The character is grounded, and we store the ground angle (calculated from the normal)
    131.                     grounded = true;
    132.                  
    133.                     // stick to surface - helps character stick to ground - specially when running down slopes
    134.                     //if (rigidbody.velocity.y <= 0) {
    135.                     rigidbody.position = Vector3.MoveTowards (rigidbody.position, hits[i].point + Vector3.up * capsule.height*.5f, Time.deltaTime * advanced.groundStickyEffect);
    136.                     //}
    137.                     rigidbody.velocity = new Vector3(rigidbody.velocity.x, 0, rigidbody.velocity.z);
    138.                     break;
    139.                 }
    140.             }
    141.         }
    142.      
    143.         Debug.DrawRay(ray.origin, ray.direction * capsule.height * jumpRayLength, grounded ? Color.green : Color.red );
    144.  
    145.  
    146.         // add extra gravity
    147.         rigidbody.AddForce(Physics.gravity * (advanced.gravityMultiplier - 1));
    148.     }
    149.  
    150.  
    151.     //used for comparing distances
    152.     class RayHitComparer: IComparer
    153.     {
    154.         public int Compare(object x, object y)
    155.         {
    156.             return ((RaycastHit)x).distance.CompareTo(((RaycastHit)y).distance);
    157.         }  
    158.     }
    159.  
    160. }