AS 3表示オブジェクトへのドラッグ支援のツールクラス

2687 ワード

public class DragUtil

	{

		private static var _objVec:Vector.<Sprite> = new Vector.<Sprite>();

		private static function addToVec(obj:Sprite):Boolean{

			if(_objVec.indexOf(obj)==-1){

				_objVec.push(obj);

				return true;

			}

			return false;

		}

		private static function removeFromVec(obj:Sprite):void{

			for(var i:int=0; i<_objVec.length; i++){

				var sp:Sprite = _objVec[i];

				if(sp!=null && sp == obj){

					_objVec.splice(i,1);

				}

			}

		}

		public static function enableDrag(obj:Sprite):void{

			if(obj){

				if(!addToVec(obj)){

					return;// Drag 

				}

				if(!obj.hasEventListener(MouseEvent.MOUSE_DOWN)){

					obj.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);

				}

				if(!obj.hasEventListener(MouseEvent.MOUSE_MOVE)){

					obj.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);

				}

				if(!obj.hasEventListener(MouseEvent.MOUSE_UP)){

					obj.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);

				}

				if(!obj.hasEventListener(MouseEvent.MOUSE_OUT)){

					obj.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);

				}

			}

		}

		public static function disableDrag(obj:Sprite):void{

			if(obj){

				removeFromVec(obj);

				if(obj.hasEventListener(MouseEvent.MOUSE_DOWN)){

					obj.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);

				}

				if(obj.hasEventListener(MouseEvent.MOUSE_MOVE)){

					obj.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);

				}

				if(obj.hasEventListener(MouseEvent.MOUSE_UP)){

					obj.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);

				}

				if(obj.hasEventListener(MouseEvent.MOUSE_OUT)){

					obj.removeEventListener(MouseEvent.MOUSE_OUT, onMouseOut);

				}

			}

		}

		private static function onMouseDown(evt:MouseEvent):void {

			var obj:Sprite = evt.target as Sprite;

			if(obj!=null && _objVec.indexOf(obj)!=-1){

				obj.startDrag(false, new Rectangle(0,0, StageProxy.stageWidth()-obj.width, StageProxy.stageHeight()-obj.height));

			}

		}

		

		private static function onMouseMove(evt:MouseEvent):void {

			if(evt.buttonDown == false) {

				var obj:Sprite = evt.target as Sprite;

				if(obj!=null && _objVec.indexOf(obj)!=-1){

					obj.stopDrag();

				}

			}

		}

		

		private static function onMouseUp(evt:MouseEvent):void {

			var obj:Sprite = evt.target as Sprite;

			if(obj!=null && _objVec.indexOf(obj)!=-1){

				obj.stopDrag();

			}

		}

		

		private static function onMouseOut(evt:MouseEvent):void {

			var obj:Sprite = evt.target as Sprite;

			if(obj!=null && _objVec.indexOf(obj)!=-1){

				obj.stopDrag();

			}

		}

	}