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

MoveTowards doesn't work

Discussion in '2D' started by SuperGodJJ, Aug 19, 2017.

  1. SuperGodJJ

    SuperGodJJ

    Joined:
    Feb 8, 2017
    Posts:
    6
    Here is the code:

    Code (CSharp):
    1. target = new Vector3 (Random.Range (-4.7f, 0), Random.Range (-2.75f, 3.5f), 0);
    2.             // Move to the random position
    3.             transform.position = Vector3.MoveTowards (transform.position,
    4.                 target, speed * Time.deltaTime);
    I want to move my gameobject automatically but it turns out that the gameobject only move a very short distance. I put it in Update() and make a if statement which used to control my gameobject stop until it move to the random position
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    If that code is in Update, then each frame you're finding a new random position, moving a little bit towards it, and then next frame you're getting a new random position, moving a little towards it, etc. You need to pick one random position and store it in a variable, so that "target" is the same every update until transform.position is equal to target, or you otherwise want to stop the movement.