I've been trying to create a drag and drop style app and have run into a snag. I have a group of movieclips that will be dragged in an array. When I drag them I want them to either,
A) Snap back to original position if there isn't a target when dropped (Working)
B) Snap to target if there is one detected (Not Working)
And if possible this would be nice but isn't necessary right now.
C) Switch positions with target if the target is another drag-able movie clip
I have all of the drag-able movie clips in one array and all of the "target" movie clips in another array. When I drop a MC onto a target it only works if I have specified that target in the code,
(dragBox[0])
or if the target is the last in the array. Here is the code I have currently.
var startX:Number = 0;
var startY:Number = 0;
var dropBoxes:Array = [/*list of dropBoxes*/];
var dragBoxes:Array = [/*list of dragBoxes*/];
for each (var dragBox_mc:MovieClip in dragBoxes){
dragBox_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickIt);
dragBox_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
}
function pickIt(evt:MouseEvent):void {
var objTarget = evt.target;
objTarget.parent.addChild(objTarget);
objTarget.startDrag();
startX = objTarget.x;
startY = objTarget.y;
}
function dropIt(evt:MouseEvent):void {
var objTarget = evt.target;
var target = evt.target.dropTarget;
if (target != null && target.parent == (dropBoxes[0])){
trace ("Dropped")
objTarget.x = (dropBoxes[0]).x;
objTarget.y = (dropBoxes[0]).y;
}else{
trace ("Returned")
objTarget.x = startX;
objTarget.y = startY;
}
objTarget.stopDrag();
}
So basically how do I get it to recognize all of the movieclips in the array at once instead of just one at a time?
Thanks
With the help of Kodiak I got this working exactly as I wanted so thanks a lot to him! Here is what I ended up with in case anyone else needs it.
function dropIt(evt:MouseEvent):void {
var objTarget = evt.target;
var target = evt.target.dropTarget;
// Drop dragBox onto dropBox
if (target != null && dropBoxes.indexOf(target.parent) != -1){
trace ("Dropped")
objTarget.x = target.parent.x;
objTarget.y = target.parent.y;
// Switch dragBox with another dragBox
}else if (target != null && dragBoxes.indexOf(target.parent) != -1){
trace ("Switched")
objTarget.x = target.parent.x
objTarget.y = target.parent.y
target.parent.x = startX
target.parent.y = startY
// If no target return to original position
}else{
trace ("Returned")
objTarget.x = startX;
objTarget.y = startY;
}
objTarget.stopDrag();
}