Thursday, December 17, 2009

Drag objects within bounded area in AS3

Dragging MovieClip objects within bounded area in AS3

Step 1) Create a movieClip and give instance name “bound_rect”. We consider the position of the background “bound_rect”. We also consider its dimensions, and your draggable movieclip's dimensions as well here.

Step 2) Create another moiveClip and give instance name “image_container” it’s your draggable movieclip. Import an image into it, It does not matter how big it is.
Give them both proper instance names to work with the code below:

var imgWidth:Number = image_container.width;
var imgHeight:Number = image_container.height;
var rectWidth:Number = bound_rect.width;
var rectHeight:Number = bound_rect.height;
var rectX:Number = bound_rect.x;
var rectY:Number = bound_rect.y;
var boundWidth = rectWidth - imgWidth;
var boundHeight = rectHeight - imgHeight;
var boundsRect:Rectangle = new Rectangle(rectX, rectY, boundWidth, boundHeight);
//
image_container.addEventListener(MouseEvent.MOUSE_DOWN, DragItem);
image_container.addEventListener(MouseEvent.MOUSE_UP, DropItem);
//
function DragItem (event:MouseEvent) {
image_container.startDrag(false, boundsRect);
}
//
function DropItem (event:MouseEvent) {
image_container.stopDrag();
}

No comments:

Post a Comment