Search code examples
javacolorslibgdxsprite

Change sprite color into white


I'm trying to change the color of a sprite (which is red and gray), in white color.

sprite.setColor(1, 1, 1, 1);

But nothing is happening.

How can I change all the sprite colors in white?


Solution

  • If you want to change the color of all the shapes in the sprite to white then the only way you can do this is to use a pixel shader and set all the fragments that they are not black(i assume black renders as transperant in your game) to white. Something like that:

    varying vec4 v_color;
    varying vec2 v_texCoords;
    uniform sampler2D u_texture;
    void main() {
        vec4 color=v_color * texture2D(u_texture, v_texCoords);
    
        if(color.r!=0 && color.g!=0 && color.b!=0){
            gl_FragColor=vec4(1,1,1,1);
        }
        else{
            gl_FragColor=color;
        }
    }
    

    If you are unfortunate and you use opengl 1.0(fixed pipeline), I suggest you to switch to gles 2.0 now that you are a beginer.Fixed pipeline is from the 90' , we are at 2013!

    The code:

    Initialize:

      ShaderProgram.pedantic = false;
    
      ShaderProgram defaultShader=SpriteBatch.createDefaultShader();
    
      ShaderProgram shaderWhiteTexture=new ShaderProgram(Gdx.files.internal("vertexShader.vs").readString(),Gdx.files.internal("fragShader.fs").readString());
    

    Render:

    //Render the textures with the normal colors 
    spriteBatch.begin();
    spriteBatch.draw(sprite1,sprite2,sprite3...);//or whatever code u use to render them
    spriteBatch.end();
    
    //Render the textures with the shader
    spriteBatch.setShader(shaderWhiteTexture);
    spriteBatch.begin();
    spriteBatch.draw(sprite4,sprite5,sprite6...);//or whatever code u use to render them
    spriteBatch.end();
    spriteBatch.setShader(defaultShader);
    

    Shaders:

    //vertexShader.vs:
    attribute highp vec4 a_position;
    attribute highp vec4 a_color;
    attribute highp vec2 a_texCoord0;
    uniform mat4 u_projTrans;
    
    varying highp vec4 v_color;
    varying highp vec2 v_texCoords;
    
    void main() {
        v_color = a_color;
        v_texCoords = a_texCoord0;
        gl_Position = u_projTrans * a_position ;
    }
    
    //fragShader.fs:
    varying highp vec4 v_color;
    varying highp vec2 v_texCoords;
    uniform sampler2D u_texture;
    void main() {
    
        gl_FragColor = vec4(0.0);
    
        highp vec4 color = texture2D(u_texture, v_texCoords);
    
        if(color.a > 0.0) {
           gl_FragColor = vec4(1.0,0,0,1.0);
    }
    
    }
    

    EDITED BY QUESTION OWNER : Now works with transparent texture

    What have been added ? :

    1 . the highp precision to variables
    2 . the fragmentShader file Main() fonction edited