Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Moving a Rigidbody2D a set distance over a set time

Discussion in 'Physics' started by austinjamesfox1, Feb 16, 2019.

  1. austinjamesfox1

    austinjamesfox1

    Joined:
    Feb 13, 2019
    Posts:
    1
    I am trying to implement a dash move that will take a definable time to dash the rigidbody/player over a certain distance. I can get the player to dash but am trying to slow down the movement so it isn't basically instantaneous. I thought I would be able to set a smaller 'dashForce' and repeat it with a while loop until the 'dashTime' counter reaches 0 but after what seems like the first dash the player stops and doesn't continue for the entirety of 'dashTime'. I think it has something to do with the fact the FixedUpdate() updates more often then Update() but not quite sure. What am I doing wrong? Or what can I do to fix my code?

    Code (CSharp):
    1. private void DoDash()
    2.     {
    3.         if (canDash && wantToDash) // if canDash and player presses C
    4.         {
    5.             dashTime = startDashTime;
    6.             controller.ZeroVelocity(); //Sets current velocity on player to zero
    7.             controller.UseGravity(false); //Disables Gravity on Rigidbody2D
    8.             while (dashTime > 0)
    9.             {
    10.                 if (facingRight) //Dashes in the direction the player is facing
    11.                 {
    12.                     Debug.Log("Dashing Right!");
    13.                     controller.rb.velocity = Vector2.right * dashForce;
    14.                 }
    15.                 else if (!facingRight)
    16.                 {
    17.                     Debug.Log("Dashing Left!");
    18.                     controller.rb.velocity = Vector2.left * dashForce;
    19.                 }
    20.                 dashTime -= Time.fixedDeltaTime;
    21.             }
    22.             controller.UseGravity(true); //Enables Gravity after dash ends
    23.             dashCD = maxDashCD; //Resets the dash cooldown
    24.         }
    25.     }
    26.  
    27. void FixedUpdate()
    28.     {
    29.         DoDash();
    30.     }