Godot Shader特效:2D描边(outline)效果

来源油管的GDQuest大神的教程《Outline Shader in Godot (tutorial)》

效果图
outline
代码如下
shader_type canvas_item;

uniform float width:hint_range(0.0,30.0);
uniform vec4 outline_color:hint_color;

void fragment(){
    float size = width * 1.0 / float(textureSize(TEXTURE,0).x);
    vec4 sprite_color = texture(TEXTURE,UV);
    float alpha = -8.0 * sprite_color.a;
    alpha += texture(TEXTURE,UV + vec2(0.0,-size)).a;
    alpha += texture(TEXTURE,UV + vec2(size,-size)).a;
    alpha += texture(TEXTURE,UV + vec2(size,0)).a;
    alpha += texture(TEXTURE,UV + vec2(size,size)).a;
    alpha += texture(TEXTURE,UV + vec2(0.0,size)).a;
    alpha += texture(TEXTURE,UV + vec2(-size,size)).a;
    alpha += texture(TEXTURE,UV + vec2(-size,0.0)).a;
    alpha += texture(TEXTURE,UV + vec2(-size,-size)).a;
    vec4 final_color = mix(sprite_color,outline_color,clamp(alpha,0.0,1.0));
    COLOR = vec4(final_color.rgb,clamp(abs(alpha) + sprite_color.a,0.0,1.0));
} 
原理

我们定义的width是以像素为单位的,在texture函数中只能使用UV百分比,因此要把像素宽度换算成整个图片的宽度百分比size

float size = width * 1.0 / float(textureSize(TEXTURE,0).x);

当前区域的上下左右及对角线共八个区域的a值对当前区域的a值求导

float alpha = -8.0 * sprite_color.a;
    alpha += texture(TEXTURE,UV + vec2(0.0,-size)).a;
    alpha += texture(TEXTURE,UV + vec2(size,-size)).a;
    alpha += texture(TEXTURE,UV + vec2(size,0)).a;
    alpha += texture(TEXTURE,UV + vec2(size,size)).a;
    alpha += texture(TEXTURE,UV + vec2(0.0,size)).a;
    alpha += texture(TEXTURE,UV + vec2(-size,size)).a;
    alpha += texture(TEXTURE,UV + vec2(-size,0.0)).a;
    alpha += texture(TEXTURE,UV + vec2(-size,-size)).a;

你可能感兴趣的:(Godot Shader特效:2D描边(outline)效果)