综合以上分析,写出完整代码。在如下代码中,为了让条理清晰,使用了多个数组来归类操作数据,请读者明察:
var linetimer:Timer = new Timer(50, 150);
linetimer.addEventListener("timer", linetimerHandler);
linetimer.addEventListener("timerComplete", animComplete);
//定义三个点
var stoppoint:Array=new Array(3);
stoppoint[0]=new Point(90,120);
stoppoint[1]=new Point(380,310);
stoppoint[2]=new Point(450,70);
//移动动画对象到起始点
LineRunner.x=stoppoint[0].x-LineRunner.width/2;
LineRunner.y=stoppoint[0].y-LineRunner.height/2;
//两点之间的距离计算函数
function dist(point1:Point,point2:Point):Number{
var distance:Number;
var pdx=point1.x-point2.x;
var pdy=point1.y-point2.y;
distance=Math.sqrt( Math.pow(pdx,2)+Math.pow(pdy,2));
return distance;
}
//此数组保存三点之间的距离和总距离
var ary_dist:Array= new Array(4);
ary_dist[1]=dist(stoppoint[0],stoppoint[1]);
ary_dist[2]=dist(stoppoint[1],stoppoint[2]);
ary_dist[3]=dist(stoppoint[2],stoppoint[0]);
//计算三点距离总长
ary_dist[0]=ary_dist[1]+ary_dist[2]+ary_dist[3];
//分别求出个阶段所需要的时长
var ary_sect:Array= new Array(2);
ary_sect[0]=Math.round(ary_dist[1]/ary_dist[0]*linetimer.repeatCount);
ary_sect[1]=Math.round(ary_dist[2]/ary_dist[0]*linetimer.repeatCount);
ary_sect[2]=linetimer.repeatCount-ary_sect[0]-ary_sect[1];
//启动定时器
linetimer.start();
//定时器触发响应
function linetimerHandler(event:TimerEvent):void {
//动画代码编写入口
var i:int=event.target.currentCount;
if(i<=ary_sect[0])
{
//操作从stoppoint[0]到stoppoint[1]
LineRunner.x+=((stoppoint[1].x-stoppoint[0].x)/ary_sect[0]);
LineRunner.y+=((stoppoint[1].y-stoppoint[0].y)/ary_sect[0]);
}
else if(i<=(ary_sect[1]+ary_sect[0]) && i>ary_sect[0])
{
//操作从stoppoint[]到stoppoint[2]
LineRunner.x+=((stoppoint[2].x-stoppoint[1].x)/ary_sect[1]);
LineRunner.y+=((stoppoint[2].y-stoppoint[1].y)/ary_sect[1]);
}
else if(i<=150 && i>(ary_sect[1]+ary_sect[0]))
{
//操作从stoppoint[2]到stoppoint[0]
LineRunner.x+=((stoppoint[0].x-stoppoint[2].x)/ary_sect[2]);
LineRunner.y+=((stoppoint[0].y-stoppoint[2].y)/ary_sect[2]);
}
}
function animComplete(event:TimerEvent):void {
event.target.reset();
event.target..start();
}
运行本例,可以看到对象以均匀的速度在A、B、C三点之间运动。无论两点之间的距离如何,运动速度都保持恒定不变,但是经过两点之间路程的时间是不同的:这样的结果是符合代码预期的。其运动轨迹可以参考图:

372

被折叠的 条评论
为什么被折叠?



