Search code examples
androidopengl-estransparentalpha-transparency

Android Opengl 2.0 Alpha Blending issue - half transparent textures


I have this problem with Apha Blending in my game, when I draw a surface with alpha texture, what is suposed to be invisible is invisible, but parts that are suposed to be visible are half transparent. It depends on the amount of light - the closer it is to light source the better it looks, but in shadows such objects almost dissapear.

I enable Alpha Blending:

GLES20.glEnable(GLES20.GL_BLEND);

then I set the function:

GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);

or

GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);

effect is still the same. I use 48bit png files with alpha channel.

my fragment shader looks like this:

final String fragmentShader =   
"precision mediump float; \n"           
    +"uniform vec3 u_LightPos; \n"      
    +"uniform sampler2D u_Texture; \n"  
    +"varying vec3 v_Position;  \n" 
    +"varying vec4 v_Color;  \n"        
    +"varying vec3 v_Normal; \n"        
    +"varying vec2 v_TexCoordinate; \n" 
    +"void main() \n"                           
    +"{          \n"                              
    +"float distance = length(u_LightPos - v_Position); \n"                  
    +"vec3 lightVector = normalize(u_LightPos - v_Position);    \n"                 
    +"float diffuse = max(dot(v_Normal, lightVector), 0.0); \n"                                                                               
    +"diffuse = diffuse * (" + Float.toString((float)Brightness) +" / (1.0 + (0.08 * distance)));   \n"
    +"diffuse = diffuse;    \n"  
    //+3
    +"gl_FragColor = (v_Color * diffuse * texture2D(u_Texture, v_TexCoordinate));   \n"
    +"} \n";   

and vertex shader:

uniform mat4 u_MVPMatrix;                  
uniform mat4 u_MVMatrix;        
attribute vec4 a_Position;      
attribute vec3 a_Normal;        
attribute vec2 a_TexCoordinate; 
varying vec3 v_Position;    
varying vec4 v_Color;   
varying vec3 v_Normal;  
varying vec2 v_TexCoordinate;             
void main()                                                     
{                                                         
    v_Position = vec3(u_MVMatrix * a_Position);            
    v_Color = a_Color;
    v_TexCoordinate = a_TexCoordinate;                                      
    v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0));
    gl_Position = u_MVPMatrix * a_Position;                               
}      

 Thx for any suggestions:)          

Solution

  • Your fragment shader multiplies all 4 (RGBA) components of the texture color with the diffuse factor. This will make your alpha component trend towards zero whenever the diffuse light disappears, turning your sprites nearly invisible.

    To fix your code change it to something like this:

    gl_FragColor = v_Color * texture2D(u_Texture, v_TexCoordinate);
    gl_FragColor.rgb *= diffuse;