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

Move in the direction of another object not linear

Discussion in 'Scripting' started by opeca, Oct 28, 2013.

  1. opeca

    opeca

    Joined:
    Sep 17, 2013
    Posts:
    19
    Hello All,

    I'm quite new in Unity.

    I have two gameobjects. I would like to solve, that the GameObject A face and move in the direction of GamObject B.

    If I simply use this code:

    Code (csharp):
    1. var start = object_A.transform.position;
    2. var end = object_B.transform.position;
    3.  
    4. object_A.transform.Translate((end - start) * 0.1f * Time.deltaTime);
    ...it's working pretty well, the gameobject A started to move straight in the direction of B.

    But if I would like to rotate, to facing A to B, the movement's path will be not a stright line, but a curve.

    Code (csharp):
    1. Quaternion rotationLookAt = Quaternion.LookRotation(end - start);
    2. object_A.transform.rotation = Quaternion.Slerp(object_A.transform.rotation, rotationLookAt, Time.deltaTime * 5f);
    $problem.jpg

    How can I solve, that even if I rotate A to facing B, the movement doesn't be a curve but a straight line?

    Thank you
     
    Last edited: Oct 28, 2013
  2. opeca

    opeca

    Joined:
    Sep 17, 2013
    Posts:
    19
    Using
    Code (csharp):
    1. object_A.transform.position += (end - start) * 0.1f * Time.deltaTime;
    instead of Translate solved my problem.
     
    ofir2471 likes this.