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

必要なのは、オブジェクト指向プログラミングの 4 つの基本概念の1 つである継承です。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も注意してください。したがって、拡張元の各クラスには、とクラスの両方の機能があります。MovieClipDraggableMovieClipDraggable

参考文献:

于 2013-01-21T03:03:10.327 に答える