I'm trying to take a portion of the current texture and turn it to 50% transparent. I send in four values, signifying the rectangle I want to make transparent. It seems every time, however, that coord.x/coord.y are set to (0, 0), resulting in the entire image being transparent when I send in any rectangle that starts at (0, 0).

I'm still new to GLSL and and probably approaching this wrong. Any pointers on the correct approach would be greatly appreciated!

Values being sent in

sprite.Shader.SetParameter("texture", sprite.Texture);
sprite.Shader.SetParameter("x1", 0);
sprite.Shader.SetParameter("x2", 5);
sprite.Shader.SetParameter("y1", 0);
sprite.Shader.SetParameter("y2", sprite.Height - 1); // sprite.Height = 32


uniform sampler2D texture;

uniform float x1;
uniform float x2;
uniform float y1;
uniform float y2;

void main() {
    vec2 coord = gl_TexCoord[0].xy;

    vec4 pixel_color = texture2D(texture, coord);

    if ((coord.x > x1) && (coord.x < x2) && (coord.y > y1) && (coord.y < y2))
        pixel_color.a -= 0.5;

    gl_FragColor = pixel_color;

1 Answer 1


Texture coordinates are expressed as floating points values between the limits 0 and 1. What you are doing is sending 5 and 32 which get clamped to 1, resulting in the image becoming transparent between 0 and 1, which encompasses the whole thing. What you need to do is divide, either in the shader or outside (preferably outside, on the cpu) by the actual width and height of the texture.

For example, say you have a 32x64 texture, and you want it to be transparent in the rect x1=0, y1=0, x2=5, y2=10. You have to divide x1 and x2 by 32 and y1 and y2 by 64, and then do the comparisons.

Something like this:

sprite.Shader.SetParameter("texture", sprite.Texture);
sprite.Shader.SetParameter("x1", 0/(float)sprite.Width);
sprite.Shader.SetParameter("x2", 5/(float)sprite.Width);
sprite.Shader.SetParameter("y1", 0/(float)sprite.Height);
sprite.Shader.SetParameter("y2", sprite.Height/(float)sprite.Height); // sprite.Height = 32
  • \$\begingroup\$ Thanks so much! I ended up getting it working after a few other small tweaks since I'm using an animated texture. puu.sh/7fUnx.gif (The character becomes transparent behind the wall) \$\endgroup\$
    – BretHudson
    Mar 2, 2014 at 9:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .