Creating Connected Lines - Page 3
       by kirupa | 25 June 2006

In the previous page, you learned about the code responsible for displaying the circles on the stage. In this page, I will explain how to get dragging to work.

Dragging the Circles
The code for dragging the circles is highlighted in the following chunk of code:

function init() {
for (var i:Number = 0; i<5; i++) {
this.attachMovie("blueCircle", "blue"+i, this.getNextHighestDepth());
var mc:MovieClip = this["blue"+i];
mc._x = Math.round(Math.random()*300);
mc._y = Math.round(Math.random()*200);
mc.onPress = function() {
this.startDrag();
};
mc.onRelease = function() {
this.stopDrag();
};
}
this.createEmptyMovieClip("line", -1);
drawLine();
this.onMouseMove = function() {
drawLine();
}
}

The dragging code is basically two parts. The first part initiates the drag, and the second part cancels the drag when you release the mouse. Let's look at the pieces of code that help you do that in greater detail:


mc.onPress = function() {
this.startDrag();
};

The name mc dynamically references the movie clip you recently moved from the library via the this[...] command. Because the reference is almost as good as pointing to an actual movie clip, you have access to the MovieClip class's methods such as onPress event handler.

So, when somebody presses on the mc movieclip, the onPress handler fires and any code contained within it is executed. The code that is executed is:

this.startDrag();

The startDrag() method allows the object (this) to be dragged around wherever your mouse cursor is.


mc.onRelease = function() {
this.stopDrag();
};

This section of code is largely the exact opposite of the section of code explained earlier. When you release your mouse press, the code executes. Instead of initiating the drag behavior, you are stopping the drag instead!


We've covered a lot of ground in the last two pages. In the next page, you will learn about how the connected lines are drawn, and how they remain connected!

Onwards to the next page!

 

1 | 2 | 3 | 4 | 5




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.