top of page
Writer's pictureperiyanayagam24

Limit drag and drop in AS3



I previously created a drag and drop tutorial in Actionscript 3 where you could freely drag the object around the stage area. However, this means the object can also get dragged beyond the stage boundaries. In this tutorial you will learn how to limit the draggable object within the stage boundaries which will stop the object once it has reached the stage edges. You will need to have completed the previous tutorial before attempting this one as there are some minor additions to the startDrag() method.

In Actionscript 2 the startDrag() method contains five parameters, and now in Actionscript 3 there are only two parameters. The first parameter locks the centre value and the second parameter is the bounding area where you have to pass an instance of the Rectangle class to the method. The rectangle bounding area has to have four parameters which are: x, y, width, and height. For more information, checkout the AS3 startDrag() reference here.

Limit drag and drop in Actionscript 3 

Step 1 

Open up the drag and drop tutorial in Actionscript 3.

Step 2 

On the timeline select the Actions layer then open the actions panel (F9) and make the following adjustments.

//The x & y coordinates of the top-left corner of the rectangle. var my_x:int=stage.stageWidth-sheep_mc.width; var my_y:int=stage.stageHeight-sheep_mc.height;

//The height and width of the rectangle. var myWidth:int=0-my_x; var myHeight:int=0-my_y;

//Create a new instance of the rectangle class with the coordinates above. var boundArea:Rectangle=new Rectangle(my_x, my_y, myWidth ,myHeight);

//Adds the mouse down and up event listeners to the sheep movie clip. sheep_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag); sheep_mc.addEventListener(MouseEvent.MOUSE_UP, drop);

//This function drags the sheep but limits to the stage boundaries. function drag(event:MouseEvent):void { sheep_mc.startDrag(false,boundArea); }

//This function releases the sheep object. function drop(event:MouseEvent):void { sheep_mc.stopDrag(); }

Step 3 

Test your movie clip Ctrl + Enter. Try moving the object around and you should notice it will not go over the stage boundaries.

17 views0 comments

Recent Posts

See All

Comments


bottom of page