Search Unity

Question Reduce movment control when in air whislt carrying momentum.

Discussion in 'Scripting' started by DontBeSnide, Feb 5, 2021.

  1. DontBeSnide

    DontBeSnide

    Joined:
    Feb 5, 2021
    Posts:
    3
    Currently, the code below will allow me to jump with no player contol whilst in the air. However, this will carry my momentum whilst in the air.

    Code (CSharp):
    1.    
    2.         if (isGrounded)
    3.         {
    4.             float x = Input.GetAxisRaw("Horizontal") * moveSpeed;
    5.             float y = Input.GetAxisRaw("Vertical") * moveSpeed;
    6.  
    7.             if (Input.GetKeyDown(KeyCode.Space) && totalJumpsLeft != 0)
    8.             {
    9.                 rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
    10.                 totalJumpsLeft = totalJumpsLeft - 1;
    11.             }
    12.             else if (isGrounded && totalJumpsLeft == 0)
    13.             {
    14.                 totalJumpsLeft = totalJumps;
    15.             }
    16.  
    17.             Vector3 move = (transform.right * x + transform.forward * y).normalized * moveSpeed;
    18.  
    19.             rb.velocity = new Vector3(move.x, rb.velocity.y, move.z);
    20.         }
    21.  
    When I check if the player is not grounded and allow them to move with a slower movement speed in air they will not carry their initial momentum and move to the airspeed I set. Also, with this way if a player was to jump and let go of their control they would stop dead in place and fall to the ground.

    What im trying to get is if a player was to jump forwards and try to move backwards, their speed would slowly decrease until they were to hit the ground. Same goes for if they jumped backwards, they would carry momentum if they were to let go of their controls or decrease their speed if they were to move forwards.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,674
    Your code above directly sets speeds based on input

    Instead, you need to do ONE of the following:

    - gradually adjust speed from existing speed to the newly inputted speed, perhaps using different rates of gradual change

    OR

    - convert to using forces when in the air, versus direct control when in the ground.

    Most likely you will simply need two separate ways of converting input to velocity to accommodate the beahvior you want. You would select these two ways based on being on the ground or not.
     
    DontBeSnide likes this.