Tuesday, 20 January 2009

AS 3 Startdrag with co-ordinates

The drag and drop functionality is a inevitable functionality which a flash programmer can't avoid. The startDrag() function however has undergone a simple modification in the latest version which gives a bit trouble to lots of programmers who have used the earlier version.

The AS3 startDrag was different from the previous version(in the parameter specification). The AS3 start drag require two parameters the first parameter is a Boolean value for lock center(same as previous versions), the second parameter is a rectangle object which specify the bound/co-ordinates. The Rectangle bound area has to be created with four parameters(1st two or x,y and later two or width and height) which specify the bounding area which is some how similar to the AS2.


You can use the following generic code in two different scenarios either your drag object is smaller than the stage size or even if it is larger than the stage size.


//manually defining the stagewidth and height
//you can use stage.stageWidth and stage.stageHeight

var stagWit=550;
var stagHit=400;

//fn to drag the mc
//the movieclip used have the registration point @ left top..
//this method is ideal when the drag object is smaller than stage as well as when the drag object is larger than stage//dragable area..
function startMoveDrag(event:MouseEvent):void {
var left:Number=stagWit-drag.width;
var top:Number=stagHit-drag.height;

var right:Number=0;
var bottom:Number=0;

var myWidth:Number=right-left;
var myHeight:Number=bottom-top;

//create the rectangle using the above co-ordinates
var boundRect:Rectangle=new Rectangle(left,top,myWidth,myHeight);

//create the drag funcction
drag.startDrag(false,boundRect);
}
function stopMoveDrag(event:MouseEvent):void {
drag.stopDrag();
}

stage.addEventListener(MouseEvent.MOUSE_DOWN,startMoveDrag);
stage.addEventListener(MouseEvent.MOUSE_UP,stopMoveDrag);


Search terms:
startDrag second parameter
startDrag AS3 not working
How to define startDrag AS 3 actionscript 3.0
startDrag parameter
startDrag rectangle problem

3 comments:

  1. how can I bound my object not to drag outside stage?? any idea?

    ReplyDelete