package { import flash.display.Sprite; import flash.display.*; import flash.utils.*; import flash.geom.Point; import flash.events.TimerEvent; import flash.events.Event; [SWF(backgroundColor="#ffffff", frameRate="24", width="550", height="400")] public class Animation extends Sprite { private const CIRCLE_RADIUS:Number = 20; private var origin:Sprite; public function Animation():void { //create the origin sprite and add it to the stage origin = new Sprite(); origin.x = stage.stageWidth / 2; origin.y = stage.stageHeight / 2; addChild(origin); //create circles createCircles(15, -275, 0, 275, 0); //create a timer so that we can animate var timer:Timer = new Timer(50); timer.addEventListener(TimerEvent.TIMER, timerListener); timer.start(); } //Create a circle drawn at the origin of the shape, but moved to (x, y) //within a sprite, add sprite to stage public function createCircle(x:Number, y:Number):void { var sprite:Sprite = new Sprite(); var circle:Shape = new Shape(); circle.graphics.beginFill(Math.random() * 0xFFFFFF); circle.graphics.drawCircle(0, 0, CIRCLE_RADIUS); circle.x = x; circle.y = y; sprite.addChild(circle); origin.addChild(sprite); } //draw num circles linearly between (x1, y1) and (x2, y2) public function createCircles(num:Number, x1:Number = 0, y1:Number = -200, x2:Number = 0, y2:Number = 200):void { var dx:Number = (x2 - x1) / num; var dy:Number = (y2 - y1) / num; for (var i:int = 0; i < num; i++) { createCircle(dx / 2 + x1 + i * dx, dy / 2 + y1 + i * dy); } } //animate the circles based on their distance from the origin public function timerListener(e:TimerEvent):void { for (var i:int = 0; i < origin.numChildren; i++) { var child:DisplayObject = origin.getChildAt(i); if (i % 2 == 0) { child.rotation += 1000 / getDistance(child); } else { child.rotation -= 1000 / getDistance(child); } } } //given a child of the stage, find its shape object //and return the shapes distance from the origin public function getDistance(spr:DisplayObject):Number { var circle:DisplayObject = (spr as DisplayObjectContainer).getChildAt(0); var p1:Point = new Point(circle.x, circle.y); var p2:Point = new Point(0, 0); return Point.distance(p1, p2); } } }