0

例如,如何创建一个处理所有 startDrag() 和 stopDrag() 事件的类?这个类没有MovieClip。我希望此类仅用作多个类使用的事件的处理程序。

我正在制作一个游戏,我有很多可以拖放的项目,我需要一种更有效的方法,而不是把这段代码放在每个项目类中。

那么还有其他方法可以做到这一点吗?现在我必须将它复制并粘贴到我拥有的每个可以拖放的类中。

public function Weapon1() 
{
        originalPosition = new Point(x,y);
        addEventListener(Event.ENTER_FRAME, onEntrance);
}
public function onEntrance(evt:Event)
{
        addEventListener(MouseEvent.MOUSE_DOWN, mousedown);
        addEventListener(MouseEvent.MOUSE_UP, mouseup);
}
public function mousedown(evt:MouseEvent)
{
        startDrag(true);
}
public function mouseup(evt:MouseEvent)
{
        stopDrag();
        if(dropTarget)
        {
            if(dropTarget.parent.name == "slot")
            {
                this.x = dropTarget.parent.x;
                this.y = dropTarget.parent.y;
            }
        }
        else
        {
            returnToPosition();
        }
    }
    else
    {
        returnToNewPosition();
    }
}
public function returnToPosition()
{
    x = originalPosition.x;
    y = originalPosition.y;
}
public function returnToNewPosition()
{
    x = newPosition.x;
    y = newPosition.y;
}
4

1 回答 1

4

您需要的是继承,它是面向对象编程的四个基本概念之一。在 OOP 中,继承使类能够采用现有基类(也称为超类)的属性和方法。

所以; 您应该创建一个具有拖放逻辑的基类,并扩展该类以创建其他派生类(也称为子类)。

例如,这是基类 ( Draggable):

package
{
    public class Draggable extends MovieClip
    {
        //Constructor

        public function Draggable()
        {
            addEventListener(Event.ADDED_TO_STAGE, onStageReady);
        }

        //Event Handlers

        protected function onStageReady(event:Event):void
        {
            addEventListener(MouseEvent.MOUSE_DOWN, mousedown);
            addEventListener(MouseEvent.MOUSE_UP, mouseup);
        }

        protected function mousedown(event:MouseEvent):void
        {
            startDrag(true);
            //more stuff here...
        }

        protected function mouseup(event:MouseEvent):void
        {
            stopDrag();
            //more stuff here...
        }
    }
}

...这是Weapon1扩展基类的类:

package
{
    public class Weapon1 extends Draggable
    {
        //Constructor

        public function Weapon1()
        {
            //initialize Weapon1
        }

        //Methods, handlers, etc...
    }
}

如你所见; 它extend是启用Weapon1类继承的关键字。
您可以继续创建更多武器类别...

public class Weapon2 extends Draggable { ... }
public class Weapon3 extends Draggable { ... }
public class Weapon4 extends Draggable { ... }

请注意,Draggable该类还扩展MovieClip该类以获得一些其他功能。因此,您扩展的每个类都Draggable将具有MovieClipDraggable类的功能。

参考:

于 2013-01-21T03:03:10.327 回答