2
votes

I'm trying to understand how to apply shaders in SpriteKit, so I made the following shader that comes from a guide with some adaptations (http://battleofbrothers.com/sirryan/understanding-shaders-in-spritekit):

void main() {
    vec4 val = texture2D(u_texture, v_tex_coord);

    if (val.a == 1.0) {
        gl_FragColor = vec4(1.0,1.0,1.0,1.0);
    } else {
        gl_FragColor = val;
    }
}

The idea of this simple shader is to translate to white every non-transparent pixel of the sprite node.

The shader works with my sprite nodes that have a single texture as their image.

The issue that I'm having is that the shader seems to be ignored when I apply it to a sprite node which comes from a multi-layered SKScene. I've tried to set the shader to every children node of the scene, but it still doesn't appear.

Any suggestions?

1
Sorry, I'm missing some comprehension. What do you mean by "multi-layered SKScene"?Confused
Hi, thank you for your support. I've found the solution to my problem (which I'll post soon). Anyway, by "multi-layered SKScene" I mean that I've created a visual scene editor file (.sks), and I built my sprite inside this scene by adding different nodes for the various body parts, so that it's easy to animate the sprite with some SKActions.gionti

1 Answers

1
votes

I've found a workaround to my problem.

I initially tried to apply the shader to every children node of my sprite as following:

for child in children {
    (child as! SKSpriteNode).shader = myShader
}

The code didn’t work out.

Now I use the following working code, which follows the hierarchy of my children nodes:

(self.childNode(withName: "body") as! SKSpriteNode).shader = myShader
(self.childNode(withName: "body")!.childNode(withName: "arm") as! SKSpriteNode).shader = myShader
// ...