Search code examples
actionscript-3drag-and-dropbounding-boxanimate-cc

Preventing MC from leaving stage with bounding rectangle AS3


I have tried many of the suggestions in other posts but cannot get this working fully.

I would like to drag an object around my stage, but I don't want that object to actually leave the stage.

When using the example below, the MC is bound by the top and bottom of the stage, but the left side still swallows up half of the dragged MC, and the right side doesn't allow the MC to get near the edge - it just has blank space (by what looks like the same width that the MC gets dragged outside on the left)

var my_x:int=stage.stageWidth-box_mc.width;
var my_y:int=stage.stageHeight-box_mc.height;

var myWidth:int=0-my_x;
var myHeight:int=0-my_y;

var boundArea:Rectangle=new Rectangle(my_x, my_y, myWidth, myHeight);

box_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
box_mc.addEventListener(MouseEvent.MOUSE_UP, drop);

function drag(event:MouseEvent):void {
    box_mc.startDrag(false,boundArea);
}

function drop(event:MouseEvent):void {
    box_mc.stopDrag();
}

I believe the code is correct, and there must be something I am missing - can someone try this out for me please and point me in the right direction?

Many Thanks,

Chris.


Solution

  • It seems that your registration point is to blame for the behaviour you're experiencing.

    You should use something like:

    var boxArea:Rectangle = box_mc.getBounds(box_mc);
    var boundArea:Rectangle = new Rectangle(-boxArea.x, -boxArea.y, stage.stageWidth-boxArea.width, stage.stageHeight-boxArea.height);
    
    box_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
    box_mc.addEventListener(MouseEvent.MOUSE_UP, drop);
    
    function drag(event:MouseEvent):void {
        box_mc.startDrag(false,boundArea);
    }
    
    function drop(event:MouseEvent):void {
       box_mc.stopDrag();
    }
    

    Basically, in the code above, you get the rectangle size of the box_mc object and deposit it in the boxArea variable and make sure to include its size and the registration point effects to the boundArea calculation.