在SpriteKit中使用着色器绘制圆



我正试图用Swift在SpriteKit中的着色器绘制一个中心圆来填充图像。我使用此链接来了解着色器,我使用的部分如下所示:

vec2 center = vec2(uResolution.x/2., uResolution.y/2.);
float radius = uResolution.x/2.;
vec2 position = gl_FragCoord.xy - center;
if (length(position) > radius) {
    gl_FragColor = vec4(vec3(0.), 1.);
} else {
    gl_FragColor = vec4(vec3(1.), 1.);
}

但我想把它和SpriteKit一起使用,所以我把它改写为:

void main() {
    vec2 center = u_sprite_size / 2.0;
    float radius = center.x;
    vec2 position = v_tex_coord - center;
    if (length(position) > radius) {
        gl_FragColor = vec4(vec3(0.0), 1.0);
    } else {
        gl_FragColor = vec4(vec3(1.0), 1.0);
    }
}

这就是我加载着色器的方式:

let node = SKSpriteNode(imageNamed: "napolean.png")
node.position = CGPoint(x: size.width / 2, y: size.height / 2)
node.shader = SKShader(fileNamed: "circle.fsh")
addChild(node)

当我运行时,映像总是黑色的,gl_FragColor = vec4(vec3(1.0), 1.0);从不运行,控制台中也没有错误。有人能解释一下出了什么问题吗?感谢

更新

Okapi指出,u_tex_cord是归一化的,所以我归一化了中心,然后把它一分为二,如下所示:vec2 center = (u_sprite_size) / length(u_sprite_size) / 2.0;。在我这样做之后,我可以画圆,但它太小了,偏离了中心

由于v_tex_coord是标准化的,您根本不必使用u_sprite_size——纹理坐标将始终在(0,0)–(1,1)范围内,这意味着您的中心和半径始终分别为(0.5、0.5)和0.5。你的着色器代码可以是这样的:

void main() {
    const float radius = 0.5;
    vec2 position = v_tex_coord - vec2(0.5, 0.5);
    if (length(position) > radius) {
        gl_FragColor = vec4(vec3(0.0), 1.0);
    } else {
        gl_FragColor = vec4(vec3(1.0), 1.0);
    }
}

最新更新