//把你舞台上的MC实例名放入数组,测试 var ballA:Array = [ball1, ball2, ball3, ball4, ball5]; //随机初始化每个MC的运动速度和方向 for (var i = 0; i<ballA.length; i++) { ballA.dx = 11*rand1_1(); ballA.dy = 7*rand1_1(); } //随机产生1或-1 function rand1_1():Number { return random(2) ? -1 : 1; } Stage.scaleMode = "noScale"; Stage.align = "TL"; var sw:Number = Stage.width; var sh:Number = Stage.height; var stageListener:Object = new Object(); //舞台大小改变时,重置sw、sh stageListener.onResize = function() { sw = Stage.width; sh = Stage.height; }; Stage.addListener(stageListener); onEnterFrame = function () { for (var i = 0; i<ballA.length; i++) { //检测所有MC之间是否有碰撞,有就根据情况改变“增量”方向 for (var j = i+1; j<ballA.length; j++) { if (ballA.hitTest(ballA[j])) { mc12(ballA, ballA[j]); ballA._x += ballA.dx; ballA[j]._x += ballA[j].dx; ballA._y += ballA.dy; ballA[j]._y += ballA[j].dy; } } //如果到了边界,就反射 if ((ballA._x<ballA._width/2 && ballA.dx<0) or (ballA._x>sw-ballA._width/2 && ballA.dx>0)) { ballA.dx *= -1; } if ((ballA._y<ballA._height/2 && ballA.dy<0) or (ballA._y>sh-ballA._height/2 && ballA.dy>0)) { ballA.dy *= -1; } //移动一个“增量” ballA._x += ballA.dx; ballA._y += ballA.dy; } }; //碰撞函数,根据两球碰撞方向和自身运动方向合成新的增量值 function mc12(mc1:MovieClip, mc2:MovieClip) { var ang:Number = Math.atan2(mc2._y-mc1._y, mc2._x-mc1._x); var ang1:Number = Math.atan2(mc1.dy, mc1.dx); var ang2:Number = Math.atan2(mc2.dy, mc2.dx); var r1:Number = (mc1.dy/Math.sin(ang1))*Math.cos(ang-ang1); var r2:Number = (mc2.dy/Math.sin(ang2))*Math.cos(ang-ang2); var dx1:Number = r1*Math.cos(ang)+r2*Math.cos(ang); var dy1:Number = r1*Math.sin(ang)+r2*Math.sin(ang); mc1.dx = -mc1.dx+dx1; mc1.dy = -mc1.dy+dy1; mc2.dx = -mc2.dx+dx1; mc2.dy = -mc2.dy+dy1; }
|