views:

387

answers:

2

I need some actionscript code to simulate the dragging and dropping of a Sprite, I was wondering if it is possible to do so? if it is how?

For example to simulate a click on a Sprite I can achieve with the following line of code.

sprite.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
A: 

For AIR Sprite Class has nativeDragStart, nativeDragOver, nativeDragEnter, nativeDragExit, nativeDragUpdate. So you can dispatch these events.

For Flex, object has to be instance of UIComponent.

zdmytriv
+1  A: 

Either do something like this:

mySprite.addEventListener("mouseDown", mouseDownHandler);
stage.addEventListener("mouseUp", mouseUpHandler);
protected function mouseDownHandler (e:MouseEvent):void{
   e.target.startDrag();
}
protected function mouseDownHandler (e:MouseEvent):void{
   e.target.stopDrag();
}

You can pass 2 arguments to the startDrag method, the first is a boolean to lock to center, the second is a Rectangle-object for boundary-points.

And for a more controlled behavior you can do something like this instead:

mySprite.addEventListener("mouseDown",
mouseDownHandler);
stage.addEventListener("mouseUp", mouseUpHandler);
protected function mouseDownHandler (e:MouseEvent):void{
   stage.addEventListener("mouseMove",
mouseMoveHandler);
}
protected function mouseDownHandler (e:MouseEvent):void{
   stage.removeEventListener("mouseMove",
mouseMoveHandler);
}
protected function mouseMovehandler(e:MouseEvent):void{
  mySprite.x=mouseX;
  mySprite.y=mouseY;
}

(haven't tested the code so there might be some small syntax-error or something)

Clox