title: Unity mid air movement with velocitychange
body: <p>I have made a script for player movement in a 3D game in Unity.
  I like how the movement works, but when I jump while moving, the player keeps moving in that direction at the same speed till it falls to the ground, which is the expected behavior for this script.
  But I want to be able to move the player in the air slightly (not fully controllable.)
  I'm imagining kinda like a minecraft like movement to be exact.</p>
  
  <p>Any advice to improve this code would be greatly apprecciated.</p>
  
  <p>This is my code.</p>
  
  <pre><code>
  using System.IO;
  using UnityEngine;
  
  public class VelocityMovement : MonoBehaviour
  {
  
      #region Variables
  
      public float speed;
      public float gravity;
      public float maxVelocityChange;
      public float jumpHeight;
      public float raycastDistance;
      public Rigidbody rb;
  
      #endregion
  
      private void Awake()
      {
          //gets rigidbody, freezes rotation of the rigidbody, disables unity's built in gravity system on rigidbody.
          rb = GetComponent&lt;Rigidbody&gt;();
          rb.freezeRotation = true;
          rb.useGravity = false;
      }
  
      private void Update()
      {
          //Jump system 
          if(Grounded())
          {
              if (Input.GetKeyDown(KeyCode.Space))
              {
                  rb.velocity = new Vector3(rb.velocity.x, CalculateJumpSpeed(), rb.velocity.z);
              }
          }
      }
  
      private void FixedUpdate()
      {
  
          //Moves the player when on the ground.
          if (Grounded())
          {
              //Calculate how fast the player should be moving.
              Vector3 targetVelocity = new Vector3(playerInputs.hAxis, 0, playerInputs.vAxis); 
              targetVelocity = transform.TransformDirection(targetVelocity);
              targetVelocity *= speed ;
  
              //Calculate what the velocity change should be
              Vector3 velocity = rb.velocity;
              Vector3 velocityChange = (targetVelocity - velocity);
              velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
              velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
              velocityChange.y = 0f;
  
              //applies a force equal to the needed velocity change
              rb.AddForce(velocityChange, ForceMode.VelocityChange);
  
          }
  
          //Adds gravity to the rigidbody
          rb.AddForce(new Vector3(0, -gravity * rb.mass, 0));
      }
  
      //Checks if player is on the ground
      private bool Grounded()
      {
          return Physics.Raycast(transform.position, Vector3.down, raycastDistance);
      }
  
      //calculates how high the player should be jumping
      private float CalculateJumpSpeed()
      {
          return Mathf.Sqrt(2 * jumpHeight * gravity);
      }
  }
  
  </code></pre>