Search code examples
actionscript-3flashmouseeventmovieclipstage

Check when a part of the MovieClip leaves the Stage


I'm creating a Drag and Drop game using AS3, i want to check when a apart of a Movieclip is outside the screen to move the View behind and let the user choose where to drop it.

I cant' test if the MovieClip credentials are bigger that the stage (scaleMode = NO_SCALE) Width/Height, because there is a part of the stage that it's hidden behind the browser window.

It's the same aspect as MOUSE_LEAVE just this time it has to be for MovieClips, i tried to see the code behind MOUSE_LEAVE but i couldn't reach it.

Thank You.

MAIN CLASS

[SWF(width='800', height='800',backgroundColor='#CC99FF', frameRate='60')]
public class DragTest extends Sprite
{
    public function DragTest()
    {
        addChild(new World(this));

        this.stage.scaleMode = "noScale";
        this.stage.align = "TL";

        this.graphics.lineStyle(5,0x555555,0.5);
        this.graphics.drawRect(0,0,800,800);
    }
}

WORLD CLASS

public class World extends Container // Container from my SWC
{
    private var _display:Sprite;
    private var _dragPt:Point;
    private var _dragedObject:MovieClip;

    public function World(display:Sprite)
    {
        super();

        _display = display;

        myMC.addEventListener(MouseEvent.MOUSE_DOWN, onPickUp, false, 0, true ); 

        display.stage.addEventListener(MouseEvent.MOUSE_UP, onDrop, false, 0, true ); 
        display.stage.addEventListener(Event.MOUSE_LEAVE, onMouseLeave, false, 0, true ); 
    }

    protected function onMouseLeave(event:Event):void
    {
        trace("Mouse Is Leaving The Stage");

    }

    protected function onDrop(e:MouseEvent):void
    {
        _display.stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMoveObject);

    }   

    private function onPickUp(e:MouseEvent)
    {
        _dragedObject = e.currentTarget as MovieClip;

        _display.stage.addEventListener(MouseEvent.MOUSE_MOVE, onMoveObject, false, 0, true);
    }

    protected function onMoveObject(e:MouseEvent):void
    {
        var point:Point = new Point(_display.stage.mouseX, _display.stage.mouseY);

            (_dragedObject as MovieClip).x = point.x;
            (_dragedObject as MovieClip).y = point.y;           
    }
}

Here is an Example : Simple Code


Solution

  • The easiest approach would probably be to use getBounds(stage) and compare with stageWidth and stageHeight:

    var bounds:Rectangle = _draggedObject.getBounds(stage);
    if (bounds.left < 0) {
        // left part of object is off-screen
    } else if (bounds.right > stage.stageWidth) {
        // right part of object is off-screen
    }
    if (bounds.top < 0) {
        // top part of object is offscreen
    } else if (bounds.bottom > stage.stageHeight) {
        // bottom part of object is off-screen
    }
    

    You could move the display in each of these cases.