remove drag and drop objects when exit frame on button click - actionscript-3

i want to make flash application that allowed users to match picture with the box containing its first letter of the word. the method is drag and drop with target. i'm really new to this.
drag and drop target is working so far but my problem is when i exit the frame after moving the object, the drag and drop object still visible.
how can i remove this object when leaving frame?
here is what i got:
import flash.events.MouseEvent;
import flash.display.DisplayObject;
var objectoriginalX:Number;
var objectoriginalY:Number;
a.buttonMode = true;
a.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
a.addEventListener(MouseEvent.MOUSE_UP, dropObject);
function pickupObject(event:MouseEvent):void
{
event.target.startDrag();
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;
}
else
{
event.target.x = objectoriginalX;
event.target.y = objectoriginalY;
}
}
thanks before, any suggestion will be appreciated
edited: this is the code i use to move to other scene
HOME1.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_15);
function fl_ClickToGoToScene_15(event:MouseEvent):void
{
MovieClip(this.root).gotoAndStop(2, "Scene 1");
}

When through code you do something to a timeline object that causes the parentage to change, that timeline object will no longer be controlled by the timeline.
So when you do this:
event.target.parent.addChild(event.target);
(presumably to bring the item being dragged to the front), you are inadvertently telling Flash that this object is controlled by code now.
The solution, is to manually remove the object(s) by code when done with them. This can be done with removeChild(childObject).
Since you are likely dealing with multiple objects that can be dragged around, it would likely be easiest to just clear all children manually prior to going to the next frame:
removeChildren(); //remove all children of the current context (timeline)
nextFrame(); //go to the next frame, or play(); or whatever you want to do
If you are targeting an older version of flash (less than 11 doesn't support the removeChildren method), you can do this in it's place:
var i:int = numChildren;
while(i--){
removeChildAt(i);
}
Alternatively, if you don't desire to clear all children of the current timeline, you could just keep track of what's being dragged around and remove those object:
var draggedObjs:Array = [];
function pickupObject(event:MouseEvent):void
{
draggedObjs.push(event.target);
...rest of code
Then do this when ready to move on:
for each(obj in draggedObjs){
removeChild(obj);
}
draggedObjs = [];
nextFrame(); //or whatever
Another option, would be to duplicate the item clicked, add it to stage, then drag the duplicate and match the originals position to it on mouse move. When the drag is done, remove the duplicate from stage.

Related

Flash AS3 - Drag and drop multiple objects to multiple targets

I have multiple objects to drag to multiple targets.
I have a code without error.
I am using multiple functions. But I wonder if I pass the objects and the specific target with one function like dropIt since I have more objects and duplicated functions.
This picture is what I want to implement.
and the code is as follows.
Thanks in advance.
var obj1:Array = [obj_1, obj_10];
var obj2:Array = [obj_2, obj_20];
for each(var redsMC:MovieClip in reds)
{
obj1MC.buttonMode = true;
obj1MC.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
obj1MC.addEventListener(MouseEvent.MOUSE_UP, dropIt);
obj1MC.startX = obj1MC.x;
obj1MC.startY = obj1MC.y;
}
for each(var orangesMC:MovieClip in oranges)
{
obj2MC.buttonMode = true;
obj2MC.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
obj2MC.addEventListener(MouseEvent.MOUSE_UP, dropIt1);
obj2MC.startX = obj2MC.x;
obj2MC.startY = obj2MC.y;
}
function pickUp(event:MouseEvent):void
{
event.target.startDrag(true);
event.target.parent.addChild(event.target);
}
function dropIt(event:MouseEvent):void
{
event.target.stopDrag();
if(event.target.hitTestObject(target1)){
event.target.buttonMode = false;
event.target.x = target1.x;
event.target.y = target1.y;
}else if(event.target.hitTestObject(target10)){
event.target.buttonMode = false;
event.target.x = target10.x;
event.target.y = target10.y;
}
else
{
event.target.x = event.target.startX;
event.target.y = event.target.startY;
event.target.buttonMode = true;
}
}
function dropIt1(event:MouseEvent):void
{
event.target.stopDrag();
if(event.target.hitTestObject(target2)){
event.target.buttonMode = false;
event.target.x = target2.x;
event.target.y = target2.y;
}else if(event.target.hitTestObject(target20)){
event.target.buttonMode = false;
event.target.x = target20.x;
event.target.y = target20.y;
}
else
{
event.target.x = event.target.startX;
event.target.y = event.target.startY;
event.target.buttonMode = true;
}
}
You should somehow make your draggable objects know their targets, thus when your SWF registers an end drag event, the object that was being dragged would check against its target and if not colliding, then float/jump back. Since your objects derive from MovieClips, it's possible to add custom properties to them without doing any declarations, but be sure to check if there is something in a custom property before using it. Let's say you have assigned each draggable object a desiredTarget as whatever target you need them to be dragged. Then, you can do like this:
function dropIt(e:MouseEvent):void {
var desiredTarget:MovieClip=e.target.desiredTarget as MovieClip; // get where this should be placed
e.target.stopDrag(); // we still need to release the dragged object
if (!desiredTarget) return; // no target - nothing to do (also helps with debug)
if (e.target.hitTestObject(desiredTarget)) {
e.target.buttonMode=false;
e.target.x=desiredTarget.x;
e.target.y=desiredTarget.y;
} else {
// move dragged object back to starting position
e.target.x=e.target.startX;
e.target.y=e.target.startY;
}
}
Despite the fact Vesper's answer is already accepted, I think it to be far too brief and insufficient, on top of that it doesn't actually answer how to design a system where any number of objects could be dropped to any number of targets, without substantial changes to the code.
// Unlike the Object class, that allows String keys only
// the Dictionary class allows you to store and
// access data by the object instance.
var theValids:Dictionary = new Dictionary;
// We'll store the original (x,y) coordinates here.
var theOrigin:Point = new Point;
// The Sprite class is the superclass of MovieClip, furthermore,
// the startDrag method defined for Sprite class, so unless you
// create your own dragging code, you are bound to use Sprites,
// while you cannot drag SimpleButtons and TextFields this way.
// We'll store the current dragged object here.
var theObject:Sprite;
// This first argument is the object you want to be draggable.
// The "...targets:Array" means you can call this method with
// any number of arguments, the first one is mandatory, the
// rest will be passed in a form of Array (empty Array if you
// call this method with a single argument).
function setupDraggable(source:Sprite, ...targets:Array):void
{
// Make the object draggable.
source.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
source.mouseChildren = false;
source.mouseEnabled = true;
source.buttonMode = true;
// Keep the list of the object's targets so it can be
// retrieved later by the key of the object itself.
theValids[source] = targets;
}
// Ok, let's setup the objects and link them to their designated
// targets. The whole point of the rest of the code is to make
// this one part as simple as it possible: you just edit
// these lines to tell which one objects go where.
// This object can be dropped to a single target.
setupDraggable(obj_1 , target1);
// These objects can go to two targets each.
setupDraggable(obj_10, target1, target10);
setupDraggable(obj_2 , target2, target20);
// This one object can be dropped to any of targets.
setupDraggable(obj_20, target1, target10, target2, target20);
// The MOUSE_DOWN event handler.
function onDown(e:MouseEvent):void
{
// Get the reference to the object under the mouse.
theObject = e.currentTarget as Sprite;
// Keep the object's initial position.
theOrigin.x = theObject.x;
theOrigin.y = theObject.y;
// Put the dragged object on top of anything else.
// We are operating in the parent context of all these
// objects here so there's no need to address anObj.parent.
setChildIndex(theObject, numChildren - 1);
// Start dragging.
theObject.startDrag(true);
// Listen to the MOUSE_UP event, which could happen offstage
// and out of the dragged object, so the only reliable
// way is to listen it from the Stage. That's why we
// are keeping theObject reference as an additional
// variable, without relying on event's data.
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
// The MOUSE_UP event handler.
function onUp(e:MouseEvent):void
{
// Unsubscribe the MOUSE_UP event handler.
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
// Stop the dragging process.
theObject.stopDrag();
// Let's assume there could be more than a single collision.
// We need to figure the one target that is closest.
var theTarget:DisplayObject;
var theDistance:int = 100000;
// Store the dragged object position so we can
// measure distances to the valid collisions, if any.
var thePlace:Point = theObject.localToGlobal(new Point);
// Now, the magic. Lets browse through the
// valid targets and see if there's a collision.
for each (var aTarget:DisplayObject in theValids[theObject])
{
if (theObject.hitTestObject(aTarget))
{
// Let's see if the current collision is closer
// to the dragged object, than the previous one
// (if any, that's what initial 100000 for).
var aPlace:Point = aTarget.localToGlobal(new Point);
var aDistance:int = Point.distance(aPlace, thePlace);
if (aDistance < theDistance)
{
theTarget = aTarget;
theDistance = aDistance;
}
}
}
// If there's at least one collision,
// this variable will not be empty.
if (theTarget)
{
// Make the object non-interactive.
theObject.removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
theObject.mouseEnabled = false;
theObject.buttonMode = false;
// Glue the dragged object to the center of the target.
theObject.x = theTarget.x;
theObject.y = theTarget.y;
}
else
{
// If we're here, that means there was no valid collisions,
// lets return the object to its designated place.
theObject.x = theOrigin.x;
theObject.y = theOrigin.y;
}
// Clean-up. Remove the reference, the object is no longer
// being dragged, so you won't need to keep it.
theObject = null;
}
P.S. I didn't test it, but I think I put enough comments to explain the whole idea.

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;
}
}
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.
Add mouse listeners to the drag array objects.
MouseDownHandler()
e.target.startDrag();
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.

Actionscript 3 drag and drop on multiple specific targes and change alpa for the dropped objects as well as stack targets

I have been trying to achieve three things in the project without success. I am new at this and have relied on tutorials to get this far. Here we go!!
a. I want to be able to drop label_3 and label_4 on either or targetlabel_3 and targetlabel_4 but not effect the other labels and targets.
b. I want to be able to drop label_2 on top of label_1 once it has been dropped. I am finding that when label_1 has been dropped, it hides the targetlabel_2 and label_2 can't find it's target.
c. I want to change the Alpa of each of labels _1, _2, _3, _4 and _5 to zero when they are dropped on their targets and change the Apha for labels _11, _21, _31, _41 and _51 to 100. (I have changed the Apha to 25 on these for the sake of making it easier for someone to see what I am trying to do).
I have been mucking around for days on this and have hit a brick wall.
Can anyone help please?
import flash.display.DisplayObject;
import flash.geom.Rectangle;
/* Drag and Drop
Makes the specified symbol instance moveable with drag and drop.
*/
var startX:Number;
var startY:Number;
var counter = 0;
var attempts = 0;
var rect:Rectangle;
rect=new Rectangle(100,100,700,500);
correct_txt.text=counter;
attempts_txt.text=attempts;
label_1.addEventListener(MouseEvent.MOUSE_DOWN,Drag);
label_1.addEventListener(MouseEvent.MOUSE_UP,Drop);
label_2.addEventListener(MouseEvent.MOUSE_DOWN,Drag);
label_2.addEventListener(MouseEvent.MOUSE_UP,Drop);
label_3.addEventListener(MouseEvent.MOUSE_DOWN,Drag);
label_3.addEventListener(MouseEvent.MOUSE_UP,Drop);
label_4.addEventListener(MouseEvent.MOUSE_DOWN,Drag);
label_4.addEventListener(MouseEvent.MOUSE_UP,Drop);
label_5.addEventListener(MouseEvent.MOUSE_DOWN,Drag);
label_5.addEventListener(MouseEvent.MOUSE_UP,Drop);
label_1.buttonMode = true;
label_2.buttonMode = true;
label_3.buttonMode = true;
label_4.buttonMode = true;
label_5.buttonMode = true;
function Drag(event:MouseEvent):void
{
event.target.startDrag(true,rect);
feedback_txt.text="";
event.target.parent.addChild(event.target);
startX=event.target.x;
startY=event.target.y;
}
function Drop(event:MouseEvent):void
{
event.target.stopDrag();
var myTargetName:String="target" + event.target.name;
var myTarget:DisplayObject=getChildByName(myTargetName);
if (event.target.dropTarget!=null&&event.target.dropTarget.parent==myTarget){
feedback_txt.text="Well done! You have selcted the correct label and placed it in the recommended position on the package.";
feedback_txt.textColor = 0xCC0000
event.target.removeEventListener(MouseEvent.MOUSE_UP,Drop);
event.target.removeEventListener(MouseEvent.MOUSE_DOWN,Drag);
event.target.buttonMode = false;
event.target.x=myTarget.x;
event.target.y=myTarget.y;
counter++;
correct_txt.text=counter;
correct_txt.textColor = 0x0000ff
attempts++;
attempts_txt.text=attempts;
attempts_txt.textColor = 0x0000ff
}else{
feedback_txt.text="Your attempt is not quite correct. You have either selected the incorrect label or placed it in the wrong position. Please try again.";
event.target.x = startX;
event.target.y = startY;
attempts++;
attempts_txt.text = attempts;
}
if (counter==5){
feedback_txt.text="Well done! You have correctly placed all 5 labels";
percentage_txt.text ="Based on your attempts, you have scored "+Math.round ((counter/attempts) *100)+" %";
percentage_txt.textColor = 0x0000ff
}
}
The easiest way to detect when a label is on another label is by using hittest in an enter frame event listener.
stage.addEventListener(Event.ENTER_FRAME, hit_test);
function hit_test(e:Event):void{
if (label_1.hitTestObject(targetLabel_1)) {
trace("Label_1 is hitting targetlabel_1");
label_hit();
}
if (label_2.hitTestObject(targetLabel_2)) {
trace("Label_2 is hitting targetlabel_2");
label_hit();
}
}
When the hittest is activated, the trace text is shown and the function is called. To change the alphas of the labels, use the function being called by the hittest. For example:
function label_hit()
{
label_1.alpha = 0;
label_2.alpha = 0;
label_3.alpha = 0;
}
If you are trying to have conditions to when things can be dragged, seen, or hit tested, that function is also where you can take care of them. For example, If you don't want a label to be visible until the hittest, you have the alpha set to 0 until the function sets it to 100. If you don't want a label to be drageable until then, you create the listener inside the function instead of earlier.
function label_hit()
{
label_1.alpha = 100;
label_1.addEventListener(MouseEvent.MOUSE_DOWN,Drag);
label_1.addEventListener(MouseEvent.MOUSE_UP,Drop);
}
If you want hittests to occur only after other hittests have already occured, place them in conditions and have the conditions met in the functions.
stage.addEventListener(Event.ENTER_FRAME, hit_test);
function hit_test(e:Event):void{
if (label_1.hitTestObject(targetLabel_1)) {
trace("Label_1 is hitting targetlabel_1");
label_hit();
}
if(condition)
{
if (label_2.hitTestObject(targetLabel_2)) {
trace("Label_2 is hitting targetlabel_2");
label_hit();
}
}
function label_hit()
{
var condition = true;
}

Creating a vector array of movie clips AS3

I have several movie clips on the stage of my main .fla named btn1-btn7 which will act as buttons. I have a class file named Functions.as where an event listener is created when a button is clicked. onButtonClicked is just going to a frame on the timeline.
obj.addEventListener(MouseEvent.CLICK, onButtonClicked);
I would like the ability to set the buttonMode, visibility, etc. of all of the buttons simultaneously. I have been looking into this for a few hours and am not able to find any solutions. I am now looking into adding them to a vector (which is a new concept for me), but I am not sure how to go about executing this properly. This is what I have so far.
public var buttons:Vector.<MovieClip > = new Vector.<MovieClip > ();
function addButtons()
{
buttons.push(btn1,btn2,btn3,btn4,btn5,btn6,btn7);
for (var i:int; i<buttons.length; i++)
{
trace(buttons[i].name);
}
}
How would I go about, for example, adding the event listener to all of the objects? I will also be setting the buttonMode to true, and making them all invisible simultaneously. I don't even know if it's possible to accomplish this. Thank you in advance for any suggestions.
I'm going to asume that you use timeline code, and have instances of the buttons already placed on the stage. So, first, create the vector:
var _btns:Vector.<MovieClip> = new Vector.<MovieClip>;
_btns.push(btn1,btn2,btn43....) //add all the buttons
Than, you can init the properties of all the buttons:
var _mc:MovieClip;//helper var
for(var i:int=0,i<_btns.length;i++)
{
_mc = _btns[i];
_mc.visible = false;
_mc.buttonMode = true;
_mc.addEventListener(MouseEvent.CLICK, onClick);
}
Then, the event handler:
function onClick(e:MouseEvent):void
{
for(var i:int=0,i<_btns.length;i++)//reset all the buttons
{
_btns[i].visible = false;
}
_mc = MovieClip(e.eventTarget);
_mc.visible = true; //make visible the clicked one
}
You just need to do what you are doing with the .name property in your example code. You need to loop thru every single button in your array (or vector, if you prefer). Here is an example how to set the property of buttonMode:
function setButtonMode(b:Boolean):void {
for(var i:int=0; i<buttons.length; i++) {
var btn:MovieClip = buttons[i]; //store the current reference in a var for faster access
btn.buttonMode = b;
btn.mouseChildren = !b;
}
}

Flash AS3 - Drag and Drop multiple objects to one target?

Title is more or less self-explanatory, I’ve been working through many different tutorials and I’m not exactly too good with AS3 to be perfectly honest. (Image above shows what I'm aiming for)
Anyway, what I notice in most of the online tutorials I see, the drag and drop tutorials are either based on one object to one target or multiple objects to multiple targets, so I was wondering if someone is kind enough to help me and explaining how I can get multiple objects to connect to one target.
And, if possible making it switchable, as in for example, if object 1 is already in place on the target when I drag object 2 over, then object 1 returns to its original position and object two takes its place.
A easier way to explain this is to say that I'm trying to create a game where there are three statues and the user can pick one of the three to place in a set target zone.
I apologies if what I say doesn't make much sense, will clear up anything if that causes confusion. Here's the AS3 code I'm using at the moment.
var startX:int;
var startY:int;
circle1_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
circle1_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
circle2_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
circle2_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
circle3_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
circle3_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
function pickUp(event:MouseEvent):void {
startX = event.target.x;
startY = event.target.y;
event.target.startDrag(true);
event.target.parent.addChild(event.target);
}
function dropIt(event:MouseEvent):void {
event.target.stopDrag();
var theTargetName:String = "target" + event.target.name;
var theTarget:DisplayObject = getChildByName(theTargetName);
if (event.target.dropTarget != null && event.target.dropTarget.parent == theTarget){
event.target.buttonMode = false;
event.target.x = theTarget.x;
event.target.y = theTarget.y;
}
else{
event.target.x = startX;
event.target.y = startY;
circle1_mc.buttonMode = true;
circle2_mc.buttonMode = true;
circle3_mc.buttonMode = true;
Instead of checking the dropTarget, you can use hitTestObject to see if the dropped object is "touching" theTarget. Otherwise, any other item that has already been dropped onto theTarget may be reported as the dropTarget.
Also, since MovieClip is dynamic, you can store the startX and startY values in each instance.
The following modified code will use a single target_mc as a drop target. When one item is dropped on it, any other items will be moved back to their original spot:
// create an array as #David suggested to keep track of your draggable items
var circles:Array = [circle1_mc, circle2_mc, circle3_mc];
for each(var circleMC:MovieClip in circles)
{
circleMC.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
circleMC.addEventListener(MouseEvent.MOUSE_UP, dropIt);
circleMC.startX = circleMC.x;
circleMC.startY = circleMC.y;
}
function pickUp(event:MouseEvent):void
{
// no longer need to keep track of startX & startY here because that's already been done up above
event.target.startDrag(true);
event.target.parent.addChild(event.target);
}
function dropIt(event:MouseEvent):void
{
event.target.stopDrag();
// check to see if the event target is touching target_mc using hitTestObject
if(event.target.hitTestObject(target_mc)){
event.target.buttonMode = false;
event.target.x = target_mc.x;
event.target.y = target_mc.y;
// move all circles OTHER than the current target back to their original positions
for each(var circleMC:MovieClip in circles)
{
if(event.target != circleMC)
{
circleMC.x = circleMC.startX;
circleMC.y = circleMC.startY;
}
}
}
else
{
// only need to move the event target back if it was dropped outside of target_mc
event.target.x = event.target.startX;
event.target.y = event.target.startY;
event.target.buttonMode = true;
}
}