as3.0 EventDispatcher 事件派发和碰撞的例子.大家可以研究研究.

package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	/**
	 * @author	SinSoul
	 * @http://www.cnblogs.com/sinsoul
	**/
	public class Main extends Sprite  
	{
		private var ballsArray:Array;
		public function Main():void {
			ballsArray = [];
			var _i:uint = 30;
			while (_i--) {
				var _ball:Dispatch = new Dispatch;
				_ball.x = Math.random () * stage.stageWidth;
				_ball.y = Math.random () * stage.stageHeight;
                                                    //这里就是监听的地方
				addChild (_ball).addEventListener (Dispatch.Dispatch_MOVE,DispatchMove );
				ballsArray .push (_ball);
			}
		}
		private function DispatchMove(e:Event ):void {
			var _ball:Dispatch = e.target as Dispatch;
			var _array:Array = ballsArray .concat ();
			_array.splice (_array.indexOf (_ball), 1);
			for each (var _b:Dispatch in _array) {
				if (Point.distance(new Point(_b.x, _b.y), new Point(_ball.x, _ball.y)) < 20) {
					_ball.color = _b.color = 0xff0000;
					ballsArray.splice (ballsArray.indexOf (_ball), 1);
					ballsArray.splice (ballsArray.indexOf (_b), 1);
					//return;
				}
			}
		}
	}
	
}
package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.ColorTransform;
	
	/**
	 * @author	SinSoul
	 * @http://www.cnblogs.com/sinsoul
	**/
	public class Dispatch extends Sprite  
	{
		public static const Dispatch_MOVE:String = "DispatchMove";
		public function Dispatch():void {
			stage?init(null):addEventListener (Event.ADDED_TO_STAGE, init);
		}		
		private function init(e:Event):void 
		{
			graphics.beginFill(0x00);
			graphics.drawCircle(0, 0, 10);
			buttonMode = true;
			addEventListener (MouseEvent.MOUSE_DOWN, mouseDown);
			//
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
		}
		//自己不能做的事,发出事件,请求有管辖权的对象去做
          //这里是发出事件的地方
		private function mouseMove(e:MouseEvent ):void {
			dispatchEvent (new Event(Dispatch.BALL_MOVE));
		}
		//自己能做的事,自己做
		private function mouseDown(e:MouseEvent ):void {
			startDrag ();
			stage.addEventListener (MouseEvent.MOUSE_MOVE, mouseMove );
			stage.addEventListener (MouseEvent.MOUSE_UP, mouseUp);
		}
		private function mouseUp(e:MouseEvent ):void {
			stopDrag ();
			stage.removeEventListener (MouseEvent.MOUSE_MOVE, mouseMove );
			stage.removeEventListener (MouseEvent.MOUSE_UP, mouseUp);
		}		
		public function set color(_c:uint):void {
			var _ctf:ColorTransform = new ColorTransform;
			_ctf.color = _c;
			transform.colorTransform = _ctf;
			//
			stopHandler();
		}
		private function stopHandler():void {
			mouseUp(null);
			buttonMode = false;
			removeEventListener (MouseEvent.MOUSE_DOWN, mouseDown);
		}
	}
	
}

posted @ 2011-05-09 17:24  sinsoul  阅读(2386)  评论(0编辑  收藏  举报