Search Unity

Make object move towards another

Discussion in 'Scripting' started by DilemaH, Feb 12, 2016.

  1. DilemaH

    DilemaH

    Joined:
    Feb 12, 2016
    Posts:
    1
    Hello world

    For as long as I can remember, theres always been this 1 snippet of code that I couldn't quite figure out (except maybe once, but I forgot how I got it). Say we want an object to move towards another one with a constant vector (say 20) in 2-dimensional space. How do you do this? We want to find Distance of x,y , and we are given x,y, and the constant vector with which we want to proceed (20 in this case). Even if theres a built in method for this, I would like to know what the formula(s) are for peace of mind
     
  2. Josenifftodd

    Josenifftodd

    Joined:
    Nov 29, 2013
    Posts:
    158
    Code (CSharp):
    1. public GameObject target;
    2.  
    3. transform.position = Vector3.MoveTowards(transform.position, target.position);
    Or you could do this i guess...


    Code (CSharp):
    1. void Update () {
    2.  
    3. this.transform.position += Vector3.left * Time.deltaTime;
    4. this.transform.position += Vector3.right* Time.deltaTime;
    5. this.transform.position += Vector3.up * Time.deltaTime;
    6.  
    7.  
    8. }