Recipe 11.13. Constraining Drag-and-Drop AreasProblemYou want to allow a movie clip to be draggable only within a certain region. SolutionUse the optional parameters for the startDrag( ) method to specify a region over which the movie clip can be dragged. DiscussionBy default, draggable movie clips can be moved anywhere on the stage. However, there are many situations in which you may want to define an area in which a movie clip can be dragged. Two examples of this include:
Fortunately, ActionScript makes it relatively simple to define a draggable area for your movie clips. In Recipe 11.12 you can read about how to use the startDrag( ) method in a basic way to create draggable movie clips. However, in addition to the optional Boolean parameter that determines whether the movie clip snaps to the pointer, the startDrag( ) method also accepts four more optional parameters. These four additional parameters determine the rectangular area over which the movie clip can be dragged by defining the left, top, right, and bottom coordinate values. The coordinates should be given as values within the movie clip instance's parent. For example, if you have a movie clip instance in the main timeline named mClip, and you want that movie clip to be draggable only within a rectangle in which the left edge is where x is 10, the top edge is where y is 30, the right edge is where x is 150, and the bottom edge is where y is 300, your code might look like this: mClip.startDrag(true, 10, 30, 150, 300); In the preceding example, the snap to parameter is true, which means that the movie clip will snap to the mouse pointer. Also, if the preceding code is placed on a keyframe of the main timeline, the movie clip would automatically begin following the mouse pointer as soon as the playhead entered that frame. But instead of following the mouse pointer anywhere on stage, it will follow the pointer within the rectangular area you have defined. If, instead, you want the movie clip to be draggable within that region only when the user clicks and drags it, the code should be placed within an onPress( ) event handler method, and the accompanying stopDrag( ) method should be placed within an onRelease( ) event handler method. Notice that the stopDrag( ) method still does not require any parameters, even when you use it to stop a drag action within a region. mClip.onPress = function():Void { this.startDrag(true, 10, 30, 150, 300); }; mClip.onRelease = function():Void { this.stopDrag(); }; |
Tripod >> 3pod Tips & Learning and manuals for educations