简体   繁体   中英

libgdx - how to set sprite batch to blend/shade like this?

I currently have a default sprite batch:

    batch = new SpriteBatch();

I have read about using shaders to modify how the batch draws each sprite. In my game, I am try to create a 'nighttime' effect - I want every pixel on screen to be black, except for pixels that are already white. For the white pixels, I want a shade of blue. Obviously I am new to libgdx and openGL - can anyone who is familiar with blending or shaders help me out with this? What should I do to my spritebatch to achieve the effect that I am describing?

Effect which you would like to achieve could be done with something like this.

Vertex Shader

attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec4 v_color;
varying vec2 v_texCoords;

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

Fragment shader

precision mediump float;

varying vec4 v_color;
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform mat4 u_projTrans;

bool equals(float a, float b) {
    return abs(a-b) < 0.0001;
}

bool isWhiteShade(vec4 color) {
    return equals(color.r, color.g) && equals(color.r, color.b);
}

void main() {
    vec4 color = texture2D (u_texture, v_texCoords) * v_color;
    if(isWhiteShade(color)) {
        color *= vec4(0, 0, 1, 1);
    }
    else {
        color *= vec4(0, 0, 0, 1);
    }
    gl_FragColor = color;
}

Add them to assets folder and then pass as arguments while creating instance of ShaderProgram and of course don't forget to apply this shader program to your SpriteBatch.

To be honest it has (almost) nothing common with SpriteBatch - all you have to do with it is just apply created shader

    batch.setShader(ShaderProgram shader)

The shaders topic is very very wide (and to be honest independent of Libgdx) and there is no simple answer to your question without informations of what it should do. Also - to be honest - try at first to read something about shaders and come back on SO when you will have some troubles with this.

You can start right here:

https://github.com/libgdx/libgdx/wiki/Shaders

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM