AS3 - How to drag an object in a line that is not vertical or horizontal
I would like to dr开发者_StackOverflowag an object in one line. I already know how to do this in a horizontal or vertical line
Here's how I do this
private var handle:Sprite;
private function init():void
{
handle = new Sprite();
handle.mouseChildren = false;
handle.buttonMode = true;
handle.graphics.beginFill(0xFF0000);
handle.graphics.drawCircle(0, 0, 5);
handle.addEventListener(MouseEvent.MOUSE_DOWN, startMove);
handle.addEventListener(MouseEvent.MOUSE_UP, stopMove);
}
private function startMove(evt:MouseEvent):void
{
var bounds:Rectangle = new Rectangle(0, 0, 100, 1);
handle.startDrag(false, bounds);
}
private function stopMove(evt:MouseEvent):void
{
handle.stopDrag();
}
But I want do drag my object in a line that isn't horizontal or vertical. For example, I would like to drag the object from the top left corner to the bottom right corner, in one straight line.
I tried to rotate the bounds rectangle, but it seems that you can not rotate a Rectangle.
How do I drag an object in a non-vertical (or non-horizontal) line?
Thank you very much!
Vincent
You cannot use startdrag system to do it. You have to use an enterframe event and constraint x/y yourself :
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class Test extends Sprite
{
private var handle:Sprite;
public function Test()
{
handle = new Sprite();
addChild(handle);
handle.mouseChildren = false;
handle.buttonMode = true;
handle.graphics.beginFill(0xFF0000);
handle.graphics.drawCircle(0, 0, 5);
handle.addEventListener(MouseEvent.MOUSE_DOWN, startMove);
addEventListener(MouseEvent.MOUSE_UP, stopMove);
}
private function startMove(evt:MouseEvent):void
{
stage.addEventListener(Event.ENTER_FRAME, updateClipPos);
}
private function stopMove(evt:MouseEvent):void
{
stage.removeEventListener(Event.ENTER_FRAME, updateClipPos);
}
private function updateClipPos(e:Event) : void
{
if(mouseX < 100)
{
handle.x = mouseX;
handle.y = handle.x;
}
}
}
}
精彩评论