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

Calculate a point - Closed Solved

Discussion in 'Scripting' started by XukeLho, Jul 3, 2015.

  1. XukeLho

    XukeLho

    Joined:
    Dec 30, 2014
    Posts:
    199
    Hi guys.
    I have this problem where I have to calculate a vector3 point somewhere along a line.


    Take a look at the attached image, in order to help me explain the problem.
    A and B are vector 3 variables that I have, dist is the distance between A and C (the distance along the X axis).

    And now I must calculate the vector 3 coordinates for C (actually, its just the Y coordinate).


    Any ideias?
     

    Attached Files:

  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Use Vector3.Lerp.

    --Eric
     
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    You use similar triangles for this.

    Here's how I think of it: calculate the fraction "t" which is how far you are from A to B. Since you have the distance along the X-axis, this is just t = dist / (B.x - A.x).

    Then you can find Y simply as C.y = A.y + t * (B.y - A.y).

    Or you can let Unity find the whole point at once as Vector3.Lerp(A, B, t). Under the hood, Lerp is simply doing math like the line above.
     
    XukeLho likes this.
  4. XukeLho

    XukeLho

    Joined:
    Dec 30, 2014
    Posts:
    199
    Oh god it worked like a charm thanks alot! I've been at it the entire day!

    I knew it had something to do with Lerp but I just could'nt find what was missing.

    I was missing the 't' calculation.

    Thanks alot.
     
  5. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    I'm glad I was able to help.