Make gorgeous water effects to your sprite textures in Spirte Kit with the new SKShader class available in iOS8 . Here comes the class code for a simple fragment shader like in this video
It’s very simple to add a shader to your game. You just have to implement a new SKShader class, set some properties and assign it to a sprite of your choice.
This is a example how a shader can be setup:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
if (NSClassFromString(@"SKShader") != nil) { SKSpriteNode *shaderContainer_move = [SKSpriteNode spriteNodeWithImageNamed:@"dummypixel.png"]; shaderContainer_move.position = waterPosition; shaderContainer_move.size = waterSize; shaderContainer_move.name = @"waterShaderContainer"; [game addChild:shaderContainer_move]; SKShader* shader_move = [SKShader shaderWithFileNamed:@"shader_water_movement.fsh"]; //Set vairiables that are used in the shader script SKTexture* shaderTexture =[SKTexture textureWithImageNamed:itemId]; shader_move.uniforms = @[ [SKUniform uniformWithName:@"customTexture" texture:shaderTexture], [SKUniform uniformWithName:@"movement" float:1], ]; //add the shader to the sprite shaderContainer_move.shader = shader_move; } |
Just set the shader file and define the variable names that should be available inside the shader script via the uniform property of the SKShader class.
I’ve done it here with the texture that should be the background of the water container.
I also assigned the same shader to the stone sprite in the moment when it contacts with the water as you can see in the video .
The uniform property „movement“ is to vary the shader behaviour a bit.
This is the code inside the shader file „shader_water_movement.fsh“
1 2 3 4 5 6 7 8 9 10 11 12 13 |
void main(void) { vec2 uv = v_tex_coord; uv.y += (sin((uv.y + (u_time * 0.10)) * 85.0) * 0.0025*movement) + (sin((uv.y + (u_time * 0.15+(movement/10.0))) * 18.0) * 0.005); uv.x += (sin((uv.y + (u_time * 0.08)) * 55.0) * 0.0029*movement) + (sin((uv.y + (u_time * 0.2+(movement/10.0))) * 15.0) * 0.005); vec4 texColor = texture2D(customTexture,uv); gl_FragColor = texColor; } |