I need to calculate projection of point on specific line segment in shader (OpenGL ES 2).
Here is how I test the algorithm:
I draw simple triangle with points A(0, 0.5), B(1, -0.5), C(-1, -0.5).
I calculate projection of every point on line segment AC.
I draw points with a projection in the middle of a line segment AC in blue. And the remaining points in green.
I expect to get a green triangle with a blue line perpendicular to the side AC. But blue line is not perpendicular to AC.
I check projection formula in code with drawing on canvas and got expected result.
What's my mistake?
Vertex shader:
uniform mat4 matrix;
attribute vec4 position;
varying vec4 vPosition;
void main()
{
vPosition = matrix * position;
gl_Position = matrix * position;
}
Fragment shader:
precision mediump float;
varying vec4 vPosition;
void main()
{
vec2 P = vPosition.xy;
vec2 A = vec2(0.0, 0.5);
vec2 B = vec2(-1.0, -0.5);
vec2 AP = P - A;
vec2 AB = B - A;
vec2 projection = A + dot(AP, AB) / dot(AB, AB) * AB;
if(projection.x > -0.51 && projection.x < -0.49 && projection.y > -0.01 && projection.y < 0.01) {
gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);
} else {
gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
}
}