views:

288

answers:

3

Hi,

I am trying to create a simple drag and drop Flash program where a user can drag xmas ornaments onto a tree. Instead of being able to drag the ornament once, I want a function so that every time an ornament is clicked on, it adds a new ornament of the same class to the stage where the ornament is clicked. Currently I have this working but there is one problem. It is not dynamic. Looking in the "drag" function, I have chosen the class "Symbol31" as the default ornament that gets added. Instead, I want the ActionScript to read the class of the ornament that was clicked on and to add that class, not "Symbol31" everytime.

Please see my code below.

Thanks

public class DragDrop extends MovieClip
{
    private var originalX:Number;
    private var originalY:Number;

    public function DragDrop()
    {
        originalX = this.x;
        originalY = this.y;
        this.addEventListener(MouseEvent.MOUSE_DOWN, drag);
    }

    private function drag(event:MouseEvent):void
    {
        if(event.target.x>Number(600))
        {
            var newOrnament:Symbol31 = new Symbol31();
            newOrnament.x=originalX;
            newOrnament.y=originalY;
            this.parent.addChild(newOrnament);
            newOrnament.startDrag();
            newOrnament.addEventListener(MouseEvent.MOUSE_UP, drop);
        }else{
            this.startDrag();
            this.parent.addChild(this);
            this.addEventListener(MouseEvent.MOUSE_UP, drop);
        }

    }
A: 

Assuming you have a base class for all your ornaments, can you do something like the following?

var newOrnament = event.target as OrnamentBase
if (newOrnament != null)
{
    // your code
}
skalburgi
+2  A: 

The most flexible solution would be to first get the name of the class by passing event.target into getQualifiedClassName (part of flash.utils) and then passing that into getDefinitionByName (also in flash.utils) to turn that string into a reference to the actual class. Make a new instance of that class and off you go.

Branden Hall
this is great! thank you
Adrian Adkison
A: 

To piggyback on what Branden Hall said the code might look something like this:

var ClassReference:Class = getDefinitionByName(getQualifiedClassName(e.target)) as Class;
var instance:DisplayObject = new ClassReference();
addChild(instance);
ThunderChunky_SF