-
// line thickness, line color, start point, end point, divisor, callback
-
function animateLineTo( thick:Number, col:uint, sp:Point, ep:Point, div:Number=4, callback:Function=null):void {
-
var s:Shape = Shape(addChild(new Shape()));
-
var ap:Point = sp.clone();
-
div = Math.max(2, div);
-
setTimeout(runLineAnimation, 1000/stage.frameRate, s.graphics , thick , col , sp , ep , ap, div, callback);
-
}
-
-
function runLineAnimation(g:Graphics , thick:Number, col:uint, sp:Point, ep:Point, ap:Point, div:Number, callback:Function):void {
-
ap.x += (ep.x - ap.x) / div;
-
ap.y += (ep.y - ap.y) / div;
-
with(g){
-
clear();
-
lineStyle(thick, col);
-
moveTo(sp.x, sp.y);
-
lineTo(ap.x, ap.y);
-
}
-
if (Math.abs(ap.x - ep.x) <1 && Math.abs(ap.y- ep.y) <1){
-
// done
-
if (callback!=null){
-
callback();
-
}
-
}else{
-
setTimeout(runLineAnimation, 1000/stage.frameRate, g , thick , col , sp , ep , ap, div, callback);
-
}
-
}
-
//
-
// test out the animateLineTo function:
-
//
-
var a:Point = new Point(100,100);
-
var b:Point = new Point(150, 200);
-
var c:Point = new Point(300, 190);
-
var d:Point = new Point(280, 90)
-
-
animateLineTo(0, 0xFF0000, a, b, 4, line2);
-
-
function line2():void{
-
animateLineTo(0, 0xFF0000, b, c, 4, line3);
-
}
-
-
function line3():void{
-
animateLineTo(0, 0xFF0000, c, d, 4, line4);
-
}
-
-
function line4():void{
-
animateLineTo(0, 0xFF0000, d, a, 4);
-
}
The above demos a function called animateLineTo() that will draw a line using zeno's paradox.
There are a couple weird/interesting tricks going on here. I'm using setTimeout() over and over rathaer than using setInterval(). This makes it so I don't need to store an interval id. I'm also using a delay of 1000/stage.frameRate, this attempts to cause the setTimeout() to run at the same frequency as an enter frame would. This is important because having a setTimeout()/setInterval() that is doing animation and attempting to run more frequently than the framerate can cause problems and is a waste of cpu power.
This snippet was spurned by a student question about how to animate a Graphics.lineTo() from point A to point B. Here is the original snippet, which is easier to read and more bare bones:
-
var p0:Point = new Point(100,100);
-
var p1:Point = new Point(400,200);
-
var dp:Point = new Point(p0.x,p0.y);
-
-
var s:Sprite = Sprite(addChild(new Sprite()));
-
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
s.graphics.clear()
-
s.graphics.lineStyle(0,0x000000);
-
s.graphics.moveTo(p0.x, p0.y);
-
s.graphics.lineTo(dp.x, dp.y);
-
dp.x += (p1.x - dp.x) / 4;
-
dp.y += (p1.y - dp.y) / 4;
-
}