Search Unity

Question [Math] Distance from a point to a line in 2D.

Discussion in 'Scripting' started by MikeyJY, Apr 22, 2023.

  1. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    I have 3 points for example:

    Code (CSharp):
    1. Vector2 M = new Vector2(1, 2);
    2. Vector2 B = new Vector2(5, 6);
    3. Vector2 C = new Vector2(3, 4);
    4. //BC - vector:
    5. Vector2 BC  = B - C;
    I want to compute the distance from M to BC. I came up with two methods that I think are too expensive:

    Code (csharp):
    1. float slopeBC = BC.y / BC.x;
    2. float distance = Mathf.abs(slopeBC * M.x - M.y + slopeBC * B.x + B.y)/Mathf.sqrt(1 + slopeBC * slopeBC);
    or

    Code (csharp):
    1. Vector3 MB = M - B;
    2. Vector3 MC = M - C;
    3. float p = (MB.magnitude + MC.magnitude + BC.magnitude)/2
    4. float distance = 2 * Mathf.sqrt(p*(p - MB.magnitude)*(p - MC.magnitude)*(p - BC.magnitude)) / BC.magnitude;
    They seem to work, but they also seem to use heavy-weight calculations.
     
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,107
    Check out this thread of mine for the most optimal 2D intersector I've come across. Read through it and there are also nearest point implementations for lines, rays, and segments.
     
    MelvMay likes this.