Actionscript 3,拖动时旋转对象

时间:2011-05-26 20:46:59

标签: actionscript rotation drag

我有一个需要通过单击和拖动来旋转的对象。在一些AS2代码之后,每次点击鼠标时我都会让对象旋转一点,但是无法通过拖动来使其工作。

needle.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_2);
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_2);

function fl_ClickToDrag_2(event:MouseEvent):void
{

        var angle = Math.atan2(mouseY-needle.y,mouseX-needle.x);
        // apply rotation to handle by converting angle into degrees
        needle.rotation = angle*180/Math.PI;
        // rotate the grip opposite the handle so it won't rotate along with it
        //this.grip._rotation = -this._rotation;
}

function fl_ReleaseToDrop_2(event:MouseEvent):void
{
    needle.stopDrag();
}

1 个答案:

答案 0 :(得分:3)

我看到的问题是MOUSE_DOWN事件每次点击只触发一次,因此您只需在处理程序中运行一次代码。

可能有比这更好的方法,但这就是我考虑的方式:

编辑细节:

public class Test extends MovieClip {
    private var n:Needle;

    public function Test() {
        // constructor code
        n = new Needle();

        stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownF,false,0,true);
        stage.addEventListener(MouseEvent.MOUSE_UP,mouseUpF,false,0,true);


        n.x = stage.stageWidth/2; //center needle on stage
        n.y = stage.stageHeight/2;
        addChild(n); //add needle to stage
    }
    public function mouseDownF(e:MouseEvent):void {
        stage.addEventListener(MouseEvent.MOUSE_MOVE,rotate,false,0,true);
    }
    public function rotate(e:MouseEvent):void {
        var angle:Number = Math.atan2(mouseY - n.y,mouseX - n.x); //get angle in radians (pythagoras) 

        angle = angle * 180/Math.PI -90; //convert to degrees , the 90 is to have it point to the mouse

        n.rotation = angle; //rotate
    }
    public function mouseUpF(e:MouseEvent):void {
        stage.removeEventListener(MouseEvent.MOUSE_MOVE,rotate);
    }
}

因此,当用户点击(mouseDown)时,它会激活一个事件监听器,每次鼠标移动时都会触发rotate处理程序。当用户放开单击时,事件侦听器将被销毁。添加事件监听器时false,0,true);是使它成为weakly referenced listener,以便它被垃圾收集器收集,而不仅仅是在内存中占用空间。