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

In the previous page, we figured out how to drag the circles and stop the drag when the mouse cursor was no longer depressed over the object. What this tutorial is about, the connected lines, will be covered in this page.

Creating the Connected Lines
The code for displaying the lines between the circles is highlighted below:

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();
}
}
init();
//
function drawLine() {
line.clear();
line.lineStyle(10, 0xBFD7EE);
//3->2
line.moveTo(blue4._x, blue4._y);
line.lineTo(blue3._x, blue3._y);
//3->2
line.moveTo(blue3._x, blue3._y);
line.lineTo(blue2._x, blue2._y);
//2->1
line.moveTo(blue2._x, blue2._y);
line.lineTo(blue1._x, blue1._y);
//1->0
line.moveTo(blue1._x, blue1._y);
line.lineTo(blue0._x, blue0._y);
//0->4
line.moveTo(blue0._x, blue0._y);
line.lineTo(blue4._x, blue4._y);
//
updateAfterEvent();
}

Phew - that's a lot of code. Don't worry, it isn't really that bad. Let's take it from the top:


this.createEmptyMovieClip("line", -1);

In the init function, after the for loop, I create a new empty movie clip called line at a depth of -1. This empty movie clip will store our actual lines, and you will see more of it shortly.


drawLine();

In this line, the drawLine function is called. The drawLine function is responsible for creating the lines between the circles, and we want the lines to be drawn immediately after our circles have been displayed. You will learn more about the drawLine method shortly.


this.onMouseMove = function() {
drawLine();
}

This section of code is very similar to the earlier line of code that only contained a call to the drawLine() function. The only difference is that every time the mouse moves, the drawLine function is called.


And now, we enter into the drawLine function. Keep in mind that the drawLine function is called every time the mouse moves, whereas the init function is called only once:

line.clear();

Every time the drawLine function is called, all current lines are cleared from the stage. If you did not clear the lines, any new lines caused by the circles moving would appear next to the old lines. You will have something that looks like the following image:

[ what removing line.clear() will do ]


We have one more page left! So, feel free to take a short break and let's go on to the next page!

Onwards to the next page!

 

1 | 2 | 3 | 4 | 5




SUPPORTERS:

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