Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Mathf.MoveTowards Popping Instead of Moving Smoothly. Why?

Discussion in 'Scripting' started by AdamCNorton, Aug 29, 2014.

  1. AdamCNorton

    AdamCNorton

    Joined:
    Apr 16, 2013
    Posts:
    57
    My understanding is that Mathf.MoveTowards would smoothly move my character from current location to target location based on the speed that I enter. However, in this case, he's instantly popping to the new location. Can anyone tell me why this code would cause the instant pop over me seeing it move over time?

    I appreciate any help.

    Code (CSharp):
    1. void MoveToPosition()
    2.     {
    3.         playerLoco.move = playerLoco.stopped;
    4.  
    5.         while(player.transform.position.x != hideTarget.transform.position.x)
    6.         {
    7.             player.transform.position = new Vector2(Mathf.MoveTowards(player.transform.position.x, hideTarget.transform.position.x, 10.0f * Time.deltaTime), hideTarget.transform.position.y);
    8.  
    9.             if(player.transform.position.x >= hideTarget.transform.position.x - hideOffset || player.transform.position.x <= hideTarget.transform.position.x + hideOffset)
    10.             {
    11.                 if(hideTarget.tag == "HideLeft")
    12.                 {
    13.                     Flip();
    14.                     break;
    15.                 }
    16.                 else
    17.                 {
    18.                     break;
    19.                 }
    20.             }
    21.         }
    22.     }
     
  2. bloeys

    bloeys

    Joined:
    Aug 26, 2014
    Posts:
    57
    Well I believe it's because you placed it in a while loop, this will loop until the condition is no longer true in ONE frame, this will cause the 'teleporting'. Try removing the while loop and call it every frame, like in an update function.

    Hope that helps.
     
  3. AdamCNorton

    AdamCNorton

    Joined:
    Apr 16, 2013
    Posts:
    57
    That was exactly it. Thank you!