简体   繁体   中英

actionscript 3.0 drag and swap

This is my code for dragging and dropping movie clips into their matching movie clip targets. I would like to make a jigsaw puzzle game where all the pieces are in some place, and when one piece is dragged onto another, they two pieces swap and if the piece matches the target it should lock into place and stay there with this code. Only problem is I don't know how to make the pieces swap locations. Any ideas?? Is this even possible?? Please help...

function pickupObject(event:MouseEvent):void {
    event.target.startDrag(true);
    event.target.parent.addChild(event.target);
    objectoriginalX=event.target.x;
    objectoriginalY=event.target.y;
}

function dropObject(event:MouseEvent):void {
    event.target.stopDrag();
    var matchingTargetName:String="target"+ event.target.name;
    var matchingTarget:DisplayObject=getChildByName(matchingTargetName);
    if(event.target.dropTarget != null && event.target.dropTarget.parent==matchingTarget)   {
        event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
        event.target.removeEventListener(MouseEvent.MOUSE_UP, dropObject);
        event.target.buttonMode=false;
        event.target.x=matchingTarget.x;
        event.target.y=matchingTarget.y;
    }
}
  1. Store drag and drop objects in two different arrays and x and y positions also. Consider 3 drag and drop objects.

     var drag:Array = new Array(drag0, drag1, drag2); var drop:Array = new Array(drag0_target, drag1_target, drag2_target); var points:Array = new Array({x:drag_0.x, y:drag_0.y},...); //this regular expression will return a digit number from given string. var pattern:RegExp = /\\d/; 

note: drop array object names should be start with drag object names. For matching purpose .

  1. Add mouse listeners to the drag array objects.
  2. MouseDownHandler()

    e.target.startDrag();

  3. MouseUpHandler()

     //create a tmp variable for store the current drag object number; tmp = e.target.name.match(pattern); for(i=0;i<drop.length; i++){ //Check whether the hit occurred in the drop clips if(MovieClip(e.target).hitTestObject(this.drop[i])){ //Check whether the object has been dropped in a right place. if(drop[i].name.split("_")[0] == e.target.name){ e.target.x = drop[i].x; e.target.y = drop[i].y; }else{ //else place the drag object into the initial position. e.target.x = points[tmp].x; e.target.y = points[tmp].y; } } } 

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM