Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question Velocity Quickly Jumps to rollSpeed at End of Roll, rather than at the start of the ability.

Discussion in 'Scripting' started by TazProductions, Nov 29, 2023.

  1. TazProductions

    TazProductions

    Joined:
    Feb 5, 2020
    Posts:
    2
    In the process of coding a roll ability for my game, I came across an issue where once I press the roll button, the rigidbody speeds up to about half of the rollSpeed I have set. Then once the roll ends, the rigidbody very quickly speeds up to the full rollSpeed, then gradually slowing down back to my runSpeed.

    Any advice on how to sort this out, and make it so that the rigidbody immediately reaches rollSpeed when I press the roll button? My player movement and rolling scripts are below, along with a video showing what I'm experiencing.



    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System.Diagnostics.CodeAnalysis;
    4. using System.Runtime.CompilerServices;
    5. using UnityEngine;
    6.  
    7. public class PlayerMovement : MonoBehaviour
    8. {
    9.     public Transform orientation;
    10.  
    11.     public MovementState state;
    12.  
    13.     public enum MovementState
    14.     {
    15.         running,
    16.         rolling,
    17.         air
    18.     }
    19.  
    20.     public bool rolling;
    21.  
    22.     [Header("Movement")]
    23.     private float moveSpeed;
    24.     public float runSpeed;
    25.     public float rollSpeed;
    26.  
    27.     public float rollSpeedChangeFactor;
    28.     public float maxYSpeed;
    29.  
    30.     public float groundDrag;
    31.  
    32.     [Header("Keybinds")]
    33.     public KeyCode jumpKey;
    34.  
    35.     [Header("Ground Check")]
    36.     public float playerHeight;
    37.     public LayerMask whatIsGround;
    38.     public bool grounded;
    39.  
    40.     [Header("Slope Handling")]
    41.     public float maxSlopeAngle;
    42.     private RaycastHit slopeHit;
    43.     private bool exitingSlope;
    44.  
    45.     [Header("Jumping")]
    46.     public float airMultiplier;
    47.     bool readyToJump;
    48.     public float jumpHeight = 2f;
    49.     public bool isJumping;
    50.     public float gasTime;
    51.     public float gasTimeCounter;
    52.  
    53.     float horizontalInput;
    54.     float verticalInput;
    55.  
    56.     Vector3 moveDirection;
    57.     Rigidbody rb;
    58.  
    59.     private void Start()
    60.     {
    61.         rb = GetComponent<Rigidbody>();
    62.         rb.freezeRotation = true;
    63.         readyToJump = true;
    64.     }
    65.  
    66.     private void Update()
    67.     {
    68.         //ground check
    69.         grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
    70.  
    71.         MyInput();
    72.         StateHandler();
    73.         SpeedControl();
    74.  
    75.         if (state == MovementState.running)
    76.         {
    77.             rb.drag = groundDrag;
    78.         }
    79.         else
    80.             rb.drag = 0;
    81.     }
    82.  
    83.     private void FixedUpdate()
    84.     {
    85.         MovePlayer();
    86.  
    87.         //handle ground drag (sliding on ground)
    88.         if (state == MovementState.running)
    89.             rb.drag = groundDrag;
    90.         else
    91.             rb.drag = 0;
    92.     }
    93.  
    94.     private void MyInput()
    95.     {
    96.         horizontalInput = Input.GetAxisRaw("Horizontal");
    97.         verticalInput = Input.GetAxisRaw("Vertical");
    98.         Jump();
    99.     }
    100.  
    101.     private float desiredMoveSpeed;
    102.     private float lastDesiredMoveSpeed;
    103.     private MovementState lastState;
    104.     private bool keepMomentum;
    105.  
    106.     private void StateHandler()
    107.     {
    108.         //Mode - Rolling
    109.         if (rolling)
    110.         {
    111.             state = MovementState.rolling;
    112.             desiredMoveSpeed = rollSpeed;
    113.             speedChangeFactor = rollSpeedChangeFactor;
    114.         }
    115.  
    116.         //Mode - running
    117.         else if (grounded)
    118.         {
    119.             state = MovementState.running;
    120.             desiredMoveSpeed = runSpeed;
    121.         }
    122.  
    123.         //Mode - Air
    124.         else
    125.         {
    126.             state = MovementState.air;
    127.             desiredMoveSpeed = runSpeed;
    128.         }
    129.  
    130.         bool desiredMoveSpeedHasChanged = desiredMoveSpeed != lastDesiredMoveSpeed;
    131.         if (lastState == MovementState.rolling) keepMomentum = true;
    132.  
    133.         if (desiredMoveSpeedHasChanged)
    134.         {
    135.             if (keepMomentum)
    136.             {
    137.                 StopAllCoroutines();
    138.                 StartCoroutine(SmoothlyLerpMoveSpeed());
    139.             }
    140.             else
    141.             {
    142.                 StopAllCoroutines();
    143.                 moveSpeed = desiredMoveSpeed;
    144.             }
    145.         }
    146.  
    147.         lastDesiredMoveSpeed = desiredMoveSpeed;
    148.         lastState = state;
    149.     }
    150.  
    151.     private float speedChangeFactor;
    152.  
    153.     private IEnumerator SmoothlyLerpMoveSpeed()
    154.     {
    155.         //smoothly Lerp movementSpeed to desired value
    156.         float time = 0;
    157.         float difference = Mathf.Abs(desiredMoveSpeed - moveSpeed);
    158.         float startValue = moveSpeed;
    159.  
    160.         float boostFactor = speedChangeFactor;
    161.  
    162.         while (time < difference)
    163.         {
    164.             moveSpeed = Mathf.Lerp(startValue, desiredMoveSpeed, time / difference);
    165.  
    166.             time += Time.deltaTime * boostFactor;
    167.  
    168.             yield return null;
    169.         }
    170.  
    171.         moveSpeed = desiredMoveSpeed;
    172.         speedChangeFactor = 1f;
    173.         keepMomentum = false;
    174.     }
    175.  
    176.     private void MovePlayer()
    177.     {
    178.         if (state == MovementState.rolling) return;
    179.  
    180.         //calculate movement direction
    181.         moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
    182.  
    183.         //on slope
    184.         if(OnSlope() && !exitingSlope)
    185.         {
    186.             rb.AddForce(GetSlopeMoveDirection() * moveSpeed * 20f, ForceMode.Force);
    187.  
    188.             if (rb.velocity.y > 0)
    189.                 rb.AddForce(Vector3.down * 80f, ForceMode.Force);
    190.         }
    191.  
    192.         //on ground
    193.         else if (grounded)
    194.             rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
    195.  
    196.         //in air
    197.         else if (!grounded)
    198.             rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
    199.  
    200.         //turn gravity off while on slope
    201.         rb.useGravity = !OnSlope();
    202.     }
    203.  
    204.     private void SpeedControl()
    205.     {
    206.         //limiting speed on slope
    207.         if (OnSlope() && !exitingSlope)
    208.         {
    209.             if (rb.velocity.magnitude > moveSpeed)
    210.                 rb.velocity = rb.velocity.normalized * moveSpeed;
    211.         }
    212.  
    213.         //limiting speed on ground or in air
    214.         else
    215.         {
    216.             Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
    217.  
    218.             //limit velocity if needed
    219.             if (flatVel.magnitude > moveSpeed)
    220.             {
    221.                 Vector3 limitedVel = flatVel.normalized * moveSpeed;
    222.                 rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
    223.             }
    224.         }
    225.  
    226.         //Limiting the Y (vertical) Velocity
    227.         if (maxYSpeed != 0 && rb.velocity.y > maxYSpeed)
    228.             rb.velocity = new Vector3(rb.velocity.x, maxYSpeed, rb.velocity.z);
    229.     }
    230.  
    231.     private void Jump()
    232.     {
    233.         //Initialize jump
    234.         if (Input.GetKeyDown(jumpKey) && readyToJump && grounded)
    235.         {
    236.             isJumping = true;
    237.             readyToJump = false;
    238.             exitingSlope = true;
    239.             //Reset Y Velocity
    240.             rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
    241.             gasTimeCounter = gasTime;
    242.  
    243.             rb.velocity = new Vector3(rb.velocity.x, Mathf.Sqrt(jumpHeight * -2f * Physics.gravity.y), rb.velocity.z);
    244.             readyToJump = false;
    245.         }
    246.  
    247.         //Continue jump if held down
    248.         if (Input.GetKey(jumpKey) && isJumping)
    249.         {
    250.             if (gasTimeCounter > 0)
    251.             {
    252.                 rb.velocity = new Vector3(rb.velocity.x, Mathf.Sqrt(jumpHeight * -2f * Physics.gravity.y), rb.velocity.z);
    253.                 gasTimeCounter -= Time.deltaTime;
    254.             }
    255.             else
    256.             {
    257.                 isJumping = false;
    258.                 exitingSlope = false;
    259.                 readyToJump = true;
    260.             }
    261.         }
    262.  
    263.         if (Input.GetKeyUp(jumpKey))
    264.         {
    265.             isJumping = false;
    266.             exitingSlope = false;
    267.             readyToJump = true;
    268.         }
    269.     }
    270.  
    271.     private bool OnSlope()
    272.     {
    273.         if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight * 0.5f + 0.3f))
    274.         {
    275.             float angle = Vector3.Angle(Vector3.up, slopeHit.normal);
    276.             return angle < maxSlopeAngle && angle != 0;
    277.         }
    278.  
    279.         return false;
    280.     }
    281.  
    282.     private Vector3 GetSlopeMoveDirection()
    283.     {
    284.         return Vector3.ProjectOnPlane(moveDirection, slopeHit.normal).normalized;
    285.     }
    286. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class Rolling : MonoBehaviour
    5. {
    6.     [Header("References")]
    7.     public Transform orientation;
    8.     public Transform playerCam;
    9.     private Rigidbody rb;
    10.     private PlayerMovement pm;
    11.     [Header("Rolling")]
    12.     public float rollForce;
    13.     public float rollUpwardForce;
    14.     public float maxRollYSpeed;
    15.     public float rollDuration;
    16.     [Header("Camera Effects")]
    17.     public ThirdPersonCam cam;
    18.     public float rollFov;
    19.     //NEW-ish stuff, could be used for bursting
    20.     [Header("Settings")]
    21.     public bool useCameraForward = true;
    22.     public bool allowAllDirections = true;
    23.     public bool disableGravity = false;
    24.     public bool resetVel = true;
    25.     [Header("Cooldown")]
    26.     public float rollCd;
    27.     private float rollCdTimer;
    28.     [Header("Input")]
    29.     public KeyCode rollKey = KeyCode.Q;
    30.     private void Start()
    31.     {
    32.         rb = GetComponent<Rigidbody>();
    33.         pm = GetComponent<PlayerMovement>();
    34.     }
    35.     private void Update()
    36.     {
    37.         if (Input.GetKeyDown(rollKey))
    38.         {
    39.             Roll();
    40.         }
    41.         if (rollCdTimer > 0)
    42.             rollCdTimer -= Time.deltaTime;
    43.     }
    44.     private void Roll()
    45.     {
    46.         if (rollCdTimer > 0) return;
    47.         else rollCdTimer = rollCd;
    48.         pm.rolling = true;
    49.         pm.maxYSpeed = maxRollYSpeed;
    50.         cam.DoFov(rollFov);
    51.         //NEW Stuff - could be used for bursting (from this line to  "rb.useGravity = false;" line (line 68) with exception of "forceToApply" line (line 65))
    52.         Transform forwardT;
    53.         if (useCameraForward)
    54.             forwardT = playerCam;
    55.         else
    56.             forwardT = orientation;
    57.         Vector3 direction = GetDirection(forwardT);
    58.         Vector3 forceToApply = direction * rollForce + orientation.up * rollUpwardForce; //NEW EQ has direction * rollForce... old EQ has orientation.forward * rollForce...
    59.         if (disableGravity)
    60.             rb.useGravity = false;
    61.         delayedForceToApply = forceToApply;
    62.         Invoke(nameof(DelayedRollForce), 0.025f);
    63.         Invoke(nameof(ResetRoll), rollDuration);
    64.     }
    65.     private Vector3 delayedForceToApply;
    66.     private void DelayedRollForce()
    67.     {
    68.         //NEW Stuff - could be used for bursting
    69.         if (resetVel)
    70.             rb.velocity = Vector3.zero;
    71.         rb.AddForce(delayedForceToApply, ForceMode.Impulse);
    72.     }
    73.     private void ResetRoll()
    74.     {
    75.         pm.rolling = false;
    76.         pm.maxYSpeed = 0;
    77.         cam.DoFov(85f);
    78.         //NEW Stuff - could be used for bursting
    79.         if (disableGravity)
    80.             rb.useGravity = true;
    81.     }
    82.     //NEW Stuff - could be used for bursting
    83.     private Vector3 GetDirection(Transform forwardT)
    84.     {
    85.         float horizontalInput = Input.GetAxisRaw("Horizontal");
    86.         float verticalInput = Input.GetAxisRaw("Vertical");
    87.         Vector3 direction = new Vector3();
    88.         //Allows bursting in any direction depending on what keys you're pressing
    89.         if (allowAllDirections)
    90.             direction = forwardT.forward * verticalInput + forwardT.right * horizontalInput;
    91.         //Only allows bursting in the direction the player is facing (with playerObj chosen) or the camera is facing (with orientation chosen)
    92.         else
    93.             direction = forwardT.forward;
    94.         //Bursts forward if no keys are pressed
    95.         if (verticalInput == 0 && horizontalInput == 0)
    96.             direction = forwardT.forward;
    97.         return direction.normalized;
    98.     }
    99. }
     
    Last edited: Nov 29, 2023
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    39,571
    Sounds like you wrote a bug! That can only mean...


    Time to start debugging!

    By debugging you can find out exactly what your program is doing so you can fix it.

    Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    If you are looking for how to attach an actual debugger to Unity: https://docs.unity3d.com/2021.1/Documentation/Manual/ManagedCodeDebugging.html

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.