Fran Verona
Fran Verona

Reputation: 5476

Drag and clone MovieClip in AS3

I have a toolbar with some cars on the left of the window, and I want to click on one element and drag it to the board creating a clone of it, but I can't do it.

My app looks like this:

enter image description here

Cars on the left are my desired dragged.

My source code is:

public class Car extends MovieClip
    {

        // imports...

        var newcar:Car;

        public function Car(){
            addListeners();
        }

        private function addListeners():void{
            this.addEventListener(MouseEvent.MOUSE_DOWN,clone);
        }

        private function clone(e:MouseEvent):void{
            // Clone the object
            newcar = new dibujo();
            newcar.graphics.copyFrom(this.graphics);
            newcar.x = this.x;
            this.parent.addChild(newcar);

                    // Asign new events to recently created mc
            newcar.addEventListener(MouseEvent.MOUSE_OVER,dragCar);
            newcar.addEventListener(MouseEvent.MOUSE_UP,dropCar);
        }

        private function dragCar(e:MouseEvent):void{
            this.startDrag();
        }

        private function dropCar(e:MouseEvent):void{
            this.stopDrag();
        }

    }

The red car and the truck use my own basic class called 'Car'.

Thanks in advance! I hope someone can help me.

Upvotes: 0

Views: 2030

Answers (1)

Kejml
Kejml

Reputation: 2204

And what is not working? Main problem I see is, that you create new car, but you don't add it to the display list. In your clone function, you need something like

this.parent.addChild(newcar);

edit: So as I said in comments, problem is, tah property graphics is read only, so you can't change it. If your cars are instaces of classes that extend your Car (if they are not, you can easily make them), you can use this: replace

newcar = new dibujo(); //I think you menat new Car() here

with

newcar = new e.target.constructor;

this should finally make it work. You will then encounter problem with dragging - it never stops. But solution is simple, add this line to your stopDrag function:

e.target.removeEventListener(MouseEvent.MOUSE_MOVE, dragCar);

Upvotes: 1

Related Questions