Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

How do I properly use Mathf.MoveTowards?

Discussion in 'Scripting' started by Voodin, Mar 11, 2019.

  1. Voodin

    Voodin

    Joined:
    Apr 19, 2018
    Posts:
    48
    I want to make a more specific jump than just adding forces so I tried using this:
    Code (CSharp):
    1. public static void Jump(Transform trans,string button,float height)
    2.     {
    3.       //jump goes here
    4.       if(Input.GetButtonDown("Jump"))
    5.       {
    6.         Vector3 movement = new Vector3(0.0f,Mathf.MoveTowards(0.0f, height, 0.1f*Time.deltaTime),0.0f);
    7.         trans.position = movement;
    8.       }
    9.  
    10.     }
    but regardless of what number I use for height my character rises the same height(which is barely off the ground at all) what am I doing wrong

    Edit: it seems changing the maxDelta parameter changes the height of the jump but the jump is still instant. my character instantly goes from the ground(what would be 'current') to 'maxDelta'(which is supposed to be the change)
     
    Last edited: Mar 11, 2019
  2. Rotary-Heart

    Rotary-Heart

    Joined:
    Dec 18, 2012
    Posts:
    814
    For using Mathf.MoveTowards or Vector3.MoveTowards you need to give the current value. So in your case it needs to be
    Mathf.MoveTowards(trans.position.y, height, 0.1 * Time.DeltaTime)
     
  3. Voodin

    Voodin

    Joined:
    Apr 19, 2018
    Posts:
    48
    here's my updated code
    Code (CSharp):
    1.   public static void Jump(Transform trans,string button,float height)
    2.     {
    3.       //jump goes here
    4.       if(Input.GetButtonDown("Jump"))
    5.       {
    6.  
    7.         Vector3 movement = new Vector3(0.0f,Mathf.MoveTowards(trans.position.y, height, 0.5f*Time.smoothDeltaTime),0.0f);
    8.         trans.position += movement;
    9.       }
    10.  
    11.     }
    The jump is still instant, adding trans.position.y has virtually unchanged my output.
     
  4. TimmyTheTerrible

    TimmyTheTerrible

    Joined:
    Feb 18, 2017
    Posts:
    186
    One problem is your calling it from inside a if statement with GetButtonDown, meaning it's only getting called a single time time - when you first pressed the button.
     
    Voodin and SparrowGS like this.
  5. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    This, your calling it one time at one frame, you need to loop over it, be it in update ir a coroutine.

    Why dont you wanna use forces?
     
  6. Voodin

    Voodin

    Joined:
    Apr 19, 2018
    Posts:
    48
    trying to move on to kinematic control because it makes much more sense for the kind of games I want to make