closest point to infinite line

37 Views Asked by At

I have a mask shader which reveals the texture depending on an angle. It uses this logic:

float line_val(vec2 coord) {
    float radians = (direction-90.0)/180.0 * M_PI;
    return coord.x * cos(radians) + coord.y * sin(radians);
}

vec2 corners[4];

void main(void)
{
    corners[0] = vec2(0.0, 0.0);
    corners[1] = vec2(1.0, 0.0);
    corners[2] = vec2(1.0, 1.0);
    corners[3] = vec2(0.0, 1.0);

    float minD = 0.0;
    float maxD = 0.0; // for corner #0
    for (int i=1; i<4; i++) {
        float val = line_val(corners[i]);
        minD = min(minD, val);
        maxD = max(maxD, val);
    }

    float middle = (maxD - minD) * mask_level + minD;

    float dist = line_val(coord);
    if( dist < middle ){
      // show texture
    }else{
      // show nothing
    }
}

Now I wonder, what if instead of showing nothing I would like to show the color on the mask edge (the closest to the current coordinate). How do I get the closest point to the current coordinates giving that my line doesn't have a start and end but it's drawn based on an angle (direction)?