================================== ※ 请勿作商业用途 ,如转载,请与作者本人联系。 ※ 有任何问题请EMAIL至: tuliping@tom.com ==================================
效果演示:
随机运动的效果在一些特效里已经司空见惯,大家对random()函数也不陌生,但要得到一个好的效果,你得用心去思量。那么,上面的演示效果如何设置代码呢。 效果简析:
mc在一定的范围内运动,运动的方向是随机的,运动的速率有快有慢,距离有长有短,运动一段随机的距离后停止一定的时间。至于两个按钮的作用很简单,Add Clip按钮用于复制mc,Delete Clip按钮用于删除复制出来的mc。
代码的构建与简析:
//求平面坐标系中两点间的距离 function getdistance(x1, y1, x2, y2) { var a, b; a=x2-x1; b=y2-y1; return (Math.sqrt(a*a+b*b)); }
//运动距离、范围、速率的设置
MovieClip.prototype.chance = function() { width = 400; height = 250; //mc运动范围的设置 var c, d; this.x = this._x; this.y = this._y; //速率、目标位置的随机设置 this.speed = Math.random()*4+2; this.targx = Math.random()*width; this.targy = Math.random()*height; c = _root.getdistance(this.x, this.y, this.targx, this.targy); d = this.speed/c; //mc运动时x、y坐标的增量 this.diffx = (this.targx-this.x)*d; this.diffy = (this.targy-this.y)*d; };
//mc运动及停止时间的设置
MovieClip.prototype.move = function() { //运动的判断 if (_root.getdistance(this.x, this.y, this.targx, this.targy)>this.speed) { this.x += this.diffx; this.y += this.diffy; } else { this.x = this.targx; this.y = this.targy; //停止时间的判断 if (!this.t) { this.t = getTimer(); } if (getTimer()-this.t>1000) { this.chance(); //停止时间大于1秒,调用chance()进行下一次的随机运动 this.t = 0; } } this._x = this.x; this._y = this.y; };
button code: Add Clip button code:
//button instance name :Add Add.onRelease=function(){ n++; _root.mc.duplicateMovieClip("mc" add n ,n); trace(n); }
Delete Clip button code: //button instance name :Delete Delete.onRelease=function(){ if (n>0) { _root["mc"add n].gotoAndPlay(2); n -= 1; trace(n); } }
以上代码都在主场景第一桢。
继续.....,做一MC,第一桢:stop();最后一桢:removeMovieClip(this); stop();具体可以参看原文件。 从库中把这MC拖到主场景,instance name:mc 为其加代码:
onClipEvent(enterFrame){ move(); } 制作结束,Ctrl+enter 就可以观看效果。
++++++细心的朋友可能会发现,MC的碰撞并没有检测,当互相碰撞时MC就停止运动,这样效果会更好一些,这个效果的添加留给你自己去完成了++++++++
download fla:
点击浏览该文件
|