///////////////////////////////////////////////////////////////////////////// // // Copyright 2009 Craig Simpson // Some rights reserved.Your reuse is governed by the Creative // Commons Attribution 3.0 United States License // //////////////////////////////////////////////////////////////////////////////// package net.craigsimpson.animation { import flash.display.Sprite; import flash.events.Event; import flash.geom.Rectangle; import net.craigsimpson.physics.Wind; import net.craigsimpson.physics.GRAVITY; public class Float extends Sprite { //-------------------------------------- // PRIVATE VARIABLES //-------------------------------------- private var xAngle:Number = 0; private var yAngle:Number = Math.PI/2; private var xRange:Number; private var yRange:Number; private var xOscVel:Number; private var yOscVel:Number; private var xCenter:Number; private var yCenter:Number; protected var wind:Wind; protected var boundary:Rectangle; protected var airResitance:Number = 8.8; //-------------------------------------- // CONSTRUCTOR //-------------------------------------- /** * @constructor */ public function Float(wind:Wind) { super(); this.wind = wind; visible = false; addEventListener(Event.ENTER_FRAME, onEnterFrame); addEventListener(Event.ADDED_TO_STAGE, onAddedToStage); } //Private Functions// private function onAddedToStage(event:Event):void { removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); boundary = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight ); x = Math.random() * boundary.width; y = Math.random() * boundary.height; resetProperties(); } private function onEnterFrame(event:Event):void { enterFrame(); deltaX(); deltaY(); checkBoundaries(); } private function deltaX():void { x = xCenter + Math.cos( xAngle ) * xRange; xCenter += wind.velocityX; xAngle += xOscVel; } private function deltaY():void { y = yCenter + Math.sin( yAngle ) * yRange; yCenter += GRAVITY.EARTH - airResitance - wind.velocityY; yAngle += yOscVel; } private function checkBoundaries():void { if( x > boundary.width + width ) { xAngle = Math.PI; x = 0 - width; xCenter = 0 + xRange - width; } else if ( x < -1 * width ) { xAngle = 0; x = boundary.width + width; xCenter = boundary.width - xRange + width; } if( y > boundary.height + height ) { x = Math.random() * boundary.width; y = -1 * height; yAngle = Math.PI; resetProperties(); } visible = true; } private function resetProperties():void { xOscVel = Math.random()* 0.025; yOscVel = Math.random()* 0.025; xRange = Math.random() * 25; yRange = Math.random() * 25; xCenter = x; yCenter = y; } protected function enterFrame():void { // override this method. } public function remove():void { removeEventListener(Event.ENTER_FRAME, onEnterFrame); removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); parent.removeChild(this); } } }