0
votes

I want to render many sprites, and I want to tint each sprite in a color (for a rainbow effect) using a shader. (Sprite texture is initially in grayscale)

First I did it with a uniform, where I passed a color, which I calculated outside the shader. That worked fine, but it was too slow.

Then I found out that it is too slow because I was setting that uniform many times per frame. I found the following:

https://gamedev.stackexchange.com/questions/83145/set-color-by-uniform-per-sprite-using-libgdx-spritebatch

[...] Tinting a sprite in OpenGL can easily be done by defining the vertex colors. Since the vertices in this case are defined by SpriteBatch.draw(), you should set the tint with SpriteBatch.setColor(). [...]

And I tried to do so:

in render():

        batch.setShader(shader);
        batch.setColor(.5f, .3f, 1, 1);
        sprite.draw(batch);
        batch.setColor(1, 1, 1, 1);
        batch.setShader(null);

vertex shader:

void main() {
 v_color = a_color;
 v_texCoords = a_texCoord0;
 gl_Position = u_projTrans * a_position;
 }

fragment shader:

void main() {
    v_color = a_color*gl_Color*2.0;
    gl_FragColor = v_color * texture2D(u_texture, v_texCoords);
}

Ok, I am not that familiar with GLSL shaders, and that is maybe why now it does not draw anything. I guess I am missing something and I cannot figure out what.

How can I tint a sprite in a color? So that it works fast?

1
You don't need a custom shader for that, the default SpriteBatch shader already supports tinting.Xoppa

1 Answers

1
votes

There's a big difference between the Sprite class and TextureRegion class. Sprites store their own vertex data, so you color them by calling setColor on the Sprite instead of the SpriteBatch. Sprites ignore whatever color is set on the Batch. Textures and TextureRegions, on the other hand, use the latest color that has been set on the Batch.

Also, you can't use vertex attribute variables in the fragment shader. You already copied a_color to v_color in your vertex shader, so you use v_color in your fragment shader. I have no idea what you're trying to do with gl_Color there.