SimpleDragAndDrop

by t2421
シンプルなドラッグアンドドロップです。黒い矩形をドラッグして、赤い枠にあてはめることができる。
黒い矩形が赤い枠以外のところでドロップされたらもとの位置に戻る。
♥0 | Line 55 | Modified 2011-03-23 20:45:02 | MIT License
play

ActionScript3 source code

/**
 * Copyright t2421 ( http://wonderfl.net/user/t2421 )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/jFkP
 */

package {
    import flash.events.MouseEvent;
    import flash.display.Sprite;
    import flash.display.DisplayObject;
    public class SimpleDragAndDrop extends Sprite {
        private var area:MyRect;
        private var ddObj:MyRect;
        private var currentDrag:MyRect;
        public function SimpleDragAndDrop() {
            // write as3 code here..
            area = new MyRect(100,50,0xff0000);
            area.x = stage.stageWidth/2;
            area.y = stage.stageHeight/2;
            ddObj = new MyRect();
            ddObj.tempX = ddObj.x;
            ddObj.tempY = ddObj.y;
            addChild(ddObj);
            addChild(area);
            startDD();
        }
        
        private function startDD():void{
            ddObj.addEventListener(MouseEvent.MOUSE_DOWN,downHandler);    
            addChild(ddObj);
            
        }
        
        private function downHandler(e:MouseEvent):void{
            MyRect(e.target).startDrag();
            currentDrag = MyRect(e.target);
            stage.addEventListener(MouseEvent.MOUSE_UP,upHandler);
        }
        
        private function upHandler(e:MouseEvent):void{
            currentDrag.stopDrag();
            stage.removeEventListener(MouseEvent.MOUSE_UP,upHandler);
            checkHit(currentDrag,area);
        }
        
        private function checkHit(obj:DisplayObject,area:DisplayObject):void{
            if(obj.hitTestObject(area)){
                currentDrag.x = area.x;
                currentDrag.y = area.y;
            }else{
                currentDrag.x = currentDrag.tempX;
                currentDrag.y = currentDrag.tempY;
            }
        }

    }
}
import flash.display.Sprite;

class MyRect extends Sprite
{
    public var tempX:Number;
    public var tempY:Number;
    public function MyRect(_width:Number=100,_height:Number=50,_color:uint=0x000000){
        this.graphics.beginFill(_color);
        this.graphics.drawRect(0,0,_width,_height);
        this.graphics.endFill();
    }

}

Forked