简体   繁体   中英

libgdx changing sprite color while hurt

I am using libgdx to make a little platformer and I would like to make the enemies blink in red while the player hurt them with his weapon.

I already tried to change the sprite color and the sprite batch color with no success, it only melt the new color with the one of the texture.

sprite.setColor(Color.RED);
spriteBatch.draw(sprite);

the effect I want to achieve is:

在此输入图像描述

going from sprite texture to full red and then back again. I think there is something to do with the Blending function, but I am not sure about that. I want to avoid making some red sprite for each monsters of my game. Does someone know how to achieve this effect?

You can create a shader like this to change the color of all pixels instead of multiplying them by that color. Use this shader with SpriteBatch by calling spriteBatch.setShader(shader); .

This is basically the default SpriteBatch shader, except the final color replaces all non-alpha pixels.

To use this method, you must batch your colored sprites separately from your normal sprites. Call spriteBatch.setShader(null); to go back to drawing regular sprites.

String vertexShader = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" //
            + "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" //
            + "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" //
            + "uniform mat4 u_projTrans;\n" //
            + "varying vec4 v_color;\n" //
            + "varying vec2 v_texCoords;\n" //
            + "\n" //
            + "void main()\n" //
            + "{\n" //
            + "   v_color = " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" //
            + "   v_texCoords = " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" //
            + "   gl_Position =  u_projTrans * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" //
            + "}\n";
        String fragmentShader = "#ifdef GL_ES\n" //
            + "#define LOWP lowp\n" //
            + "precision mediump float;\n" //
            + "#else\n" //
            + "#define LOWP \n" //
            + "#endif\n" //
            + "varying LOWP vec4 v_color;\n" //
            + "varying vec2 v_texCoords;\n" //
            + "uniform sampler2D u_texture;\n" //
            + "void main()\n"//
            + "{\n" //
            + "  gl_FragColor = v_color * texture2D(u_texture, v_texCoords).a;\n" //
            + "}";

        ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShader);

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