Next, we will make the movie clip instance being dragged "snap back" to its origin when it is dropped. At first, this will happen unconditionally. Later we will program it to snap back only if the user didn't drop it where they were supposed to.
To accomplish this, we introduce two more new variables, both of the Number type (I always use the Number type for screen locations, as everything is not always located on an even pixel). One variable is for recording the x location, and the other, the y location, of the movie clip being dragged. We will call these variables startX and startY. No special significance to these names, I just made them up, but you always want descriptive names. You might be inclined to think that you would need a set of variables like this for each movie clip instance, or that they should even have those as properties. But since only one clip can be dragged at a time, they can just all share these two variables.
The strategy is to just simply record the starting position of the movie clip that gets the MOUSE_DOWN event. Therefore, inside the MOUSE_DOWN event handler is where we are going to record values for these variables. We don't even need to worry in our programming about what the actual numbers are, or where any movie clips are positioned. Whatever that position is, it gets recorded when the user mouses down on it. This also allows us to move them around at will when we are authoring the fla file, and the code will still work.
Here is the new code with startX and startY added in:
var dragArray:Array = [square, circle, triangle];
var currentClip:MovieClip;
var startX:Number;
var startY:Number;
for(var i:int = 0; i < dragArray.length; i++) {
dragArray[i].buttonMode = true;
dragArray[i].addEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDown);
}
function item_onMouseDown(event:MouseEvent):void {
currentClip = MovieClip(event.currentTarget);
startX = currentClip.x;
startY = currentClip.y;
addChild(currentClip); //bring to the front
currentClip.startDrag();
stage.addEventListener(MouseEvent.MOUSE_UP, stage_onMouseUp);
}
function stage_onMouseUp(event:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_UP, stage_onMouseUp);
currentClip.stopDrag();
currentClip.x = startX;
currentClip.y = startY;
}
And here is how the swf now behaves:
When you release the mouse button, the movie clip instances "snap back" to where they started from. On the next page, we will introduce conditional logic. The clip will only snap back to its origin if the user doesn't drop it where we think they should.