Wednesday, January 19, 2011

Creation of realistic Flash water ripples with AS3

Creation of realistic Flash water ripples with AS3:

This is basically the Flash porting of the Flex experiment made by David Lenaerts in his blog.

I found the script a very interesting way to use the NascomASLib, an open source AS3 library that provides a couple of interesting graphic effects such as pixelate and rippler, the one used in the example. The point is the original source code was written for Flex, and reading through the comments it wasn’t easy to change the embedded image with one used in the library. Some comments even say to use the Flash timeline.

That’s why I provided a quick AS3 solution to achieve this effect with no headache.

This is the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package {
 import flash.display.Bitmap;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 import flash.display.BitmapData;
 import flash.utils.Timer;
 import flash.events.TimerEvent;
 public class Ripple extends Sprite {
  private var myRippler:Rippler;
  var rippleTarget:Bitmap;
  public function Ripple() {
   var rippleBitmap:BitmapData=new BitmapData(640,480,false,0);
   var ripplePicture:toRipple=new toRipple();
   var timer:Timer=new Timer(100);
   timer.start();
   rippleBitmap.draw(ripplePicture);
   rippleTarget=new Bitmap(rippleBitmap);
   addChild(rippleTarget);
   myRippler=new Rippler(rippleTarget,20,5,5);
   stage.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMoveTriggered);
   timer.addEventListener(TimerEvent.TIMER, onTimerTriggered);
  }
  private function onMouseMoveTriggered(e:MouseEvent):void {
   myRippler.drawRipple(rippleTarget.mouseX,rippleTarget.mouseY,20,1);
  }
  private function onTimerTriggered(e:TimerEvent):void {
   var posX:Number=Math.random()*640;
   var posY:Number=Math.random()*480;
   myRippler.drawRipple(posX,posY,15,5);
  }
 }
}

The core lies in line 9 which calls the Rippler class that I modified to work as a standalone class (you will find it in the downloadable source code at the end of the post), then at line 13 that constructs a toRipple object, that is the MovieClip Symbol with the background image [...]

No comments:

Post a Comment