AS3 Error drag and drop multiple draggable object to multiple target - actionscript-3

I want to make the game drag and drop to create multiple draggable objects and it can dragged to multiple targets. But I encountered an error when I drag to the first object that I choose to certain target object is not dragged to the target and then I drag it to another target then succeed. I wanted to fix it. And if you can fix it when the object is dragged to the target and then want to be replaced by another object then the dragged object will be replaced and returned to its original position.
This is a overview the program
And this is the source codes that I use
var xPos:int;
var yPos:int;
var poin:int = 0;
var namaobj1:String;
var namaobj2:String;
addListeners(membaca, menulis, berenang, sepakbola, melukis, memasak, menari, bercocoktanam, beladiri, bermainmusik);
proses.addEventListener(MouseEvent.CLICK,proses1);
function getPosition(target:Object):void
{
xPos = target.x;
yPos = target.y;
}
function dragObject(e:MouseEvent):void
{
getPosition(e.target);
e.target.startDrag(true);
}
function stopDragObject(e:MouseEvent):void
{
if (e.target.hitTestObject(getChildByName("target2")))
{
e.target.x = getChildByName("target2").x;
e.target.y = getChildByName("target2").y;
namaobj2 = e.target.name;
}
else if (e.target.hitTestObject(getChildByName("target1")))
{
e.target.x = getChildByName("target1").x;
e.target.y = getChildByName("target1").y;
namaobj1 = e.target.name;
}
else
{
e.target.x = xPos;
e.target.y = yPos;
}
pil1.text = namaobj1;
pil2.text = namaobj2;
e.target.stopDrag();
}
function addListeners(... objects):void
{
for (var i:int = 0; i < objects.length; i++)
{
objects[i].addEventListener(MouseEvent.MOUSE_DOWN, dragObject);
objects[i].addEventListener(MouseEvent.MOUSE_UP, stopDragObject);
}
}
I'm using draggable objects by putting addListener function.
I also include his .fla can be downloaded here ( TEST.FLA ) rather you can more easily apply fixed codes

You can add Mouse_UP event in your targets instead of you dragged objects. Then when the MOUSE_UP event is trigged, you will know which objects is your target(e.target) without hitTestObject. The code is as follows:
You could have to set dragged object's mouseEnabled when mouse down, and true after dragged.

Related

Easy way to make a lot of buttons share a function? AS3

I am trying to do a simple light-up pegboard in flash. I have finished the general logic for 1 peg but there will be a total of 2,300 pegs and I don't want to have to add an event listener to each movieclip.
Here is my code:
import flash.events.Event;
var my_color:ColorTransform = new ColorTransform();
movieClip_1.addEventListener(MouseEvent.MOUSE_UP, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
if (my_color.color == 0)
{
my_color.color = 0x0000FF;
event.target.transform.colorTransform = my_color;
}
else if (my_color.color == 255)
{
my_color.color = 0x00FF00;
event.target.transform.colorTransform = my_color;
}
else if (my_color.color == 65280)
{
my_color.color = 0xFF0000;
event.target.transform.colorTransform = my_color;
}
else if (my_color.color == 16711680)
{
my_color.color = 0xFFFFFF;
event.target.transform.colorTransform = my_color;
}
else if (my_color.color == 16777215)
{
my_color.color = 0x000000;
event.target.transform.colorTransform = my_color;
}
else
{
trace(my_color.color);
}
}
[
Here are 3 ways to accomplish this:
Put the code on the peg's own timeline. (or make a class file, and attach it to your peg object). This will re-use the same code for each peg instance automatically. Just take the same code you have, but use the this keyword instead of a hard reference to the movie clip:
var my_color:ColorTransform = new ColorTransform();
this.addEventListener(MouseEvent.MOUSE_UP, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
//.....
Make a container Sprite/MovieClip and have all the pegs be the sole children of it. Then iterate over all the children of that container and attach the listener:
//loop through all children of the container and add an event listener
var i:int = container.numChildren;
while(i--){
container.getChildAt(i).addEventListener(....);
}
This is good because you don't have to give them instance names, which would be quite tedious.
Attach a click listener to a common parent of all pegs, and use the target property of the event to see if the click was on a peg.
Assuming you have right-clicked your peg library object, gone to properties and checked "export for actionscript" and given it the Class name "MyPeg", you could do this:
commonParent.addEventListener(MouseEvent.CLICK, parentClick);
function parentClick(e:Event):void {
if(e.target is MyPeg){
//it's a PEG, do something
}
}
Now, depending on how your peg object is structured, target could also refer to a child of your peg (instead of the peg itself). To avoid this if it's applicable, you can disable mouse input on the children of the peg. So on the first frame of your peg object, you could this: this.mouseChildren = false;
Now, even better (less tedious) would be to instantiate your pegs through code too. So as mentioned earlier, export your peg for actionscript in it's properties, and give it a class name ("MyPeg" for my example). Then something along these lines:
var curRow:int = 0;
var curCol:int = 0;
var totalRows:int = 25;
var totalCols:int = 92;
var startingY:int = 10;
var startingX:int = 10;
var padding:int = 2; //gap between pegs
var curPeg:MyPeg;
while(true){
//create the peg, and add it to the display.
curPeg = new MyPeg();
addChild(curPeg);
//add the click listener to this peg
curPeg.addEventListener(MouseEvent.CLICK, fl_mouseClickHandler);
//assign the position of this peg
curPeg.x = startingX + (curCol * (curPeg.width + padding));
curPeg.y = startingY + (curRow * (curPeg.height + padding));
//increment the column
curCol++;
//check if we've reached the last column in the row
if(curCol >= totalCols - 1){
//yes, so reset the column to 0 and increment the row
curCol = 0;
curRow++;
//break out of the loop if the curRow exceeds or is equal to the total rows var
if(curRow >= totalRows) break;
}
}
This way you could change your grid size simply by modifying the number assigned to totalCols and totalRows - no need to tediously move around 2300 objects in FlashPro.
One way to do it is loop through all the children of the parent of your 2300 pegs.
for (var i:int=0; i<numChildren; i++) {
var clip = getChildAt(i);
if (clip.name.indexOf('movieClip_')==0) {
clip.addEventListener((MouseEvent.MOUSE_UP, fl_MouseClickHandler);
}
}
Another way to do it is to add a handler to the entire parent clip and then in the handler check and see if what was clicked is one of your pegs. But you have to disable mouseChildren on the child clips for that to work.
Note that you may want to look at replacing that big if/then statement with switch/case, which is clearer and more compact in this type of situation.

How to apply drag and drop function to all frames in movie clip? Actionscript3

Each frame contain 1 text field. I apply the code on timeline.
But it only gets applied to the last object, which means that I can only drag and drop the last object. Why?
How can I improve this so that I can drag and drop all objects?
for(var j:uint=0; j<3; j++)
{
var q:Ans = new Ans();
q.stop();
q.x = j * 300+50;// set position
q.y = 500;
var r:uint = Math.floor(Math.random() * q_list.length);
q.qface = q_list[r];// assign face to card
q_list.splice(r,1);// remove face from list;
q.gotoAndStop(q.qface+1);
q.addEventListener(MouseEvent.MOUSE_DOWN, startAnsDrag);
q.addEventListener(MouseEvent.MOUSE_UP, stopAnsDrag);
q.addEventListener(Event.ENTER_FRAME, dragAns);
addChild(q);// show the card
}
//----------------------------drag
// offset between sprite location and click
var clickOffset:Point = null;
// user clicked
function startAnsDrag(event:MouseEvent) :void
{
clickOffset = new Point(event.localX, event.localY);
}
// user released
function stopAnsDrag(event:MouseEvent) :void
{
clickOffset = null;
}
// run every frame
function dragAns(event:Event) :void
{
if (clickOffset != null)
{ // must be dragging
q.x = clickOffset.x+mouseX+135;
q.y = clickOffset.y+mouseY;
}
}
Make a new layer in the timeline just for your drag-and-drop code, which you can remove from your other actionscript. Put the code on the first frame in that layer. Now click on and select the last frame on that layer in which you want the code to be effective (probably the last frame of the MovieClip). Press F5 to draw-out the range of frames which will be affected by the code. Voila!

AS3 Object Bin and Reset Button

I am trying to create a game for kids where they can drag letters on to a stage to make words.
I want to add a 'trash can' where users can drag letters they no longer need to dispose of them. I have created the movie clip but am totally unsure how to make it function using AS3.
I would also like to add a reset button so that the stage reverts to it's original state. Again, I have drawn it up and added the little as3 that I am aware of (to make it a button) but if anyone could assist with how to actually make this happen, I would be grateful.
The files are here: SWF | FLA and the code for the game is as follows:
import flash.display.MovieClip;
for (var i=1; i<27; i++)
{
this["object" + i].addEventListener(MouseEvent.MOUSE_DOWN, onStart);
this["object" + i].addEventListener(MouseEvent.MOUSE_UP, onStop);
}
var sx = 0,sy = 0;
function onStart(e)
{
sx = e.currentTarget.x;
sy = e.currentTarget.y;
e.currentTarget.startDrag();
}
function onStop(e)
{
if ( e.target.dropTarget != null &&
e.target.dropTarget.parent == dest &&
e.currentTarget.name != "copy" )
{
var objectClass:Class =
getDefinitionByName(getQualifiedClassName(e.currentTarget)) as Class;
var copy:MovieClip = new objectClass();
copy.name = "copy";
this.addChild(copy);
copy.x = e.currentTarget.x;
copy.y = e.currentTarget.y;
e.currentTarget.x = sx;
e.currentTarget.y = sy;
copy.addEventListener(MouseEvent.MOUSE_DOWN, onStart);
copy.addEventListener(MouseEvent.MOUSE_UP, onStop);
}
e.currentTarget.stopDrag();
}
resetButton.addEventListener(MouseEvent.CLICK, reset);
resetButton.buttonMode = true;
function reset(event:MouseEvent):void
{
//Not sure what AS3 to add here to reset to original state
}
I have already gave you the solution here Flash AS3 Clone, Drag and Drop
Here, I am providing a detail solution on how to drag objects inside a bin and remove them.
For dropping copied objects inside a bin, after dragging is stopped, check collision with bin object. for more info see,
copiedObject.hitTestObject(binObject)
For e.g.
First create trash-can MovieClip on the stage and give it an instance name 'trashCan' and add following lines to your onStop()(below e.currentTarget.stopDrag();)function like so:
UPDATE:
var copiedObjsArr:Array = [];
function onStop(e)
{
if ( e.target.dropTarget != null &&
e.target.dropTarget.parent == dest &&
e.currentTarget.name != "copy" )
{
//Code here remains same
//.......
//Keep collecting copied letters for further access in `reset()` function
copiedObjsArr.push(copy);
}
else if(e.currentTarget.name == "copy") //this is 'else if' (newly added)
{
var tarObject:MovieClip = e.currentTarget;
// These detects collision of dragged object with the trashCan
if(tarObject.hitTestObject(trashCan)) {
//These removes dragged object from the display list (not from the memory)
removeChild(tarObject);
tarObject = null; //to garbage
}
}
e.currentTarget.stopDrag();
}
And your reset() becomes like so:
function reset(event:MouseEvent):void
{
if(copiedObjsArr.length > 0)
{
//Traverse through all copied letters
for(var i:int = 0; i<copiedObjsArr.length; i++)
{
var objToRemove:MovieClip = copiedObjsArr[i];
removeChild(objToRemove);
objToRemove = null;
}
//Finally empty the array
copiedObjsArr = [];
}
}

use 1 object multiple times in as3?

I'm trying to make something like bookmarks, I have 1 note on the stage and when the user clicks it, it starts to drag and the users drops it where they want. the problem is I want these notes to be dragged multiple times.. here is my code:
import flash.events.MouseEvent;
//notess is the instance name of the movie clip on the stage
notess.inputText.visible = false;
//delet is a delete button inside the movie clip,
notess.delet.visible = false;
//the class of the object i want to drag
var note:notes = new notes ;
notess.addEventListener(MouseEvent.CLICK , newNote);
function newNote(e:MouseEvent):void
{
for (var i:Number = 1; i<10; i++)
{
addChild(note);
//inpuText is a text field in notess movie clip
note.inputText.visible = false;
note.x = mouseX;
note.y = mouseY;
note.addEventListener( MouseEvent.MOUSE_DOWN , drag);
note.addEventListener( MouseEvent.MOUSE_UP , drop);
note.delet.addEventListener( MouseEvent.CLICK , delet);
}
}
function drag(e:MouseEvent):void
{
note.startDrag();
}
function drop(e:MouseEvent):void
{
e.currentTarget.stopDrag();
note.inputText.visible = true;
note.delet.visible = true;
}
function delet(e:MouseEvent):void
{
removeChild(note);
}
any help will be appreciated.
You need to create a new instance of your note class when you drop, copy the location and other variables from the note you were dragging, add your new note to the stage, and return the dragging note to its original position.
Something like:
function drop($e:MouseEvent):void
{
$e.currentTarget.stopDrag();
dropNote($e.currentTarget as Note);
}
var newNote:Note;
function dropNote($note:Note):void
{
newNote = new Note();
// Copy vars:
newNote.x = $note.x;
newNote.y = $note.y;
// etc.
// restore original note.
// You will need to store its original position before you begin dragging:
$note.x = $note.originalX;
$note.y = $note.orgiinalY;
// etc.
// Finally, add your new note to the stage:
addChild(newNote);
}
... this is pseudo-code really, since I don't know if you need to add the new note to a list, or link it to its original note. If you Google ActionScript Drag Drop Duplicate, you will find quite a few more examples.
I think you are not target the drag object in drag function and problem in object instantiation
for (var i:Number = 1; i<numberOfNodes; i++) {
note = new note();
addChild(note);
...
....
}
function drag(e:MouseEvent):void{
(e.target).startDrag();
}
If you are dragging around multiple types of objects (eg. Notes and Images), you could do something like this, rather than hard coding the type of object to be instantiated.
function drop(e:MouseEvent):void{
// Get a reference to the class of the dragged object
var className:String = flash.utils.getQualifiedClassName(e.currentTarget);
var TheClass:Class = flash.utils.getDefinitionByName(className) as Class;
var scope:DisplayObjectContainer = this; // The Drop Target
// Convert the position of the dragged clip to local coordinates
var position:Point = scope.globalToLocal( DisplayObject(e.currentTarget).localToGlobal() );
// Create a new instance of the dragged object
var instance:DisplayObject = new TheClass();
instance.x = position.x;
instance.y = position.y;
scope.addChild(instance);
}

as3 marquee select drag multiple child objects

Can anyone tell me how to achieve marquee selection effect with AS3 to select multiple movieclips by drawing a dynamic rectangle around them and then drag and drop them anywhere?
Don't use startDrag() if you need multiple objects to be draggable, since it only allows one object to be dragged at a time. Instead, listen for mouse events and do the moving manually:
var oldX:int;
var oldY:int;
var dragging:Boolean = false;
function onMouseDown(evt:MouseEvent):void {
dragging = true;
oldX = evt.stageX;
oldY = evt.stageY;
}
function onMouseMove(evt:MouseEvent):void {
if (!dragging) return;
var dX:int = evt.stageX - oldX;
var dY:int = evt.stageY - oldY;
for (int i = 0; i < selectedClips.length; i++) {
var clip:DisplayObject = selectedClips[i];
clip.x += dX;
clip.y += dY;
}
oldX = evt.stageX;
oldY = evt.stageY;
}
function onMouseUp(evt:MouseEvent):void {
dragging = false;
}
This code assumes that:
Your array of selected objects is called selectedClips.
Your array of selected objects all inherit from DisplayObject.
You have added event listeners on all draggable objects for the MOUSE_DOWN, MOUSE_MOVE, and MOUSE_UP mouse events which call these functions.
If any of those three conditions are not met, update my code or your code to work properly. Also, if you need to do any additional handling when the objects are dropped, you can use the mouse up handler to add custom code.