简体   繁体   中英

SFML/C++ Flashing hit effect on sf::Sprite

as I've searched for a solution, I've only realized the way sfml handles setColor on sf::Sprite objects. It's just multiplication of current RGB values of each pixel in the sprite.

This way it's impossible to make a "White" flashing hit effect on a sprite. By flashing hit effect I mean this: When you hit an enemy, it will turn pure white for a second then this effect fades away quickly until the sprite is it's original form.

how can I make this white flashing hit effect on SFML? (Maybe using shaders?)

thanks

Seems like the best solution is to write your own shader for this. I've solved the problem this way. Here is the code:

tint.frag

uniform sampler2D texture;

uniform vec4 flashColor;

void main()
{


vec4 pixel_color = texture2D(texture, gl_TexCoord[0].xy);
float percent = flashColor.a;

vec4 colorDifference = vec4(0,0,0,1);

colorDifference.r = flashColor.r - pixel_color.r;
colorDifference.g = flashColor.g - pixel_color.g;
colorDifference.b = flashColor.b - pixel_color.b;
pixel_color.r = pixel_color.r + colorDifference.r * percent;
pixel_color.g = pixel_color.g +colorDifference.g * percent;
pixel_color.b =pixel_color.b + colorDifference.b * percent;


gl_FragColor = pixel_color; 

}

to use tint.frag file(it's a shader file) you should send flashColor value to sf::Shader object this way:

.cpp code

flashColor.a = 1.0;//1.0 for 100% effect to 0.0 for 0% effect
shader.loadFromFile("shader/tint.frag", sf::Shader::Fragment);//use your own 
//file path
shader.setUniform("flashColor", sf::Glsl::Vec4(1, 0, 0, 1));//from left to 
//right: red,green,blue,alpha. Alpha is useless in this shader file.
//max is 1, not 255.
window.draw(yoursprite, &shader);

by chaning flashColor.a, you can change the tinting effect. 0 is the original color, 1 is fully coloring the texture with the color you want.

I don't think there is an out of the box solution for this.

However, you could try to create yours by having a white sprite of the size of the ennemy you want to make the animation on and that is following it. During the game, you set the transparency of the white sprite to 0 to make it invisible (with the setColor as you mentioned), and when the ennemy is hit, set the transparency value at 255. You can then decrease it over time to make the "fade away" effect.

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