AS3 - 如何在不同的事件中调用之前的currentTarget?

时间:2015-06-08 20:04:42

标签: actionscript-3 events

我有一个下拉菜单,可让您选择要放置在舞台上的项目。该项目是可拖放的,因此我使用event.currentTarget.startDrag();开始拖动。好的,到目前为止一切正常。

但是,我还需要能够在拖动项目时旋转项目(使用空格键)。

stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
    function myKeyDown(e:KeyboardEvent):void{
    if (e.keyCode == Keyboard.SPACE){
        rotate++;
        if (rotate == 5){
            rotate = 1;

        }
        WHATGOESHERE?.gotoAndStop(rotate);
        } 

如果我在对象的实例名称中进行硬编码,一切正常 - 因此旋转功能正常工作。问题是,如何在keyDown事件内部从startDrag函数引用event.currentTarget?

我的第一个想法是将event.currentTarget设置为变量,然后从keyDown事件中调用变量。但是,targetHold = event.currentTarget;似乎没有记录被单击对象的实例名称...

public var targetHold:Object = new Object;

function ClickToDrag(event:MouseEvent):void {
    event.currentTarget.startDrag();
    targetHold = event.currentTarget;
        trace ("targetHold " + targetHold);

    stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
    function myKeyDown(e:KeyboardEvent):void{
    if (e.keyCode == Keyboard.SPACE){
        rotate++;
        if (rotate == 5){
            rotate = 1;
        }
        targetHold.gotoAndStop(rotate); //does not work
        } 
    }


function ReleaseToDrop(event:MouseEvent):void { 
    event.currentTarget.stopDrag();
}

2 个答案:

答案 0 :(得分:2)

单击对象时,它应该具有焦点。如果您在对象上注册KeyboardEvent的侦听器而不是在舞台上,则它将是.currentTarget

这是我想到的一个例子。在开始拖动之后,将侦听器添加到同一对象而不是舞台。

event.currentTarget.startDrag();
event.currentTarget.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);

这样做的正确方法是定义类中的所有功能。在自包含的类中,您不需要任何.currentTarget

答案 1 :(得分:1)

以下是我将如何做到这一点:(好吧,实际上我会遵循@ null的建议并将其封装在一个所有可拖动对象都会扩展的子类中,但这样做有点宽,所以这样做)

public var targetHold:MovieClip; //don't make a new object, just create the empty var

public function YourConstructor(){
    //your other constructor code
    stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown); //don't add the listener in the click function
}

private function clickToDrag(event:MouseEvent):void {
    if(targetHold) ReleaseToDrop(null);  //safeguard in case flash lost the focus during the mouse up

    targetHold = event.currentTarget as MovieClip;  //assign the current target. Might as well cast it as MovieClip and get code completion benefits
    targetHold.startDrag();
    trace ("targetHold " + targetHold);
}

private function myKeyDown(e:KeyboardEvent):void{
    //check if target hold exists
    if (targetHold != null && e.keyCode == Keyboard.SPACE){
        rotate++;
        if (rotate == 5){
            rotate = 1;
        }
        targetHold.gotoAndStop(rotate);
    } 
}

private function ReleaseToDrop(event:MouseEvent):void { 
    if(targetHold) targetHold.stopDrag();
    targetHold = null;
}