Search Unity

Vector3.MoveTowards (movement stops)

Discussion in 'Scripting' started by Beauchamp, Dec 20, 2014.

  1. Beauchamp

    Beauchamp

    Joined:
    Aug 11, 2014
    Posts:
    5
    Hey guys,
    I want to move an object from one position to another fluently. Lets say I want to move an object from current coordinates to new position (3, 1, 5) upon pressing up key once (not by holding it). I'm new to C# so I'm sorry for probably stupid and simple question :)

    My script looks like this:

    void Update ()
    {

    if (Input.GetKeyDown("up"))
    {
    transform.position = Vector3.MoveTowards (transform.position, new Vector3 (3, 1, 5), 1f * Time.deltaTime);
    }
    }

    I guess the problem is the transform.position command executes just once (when i press up key), problem is i don't know how to tell unity to keep changing the position after i once press that "up" key until object hits those (3,1,5) coordinates.

    I'll appreciate any help :)

    Ty

    B.
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    You need to throw a boolean flag so it will keep moving.
    Code (csharp):
    1.  
    2. bool isMoving = false;
    3. Vector3 target = new Vector3 (3, 1, 5);
    4. void Update ()
    5. {
    6. if (Input.GetKeyDown("up"))
    7. {isMoving = true;}
    8. if(isMoving){
    9. transform.position = Vector3.MoveTowards (transform.position, target, 1f * Time.deltaTime);
    10. if(transform.position == target) isMoving = false;
    11. }
    12. }
    13.  
     
    Beauchamp likes this.
  3. Beauchamp

    Beauchamp

    Joined:
    Aug 11, 2014
    Posts:
    5
    thx a lot for the reply, i was just about to write that i figured out the same after 2 hours of changing everything all over again :D

    well i have similar thing, just maybe in maybe like 3 times more lines, but it finally works and my dungeon rat is moving as intended :)

    i also find out i should rather use quesions instead, will do it next time.

    TY
     
  4. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    Glad you got it worked out.