Как перетащить два мувиклипа (на отдельных слоях) одновременно - PullRequest
0 голосов
/ 28 июня 2011

Я искал часы, но так и не нашел ответа на мою проблему.

Моя цель - иметь карту, которую я могу перетаскивать в рамке веб-страницы. Найти правильный код для перемещения карты в ограниченном фрейме было не так-то просто, но мне удалось найти его (который работает как шарм):

zoom3.addEventListener(MouseEvent.MOUSE_DOWN, dragArea);
zoom3.addEventListener(MouseEvent.MOUSE_UP, dropArea);

function dragArea(e:MouseEvent):void{
var bounds:Rectangle = new Rectangle(
                            stage.stageWidth - zoom3.width, 
                            stage.stageHeight - zoom3.height, 
                            zoom3.width - stage.stageWidth, 
                            zoom3.height - stage.stageHeight
                        );
zoom3.startDrag(false, bounds);
}

function dropArea(e:MouseEvent):void{
zoom3.stopDrag();
}

Теперь уловка в том, что я бы хотел, чтобы карту перетаскивали одновременно с расположенным выше видеоклипом, который содержит названия регионов, городов и т. Д. Оба не могут быть на одном слое, так как мне нужно поместить слой текстуры между ними.

Есть ли простой способ связать оба слоя и заставить их двигаться одновременно?

Надеюсь, я достаточно ясен, английский - мой второй язык. Спасибо за чтение и, возможно, за помощь.

1 Ответ

2 голосов
/ 29 июня 2011

Вы можете:

  • добавьте прослушиватель события enterframe при запуске перетаскивания (удалите его при остановке перетаскивания). отследите разницу в положении с помощью перетаскиваемого фрагмента ролика и примените его ко второму.
  • переопределяет установщики для x и y перетаскиваемого клипа и либо отражает его на перетаскиваемом клипе, либо отправляет событие, которое прослушивает второй мувиклип, и соответственно обновляет

Вариант 1:

private var m_prevX:Number = 0.0;
private var m_prevY:Number = 0.0;

private function dragArea(e:MouseEvent):void
{
    var bounds:Rectangle = ...

    // hold the current x and y so that we can get the difference
    this.m_prevX = zoom3.x;
    this.m_prevY = zoom3.y;

    // add the enterframe listener
    zoom3.addEventListener( Event.ENTER_FRAME, this._onEnterFrame );

    // start dragging
    zoom3.startDrag(false, bounds);
}

private function dropArea(e:MouseEvent):void
{
    zoom3.stopDrag();

    // remove the enter frame listener
    zoom3.removeEventListener( Event.ENTER_FRAME, this._onEnterFrame );
}

// called every frame that we're dragging
private function _onEnterFrame( e:Event ):void
{
    // get the difference in movement
    var diffX:Number = this.m_prevX - zoom3.x;
    var diffY:Number = this.m_prevY - zoom3.y;

    // store the current pos
    this.m_prevX = zoom3.x;
    this.m_prevY = zoom3.y;

    // apply the difference to the other clip
    myOtherClip.x += diffX;
    myOtherClip.y += diffY;
}

** Опция ": ** Более ОО подход. Вам не нужно переопределять x и y, но zoom3 необходимо расширить класс примерно так:

public class DraggableClip extends MovieClip
{
    /******************************************************/

    /**
     * The name of the event that we dispatch when we're being dragged
     * and our position changes
     */
    public static const DRAG_UPDATE_POS:String = "drag_update_pos";

    /******************************************************/

    /**
     * The x difference in position if we're being dragged
     */
    public var dragDiffX:Number = 0.0;

    /**
     * The y difference in position if we're being dragged
     */
    public var dragDiffY:Number = 0.0;

    /******************************************************/

    private var m_prevX:Number = 0.0; // our previous x position
    private var m_prevY:Number = 0.0; // our previous y position

    /******************************************************/

    /**
     * Start dragging the clip. This is dispatch an event when
     * our position changes
     */
    override public function startDrag():void
    {
        // reset the drag difference positions
        this.dragDiffX = 0.0;
        this.dragDiffY = 0.0;

        // hold our current position
        this.m_prevX = this.x;
        this.m_prevY = this.y;

        // add an event listener to that we can track the difference
        // you could also set it to listen to MouseEvent.MOUSE_MOVE if
        // you wanted
        this.addEventListener( Event.ENTER_FRAME, this._onEnterFrame );

        // start dragging
        super.startDrag();
    }

    /**
     * Stop dragging the clip
     */
    override public function stopDrag():void
    {
        // remove the event listener
        this.removeEventListener( Event.ENTER_FRAME, this._onEnterFrame );

        // stop draggin
        super.stopDrag();
    }

    /******************************************************/

    // called every frame we're updating
    private function _onEnterFrame( e:Event ):void
    {
        // get the drag difference
        this.dragDiffX = this.m_prevX - this.x;
        this.dragDiffY = this.m_prevY - this.y;

        // store the current x and y
        this.m_prevX = this.x;
        this.m_prevY = this.y;

        // if our position has changed, dispatch an event
        if( this.dragDiffX != 0.0 && this.dragDiffY != 0.0 )
            this.dispatchEvent( new Event( DraggableClip.DRAG_UPDATE_POS ) );
    }
}

Затем, чтобы прослушать события, примерно так:

private function _init():void
{
    // do your init stuff
    zoom3       = new DraggableClip;
    myOtherClip = new MovieClip;

    // add the event listener to zoom3
    zoom3.addEventListener( DraggableClip.DRAG_UPDATE_POS, this._onDragZoom3 );
}

private function _onDragZoom3( e:Event ):void
{
    // zoom3's position has been changed, update myOtherClip
    myOtherClip.x += zoom3.dragDiffX;
    myOtherClip.y += zoom3.dragDiffY;
}
...