package { import flash.display.Sprite; import flash.events.Event; public class Boxes extends Sprite { private var box:Box; private var boxes:Array; private var gravity:Number=0.1; public function Boxes() { init(); } private function init():void { boxes = new Array(); createBox(); addEventListener(Event.ENTER_FRAME, onEnterFrame); } private function onEnterFrame(event:Event):void { box.vy+=gravity; box.y+=box.vy; //如果物体下落到了舞台(最下)边界,则再造一个出来往下掉 if (box.y+box.height/2>stage.stageHeight) { box.y=stage.stageHeight-box.height/2; createBox(); } else{ for (var i:uint = 0; i < boxes.length; i++) { //每个正在下掉的物体与其它物体做(矩形)碰撞检测 if (box!=boxes[i]&&box.hitTestObject(boxes[i])) { box.y=boxes[i].y-boxes[i].height/2-box.height/2; //堆到顶了,则停止 if (box.y<=box.height/2){ removeEventListener(Event.ENTER_FRAME,onEnterFrame); } else{ createBox(); } } } } } private function createBox():void { box=new Box(Math.random()*40+10,Math.random()*40+10,Math.random()*0xffffff); box.x=Math.random()*stage.stageWidth; addChild(box); boxes.push(box); } } }