calculate distance from line to points code example

Example: distance from point to line

// Get the normal distance from a point P to a line 
// defined by two points L1 and L2:
//
// Formula:

float normalDistanceToLine(vec2 P, vec2 L1, vec2 L2) {
    float dividend = abs((L2.x - L1.x)*(L1.y - P.y) - (L1.x - P.x)*(L2.y - L1.y));
    float divisor = sqrt(pow(L2.x - L1.x, 2) + pow(L2.y - L1.y, 2));
  
    if (divisor != 0.f) {
        return dividend / divisor;
    else		// Points L1 and L2 are the same, choose one
      	return sqrt(pow(P.x - L1.x, 2) + pow(P.y - L1.y, 2));
}
  
// With a distance function (maybe for a glsl shader)
  
float normalDistanceToLine(vec2 P, vec2 L1, vec2 L2) {
  
    float dist = distance(L1, L2);
  
    if (dist != 0.f) {
        return abs((L2.x - L1.x)*(L1.y - P.y) - (L1.x - P.x)*(L2.y - L1.y)) / dist;
    else		// Points L1 and L2 are the same, choose one
      	return distance(P, L1);
}

Tags:

Cpp Example