问题
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?
回答1:
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);
来源:https://stackoverflow.com/questions/24099103/libgdx-changing-sprite-color-while-hurt