利用TweenNano的onUpdate实现多对象同步动画

最近做几个小东西,有了点心得,就是做多对象动画,需要动作一致的时候,如果分开实现,可能会导致多个对象的动画不能同步,并且会多次计算动画帧,于是就想到在onUpdate回调函数里做手脚。原理就是仅对一个对象做动画,传入onUpdate回调,在此回调函数中将动作同步到其它对象上。前提就是动画使用了greensock的TweenNano或TweenLite等。简单的动画我一般使用TweenNano。

下面是一个示例:

源码如下:

package  
{
	import com.greensock.TweenNano;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	
	/**
	 * ...
	 * @author Shirne http://www.shirne.com/
	 */
	public class AnimateOne extends Sprite 
	{
		
		private var s1:Sprite;
		private var s2:Sprite;
		private var s3:Sprite;
		
		private var btn:Sprite;
		
		private var t:TweenNano;
		
		
		public function AnimateOne() 
		{
			if (stage) {
				init();
			}else {
				this.addEventListener(Event.ADDED_TO_STAGE, init);
			}
		}
		
		public function init(e:Event = null):void {
			if (e) {
				this.removeEventListener(Event.ADDED_TO_STAGE, init);
			}
			//生成元素
			s1 = new Sprite();
			s2 = new Sprite();
			s3 = new Sprite();
			
			s1.graphics.beginFill(0xff0000, .6);
			s1.graphics.drawCircle(10, 10, 10);
			s1.graphics.endFill();
			s1.x = 10;
			s1.y = 10;
			addChild(s1);
			s2.graphics.beginFill(0x00ff00, .6);
			s2.graphics.drawCircle(10, 10, 10);
			s2.graphics.endFill();
			s2.x = 40;
			s2.y = 40;
			addChild(s2);
			s3.graphics.beginFill(0x0000ff, .6);
			s3.graphics.drawCircle(10, 10, 10);
			s3.graphics.endFill();
			s3.x = 70;
			s3.y = 70;
			addChild(s3);
			
			
			btn = new Sprite();
			btn.graphics.beginFill(0xffff00, .8);
			btn.graphics.drawRect(0, 0, 80, 30);
			btn.graphics.endFill();
			var txt:TextField = new TextField();
			txt.autoSize = TextFieldAutoSize.LEFT;
			txt.defaultTextFormat = new TextFormat("微软雅黑", 14, 0x333333);
			txt.text = "点击测试";
			txt.x = (btn.width - txt.width) * .5;
			txt.y = (btn.height - txt.height) * .5;
			btn.addChild(txt);
			btn.buttonMode = true;
			btn.mouseChildren = false;
			//绑定动画事件
			btn.addEventListener(MouseEvent.CLICK, autoTest);
			btn.x = (stage.stageWidth - btn.width) * .5;
			btn.y = stage.stageHeight - btn.height - 20;
			addChild(btn);
		}
		
		
		public function autoTest(e:MouseEvent):void {
			var targetx:Number = stage.stageWidth - s1.width - 70;
			if (s1.x > 10) {
				targetx = 10;
			}
			var b1:Number = s1.x;
			var b2:Number = s2.x;
			var b3:Number = s3.x;
			if (t) {
				t.kill();
			}
			t = TweenNano.to(s1, .5, { x:targetx, onUpdate:function():void {
				//同步第二个和第三个对象
				var d:Number = s1.x - b1;
				s2.x = b2 + d;
				s3.x = b3 + d;
			}});
		}
		
	}

}