Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How can I activate player controller only at air

Discussion in 'Getting Started' started by Lupinder, Jun 19, 2020.

  1. Lupinder

    Lupinder

    Joined:
    Oct 6, 2018
    Posts:
    85
    I want to move left or right when ı press a and d but ı just wanna do that only when my character is not on ground. When character on ground, ı want to my character don't move side areas. Forward(w) and backward(s) walking stil gonna be active but left and right movement wont work when character grounded. How can ı do that ? Thanks for help...

    Code (CSharp):
    1.  
    2.  
    3.         Animator animator;
    4.  
    5.         void Awake()
    6.         {
    7.  
    8.             animator = GetComponent<Animator>();
    9.         }
    10.  
    11.  
    12.         [Header("Movement")]
    13.         public float movementSpeed;
    14.         public float Accelaration;
    15.         public float airMovementSpeed;
    16.         public float maxSpeed;
    17.        
    18.         [Header("Friction")]
    19.         public float friction;
    20.         public float airFriction;
    21.  
    22.         [Header("Rotation")]
    23.         public float rotationSensitivity;
    24.         public float rotationBounds;
    25.  
    26.         [Header("Gravity")]
    27.         public float extraGravity;
    28.  
    29.         [Header("Ground Detection")]
    30.         public LayerMask whatIsGround;
    31.         public float checkYOffset;
    32.         public float checkRadius;
    33.         public float groundTimer;
    34.  
    35.         [Header("Jumping")]
    36.         public float jumpForce;
    37.         public float jumpCooldown;
    38.  
    39.         [Header("Data")]
    40.         public Camera playerCamera;
    41.         public Transform playerCameraHolder;
    42.         public Rigidbody playerRigidBody;
    43.  
    44.         private InputObject _forwardsInput;
    45.         private InputObject _backwardsInput;
    46.         private InputObject _leftInput;
    47.         private InputObject _rightInput;
    48.         private InputObject _jumpInput;
    49.         private InputObject _runInput;
    50.  
    51.         private float _xRotation;
    52.         private float _yRotation;
    53.         private float _grounded;
    54.         private bool _realGrounded;
    55.         private float _jumpCooldown;
    56.        
    57.         private void Start() {
    58.             _forwardsInput = new InputObject("Forwards", Key.W);
    59.             _backwardsInput = new InputObject("Backwards", Key.S);
    60.  
    61.  
    62.             _runInput = new InputObject("run", Key.LeftShift  );
    63.  
    64.             _leftInput = new InputObject("Left", Key.A);
    65.             _rightInput = new InputObject("Right", Key.D);
    66.             _jumpInput = new InputObject("Jump", Key.Q);
    67.         }
    68.  
    69.         private void FixedUpdate() {
    70.             GroundCheck();
    71.             ApplyMovement();
    72.             ApplyFriction();
    73.             ApplyGravity();
    74.             RunMovement();
    75.         }
    76.  
    77.         private void Update() {
    78.             Rotation();
    79.             Jumping();
    80.         }
    81.  
    82.         private void GroundCheck() {
    83.             _grounded -= Time.fixedDeltaTime;
    84.             var colliderList = new Collider[100];
    85.             var size = Physics.OverlapSphereNonAlloc(transform.position + new Vector3(0, checkYOffset, 0), checkRadius, colliderList, whatIsGround);
    86.             _realGrounded = size > 0;
    87.             if (_realGrounded)
    88.                 _grounded = groundTimer;
    89.            
    90.              
    91.            
    92.         }
    93.  
    94.         private void ApplyMovement() {
    95.             var axis = new Vector2(
    96.                 (_leftInput.IsPressed ? -1 : 0) + (_rightInput.IsPressed ? 1 : 0),
    97.              
    98.  
    99.  
    100.                 (_backwardsInput.IsPressed ? -1 : 0) + (_forwardsInput.IsPressed ? 1 : 0)
    101.             ).normalized;
    102.  
    103.  
    104.  
    105.  
    106.  
    107.             var speed = _realGrounded ? movementSpeed : airMovementSpeed;
    108.          
    109.             var vertical = axis.y * speed * Time.fixedDeltaTime * transform.forward;
    110.  
    111.          
    112.             var horizontal = axis.x * speed * Time.fixedDeltaTime * transform.right;
    113.  
    114.             if (CanApplyForce(vertical, axis))
    115.                 playerRigidBody.velocity += vertical;
    116.            
    117.             if (CanApplyForce(horizontal, axis))
    118.                 playerRigidBody.velocity += horizontal;
    119.         }
    120.  
    121.         private void RunMovement()
    122.         {
    123.             var axis = new Vector2(
    124.                 (_leftInput.IsPressed ? -1 : 0) + (_rightInput.IsPressed ? 1 : 0),
    125.  
    126.  
    127.  
    128.                 (_backwardsInput.IsPressed ? -1 : 0) + (_runInput.IsPressed ? 2 : 0)
    129.             ).normalized;
    130.  
    131.            
    132.  
    133.  
    134.  
    135.  
    136.  
    137.  
    138.             var speed = _realGrounded ? Accelaration : airMovementSpeed;
    139.          
    140.  
    141.  
    142.             var vertical = axis.y * speed * Time.fixedDeltaTime * transform.forward;
    143.  
    144.            
    145.  
    146.  
    147.                 var horizontal = axis.x * speed * Time.fixedDeltaTime * transform.right;
    148.  
    149.          
    150.  
    151.             if (CanApplyForce(vertical, axis))
    152.                 playerRigidBody.velocity += vertical;
    153.  
    154.          
    155.  
    156.             if (CanApplyForce(horizontal, axis))
    157.                 playerRigidBody.velocity += horizontal;
    158.          
    159.         }
    160.  
    161.         private void ApplyFriction() {
    162.             var vel = playerRigidBody.velocity;
    163.             var target = _realGrounded ? friction : airFriction;
    164.             vel.x = Mathf.Lerp(vel.x, 0f, target * Time.fixedDeltaTime);
    165.             vel.z = Mathf.Lerp(vel.z, 0f, target * Time.fixedDeltaTime);
    166.             playerRigidBody.velocity = vel;
    167.         }
    168.        
    169.         private void Rotation() {
    170.             Cursor.lockState = CursorLockMode.Locked;
    171.             var mouseDelta = Mouse.current.delta.ReadValue();
    172.            
    173.             _xRotation -= mouseDelta.y * rotationSensitivity;
    174.             _xRotation = Mathf.Clamp(_xRotation, -rotationBounds, rotationBounds);
    175.             _yRotation += mouseDelta.x * rotationSensitivity;
    176.            
    177.             transform.rotation = Quaternion.Euler(0, _yRotation, 0);
    178.             playerCameraHolder.localRotation = Quaternion.Euler(_xRotation, 0, 0);
    179.         }
    180.  
    181.         private void ApplyGravity() {
    182.             var vel = playerRigidBody.velocity;
    183.             vel.y -= Mathf.Abs(vel.y) * Time.fixedDeltaTime * extraGravity;
    184.             playerRigidBody.velocity = vel;
    185.         }
    186.  
    187.         private void Jumping() {
    188.             _jumpCooldown -= Time.deltaTime;
    189.             if (!(_grounded >= 0) || !(_jumpCooldown <= 0) || !_jumpInput.IsDown) return;
    190.             var vel = playerRigidBody.velocity;
    191.             vel.y = jumpForce;
    192.             playerRigidBody.velocity = vel;
    193.             _jumpCooldown = jumpCooldown;
    194.         }
    195.        
    196.         private bool CanApplyForce(Vector3 target, Vector2 axis) {
    197.             var targetC = Get2DVec(target).normalized;
    198.             var velocityC = Get2DVec(playerRigidBody.velocity).normalized;
    199.             var dotProduct = Vector2.Dot(velocityC, targetC);
    200.             return dotProduct <= 0 || dotProduct * Get2DVec(playerRigidBody.velocity).magnitude < maxSpeed * GetAxisForce(axis);
    201.         }
    202.  
    203.         private static float GetAxisForce(Vector2 axis) {
    204.             return (int)axis.x != 0 ? Mathf.Abs(axis.x) : Mathf.Abs(axis.y);
    205.         }
    206.  
    207.         private static Vector2 Get2DVec(Vector3 vec) {
    208.             return new Vector2(vec.x, vec.z);
    209.         }
    210.     }
    211. }
    212.