I have a AS3 class which extends movieClip with a dynamic image, how to make this image draggable?
I need to make an item draggable (dragable?) Sorry if my terminology is not right!
I have a class where I will store variable and do calculations:
package Classes
{
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class PrintItem extends MovieClip
{
public var imageLoader:Loader;
public function PrintItem()
{
}
public function loadImage(url:String):void
{
imageLoader = new Loader();
imageLoader.load(new URLRequest(url));
}
}
}
I create a new instance of the class, I pass it an URL in loadImage and I add it to the canvas like this:
var myItem:PrintItem = new PrintItem();
myItem.loadImage("pic.jpg");
this.addChild(myItem.imageLoader);
myItem.imageLoader.x = 50;
myItem.imageLoader.y = 50;
myItem.imageLoader.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
myItem.imageLoader.addEventListener(MouseEvent.MOUSE_UP, dropIt);
But there I am stuck. I need to make this item draggable and write the pickUp and dropIt functions. event.target.startDrag(false); doesn't work (Loader isn't draggable) and event.target.parent.startDrag(false); doesn't work as the whole stage becomes draggable! HELP! Is it because only th开发者_Go百科e Loader is added to the stage?
Ok. I know it has only been a few minutes, but I have found the answer. Writing it down here cleared it in my head. Here's what worked for me in case it helps anybody else:
First, I added the Loader image as a child to the class like this:
public function loadImage(url:String):void
{
imageLoader = new Loader();
imageLoader.load(new URLRequest(url));
this.addChild(imageLoader); // IMPORTANT!
this.mouseChildren = false;
this.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
this.addEventListener(MouseEvent.MOUSE_UP, dropIt);
}
And then I only had to add the class to the stage, not the loader:
this.addChild(myItem);
Back to the class, I added this:
public function pickUp(event:MouseEvent):void
{
trace("Pickup");
this.startDrag(false);
}
public function dropIt(event:MouseEvent):void
{
this.stopDrag();
trace("X = " + event.target.x + " Y = " + event.target.y); // Just to help me
}
Et voila! It worked!
精彩评论