Hey guys,
some of you might have seen that Robert recently ported over the "FragmentFilters" from Starling to Sparrow. That allows for some very cool effects, one of which I want to show you here!
It's the "SPDisplacementMapFilter". That filter takes a texture and uses it to distort the pixels of a display object. The nice thing about this is that you can even animate that distortion.
Now, let's say you want to create a nifty water reflection like this one:
Water Reflection Demo
That demo is from Starling, of course, but it works just the same with Sparrow. To add such a distortion to an arbitrary display object in your game, just call the following method:
- (void)addDistortionTo:(SPDisplayObject *)target
{
float scale = Sparrow.contentScaleFactor;
NSURL *url = scale == 1.0f ?
[NSURL URLWithString:@"http://i.imgur.com/n95LSGb.jpg"] :
[NSURL URLWithString:@"http://i.imgur.com/QRXLvws.jpg"];
[SPTexture loadFromURL:url generateMipmaps:NO scale:scale
onComplete:^(SPTexture *texture, NSError *outError)
{
float __block offset = 0;
SPDisplacementMapFilter *filter = [[SPDisplacementMapFilter alloc] initWithMapTexture:texture];
filter.componentX = SPColorChannelRed;
filter.componentY = SPColorChannelRed;
filter.scaleX = 40;
filter.scaleY = 5;
target.filter = filter;
[target addEventListenerForType:SPEventTypeEnterFrame block:^(SPEnterFrameEvent *event)
{
if (offset > texture.height / 2.0f) offset -= texture.height / 2.0f;
else offset += event.passedTime * 20.0f;
filter.mapPoint.y = offset - texture.height / 2;
}];
}];
}
I cheat a little, because I download the water-maps from a server (in the Starling version, I can use Flash's Perlin noise generator to do that on demand); so you should probably create those yourself or download them. But the principle should be the same.
I hope you like it! I'm looking forward to what you come up with! =)
[BTW, for reference: the above code is stored in this Gist, where I can update it in the future.]