Search Unity

calculating perpendicular point

Discussion in 'Scripting' started by username85, Jan 13, 2010.

  1. username85

    username85

    Joined:
    Jan 6, 2010
    Posts:
    17
    Hello everyone,

    I am trying to do this mathematically in Unity. Assuming there is a line between two points A and B. There is a third point C, outside this line. I want to deduce the point D in the line AB that when a line is drawn from C to that point D, it will make that new line CD perpendicular to the line AB.

    Therefore: A, B, C are already known, and I want to calculate the position of D within the AB line. For the sake of simplicity the four points can be seen as Vector2. Outlining the required equation to calculate the point D will be enough for me.

    Thank you.
     
  2. username85

    username85

    Joined:
    Jan 6, 2010
    Posts:
    17
    I just solved this problem myself. I doubt laying down the solution for this might be useful to someone in the future, but I know it wont hurt, so here it is

    A = (x1,y1), B = (x2,y2), C = (x3, y3), D = (x4, y4)
    x1, y1, x2, y2, x3, y3 are known, in order to calculate x4 and y4 we do the following

    Code (csharp):
    1. k = ((y2-y1) * (x3-x1) - (x2-x1) * (y3-y1)) / ((y2-y1)^2 + (x2-x1)^2)
    2. x4 = x3 - k * (y2-y1)
    3. y4 = y3 + k * (x2-x1)
     
  3. BLarentis

    BLarentis

    Joined:
    Mar 12, 2012
    Posts:
    3
    Hello,
    Thanks for the post. That was exactly what I was looking for.
     
  4. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    Code (csharp):
    1. Vector3 normAB = AB.normalized;
    2. float magAD = Vector3.dot(normAB, AC);
    3.  
    4. Vector3 D = A + normAB * magAD
     
  5. Kermitt54

    Kermitt54

    Joined:
    Aug 14, 2012
    Posts:
    9
    Not sure if this existed when this thread was created, but Unity has a built-in function that can do this (vector projection) in a single step.

    Vector3 D = Vector3.Project(C, Vector3.Normalize(B - A));


    EDIT:
    On further investigation I found this doesn't work. I'm still pretty sure this function can be used to do the same thing but I appear to be using it wrong. I've implemented alexzzzz's method and it works great.
     
    Last edited: Dec 4, 2012