在SpriteKit中使用着色器绘制圆 [英] Drawing a circle with a shader in SpriteKit

查看:77
本文介绍了在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_coord是规范化的,所以我标准化了中心,然后将其一分为二,如下所示: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);
    }
}

这篇关于在SpriteKit中使用着色器绘制圆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆