Reputation: 11
I'am trying to make alpha larger the farther the pixel is from the lightsource.
How can I calculate the distance between my lightsource(u_lightSourcePosition) and the pixel being rendered?
I tried doing this:
float distance_from_point_to_pixel = distance(gl_FragCoord,v_lightSourcePosition)
but it didn't work.
Vertex shader
attribute vec3 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;
varying vec4 v_color;
varying vec2 v_texCoord0;
varying vec2 v_lightSourcePosition;
uniform mat4 u_projTrans;
uniform vec2 u_lightSourcePosition;
void main() {
vec4 position = u_projTrans * vec4(a_position, 1.0);
gl_Position = position;
v_color = a_color;
v_texCoord0 = a_texCoord0;
v_lightSourcePosition = u_lightSourcePosition ;
}
Fragment shader
varying vec4 v_color;
varying vec2 v_texCoord0;
varying vec2 v_lightSourcePosition;
uniform sampler2D u_sampler2D;
void main() {
vec4 color = texture2D(u_sampler2D, v_texCoord0) * v_color;
float lightRadius = 400.0;
float distance_from_point_to_pixel = distance(gl_FragCoord,v_lightSourcePosition);
color.a = distance_from_point_to_pixel / lightRadius;
gl_FragColor = color;
}
Upvotes: 0
Views: 1465
Reputation: 402
You need the world space of the fragment. Pass it from the vertex shader to the pixel shader as another vec3
and you'll probably want to pass in a world/model
matrix to translate a_position
from object space to world space. vec3 pworld = (model * vec4(a_position,1.0)).xyz;
Upvotes: 1