<< Chapter < Page Chapter >> Page >
Listing

Source code for the class named driver.

/*Project LighteningStorm01 This project is the culmination of several previousprojects dealing with animation, sound, transparency, mouse events, chromakey, etc.When the program starts running, the scene is of a very stormy day. There is a button in the upper-left cornerof the scene. The clouds are moving. There is also a yellow moon behind the clouds that is moving veryslowly across the screen from left to right. When the user clicks the button, a bolt of lighteningcomes out of the sky and strikes an image of a tree. Several aspects of the scene change to reflectthe sights and sounds of a lightening strike. In addition to the clouds moving, the overall colorof the scene slowly changes randomly. The overall color varies around a dark cyan when there is nolightening bolt and varies around a dark yellow when there is a lightening bolt.This project was developed using FlashDevelop, which has a couple of requirements that may not exist withFlex Builder 3 or Flash Builder 4. 1. You must manually copy all mp3 files into the binfolder. 2. You must insert an extra slash character in the URLwhen embedding an image file in the swf file. *********************************************************/package CustomClasses{ import flash.display.Bitmap;import flash.display.BitmapData; import flash.media.SoundChannel;import mx.containers.Canvas; import mx.controls.Image;import mx.controls.Button; import mx.events.FlexEvent;import flash.events.TimerEvent; import flash.events.MouseEvent;import flash.utils.Timer; import flash.utils.ByteArray;import flash.media.Sound; import flash.net.URLRequest;import flash.media.SoundChannel; import flash.events.Event;import flash.geom.Rectangle;//====================================================//public class Driver extends Canvas { //Extending Canvas makes it possible to position// images with absolute coordinates. The default // location is 0,0;private var bkgndColor:uint = 0x005555;private var redBkgnd:uint = 0; private var greenBkgnd:uint = 128;private var blueBkgnd:uint = 128;private var normalSky:Image = new Image(); private var flippedSky:Image = new Image();private var tree:Image = new Image();private var newTreeImage:Image = new Image(); private var treeBitMap:Bitmap;private var alphaLim:Number = 0.5;private var normalAlpha:Number = alphaLim; private var flippedAlpha:Number;private var normalAlphaDecreasing:Boolean = true; private var canvasObj:Canvas;private var timer:Timer = new Timer(35); private var loopCntr:uint;private var lighteningCntr:uint = 0;private var lighteningCntrLim:uint = 25; private var lighteningStartX:uint;private var lighteningStartY:uint; private var lighteningEndX:uint;private var lighteningEndY:uint;private var sizzle:Sound; private var thunder:Sound;private var wind:Sound; private var rain:Sound;private var sizzlePlaying:Boolean = false;private var channel:SoundChannel;private var button:Button;private var radius:Number = 24;//radius of circle private var circleX:Number = 5 * radius;private var circleY:Number = 1.5 * radius; private var dx:Number = 0.05;//--------------------------------------------------//public function Driver(){//constructor //Make this Canvas visible.bkgndColor = (redBkgnd<<16) + (greenBkgnd<<8) + blueBkgnd;setStyle("backgroundColor", bkgndColor); setStyle("backgroundAlpha",0.5);//Load the two sky images and embed them in the // swf file.//Note the use of a / to eliminate the "Unable to // resolve asset for transcoding" Compiler Error[Embed("/normalsky.jpg")] var imgNormal:Class;normalSky.load(imgNormal);[Embed("/flippedsky.jpg")] var imgFlipped:Class;flippedSky.load(imgFlipped);//Load the . treeImage and embed it in the swf file. [Embed("/tree.png")]var imgTree:Class; tree.load(imgTree);//Load sound files and play two of them. sizzle = new Sound();sizzle.load(new URLRequest("sizzle.mp3"));thunder = new Sound(); thunder.load(new URLRequest("thunder.mp3"));wind = new Sound();wind.load(new URLRequest("wind.mp3")); wind.play(0,2);//play twicerain = new Sound();rain.load(new URLRequest("rain.mp3")); rain.play(0, int.MAX_VALUE);//play forever//Register an event listener on the CREATION_ // COMPLETE event.this.addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);//Save a reference to this Canvas object, which will // be used later for a variety of purposes.canvasObj = this;//Draw a yellow filled circle on this Canvas object.graphics.beginFill(0xffff00); graphics.drawCircle(circleX,circleY,radius);graphics.endFill();} //end constructor //--------------------------------------------------////This handler method is executed when the Canvas has // been fully created.private function creationCompleteHandler( event:mx.events.FlexEvent):void{//Set the width and height of the Canvas object// based on the size of the bitmap in the // normalSky image.this.width = Bitmap(normalSky.content).width; this.height = Bitmap(normalSky.content).height;//Add the images to the Canvas object. Note that// the two images are overlaid at 0,0. this.addChild(normalSky);this.addChild(flippedSky);//Add a button at in the upper-left corner in front // of the sky images.button = new Button(); button.x = 10;button.y = 10; button.addEventListener(MouseEvent.CLICK, onClick);button.label = "Click Me"; button.setStyle("color", 0xFFFF00);addChild(button);//Get and save a reference to a Bitmap object// containing the contents of the tree file. treeBitMap = Bitmap(tree.content);//Place the treeBitMap in a new Image object and// place it on the canvas near the bottom center of // the canvas.treeBitMap.x = canvasObj.width / 2 - treeBitMap.width/2;treeBitMap.y = canvasObj.height - treeBitMap.height; newTreeImage.addChild(treeBitMap);this.addChild(newTreeImage);//Make the tree almost invisible. It will be made // highly visible in conjunction with a// lightening flash. newTreeImage.alpha = 0.2;//Cause the blue background of the tree to// be transparent. processChromaKey(treeBitMap);//Register a timer listener and start the timer// running. timer.addEventListener(TimerEvent.TIMER, onTimer);timer.start(); } //end creationCompleteHandler//--------------------------------------------------////TimerEvent handler. This method is executed each // time the timer object fires an event.public function onTimer(event:TimerEvent):void {//Update the loop counter. Several things depend on // this counter.loopCntr++; if (loopCntr>int.MAX_VALUE-2) { //Guard against numeric overflow.loopCntr = 0; }//end if//Play a wind sound every 100th timer event only// if a random value is greater than 0.5. This // should happen half the time on the average.if ((loopCntr % 100 == 0)&&(Math.random()>0.5)) { wind.play();}//end if//Make random changes to the background color. processBackgroundColor();//Make changes to the alpha values of the normal// and flipped sky images. makeTheCloudsMove();//Draw a filled circle on this Canvas object.if (!sizzlePlaying) { //Erase the circle. Note that this would also// erase the lightening bolt if it were done while // the sizzle sound is playing.graphics.clear(); }//end if//Make the circle move a very small distance to the// right. Make it wrap and reappear on the left //when it reaches the right side of the window.circleX += dx; if (circleX>canvasObj.width - radius) { circleX = 5 * radius;}//end if graphics.beginFill(0xffff00);graphics.drawCircle(circleX,circleY,radius); graphics.endFill();}//end onTimer//--------------------------------------------------////This function processes the background color. The // color changes among various shades of cyan when// there is no lightening bolt. The color changes // among various shades of dark yellow when there is a// lightening bolt. private function processBackgroundColor():void {if (!sizzlePlaying) { //Vary background color when there is no// lightening flash. if (Math.random()>0.5) { if (greenBkgnd<250){ greenBkgnd += 5;}//end if }else {if(greenBkgnd>5){ greenBkgnd -= 5;}//end if }//end elseif (Math.random()>0.5) { if (blueBkgnd<250){ blueBkgnd += 5;}//end if }else {if(blueBkgnd>5){ blueBkgnd -= 5;}//end if }//end else}else {//Vary background color during a lightening flash if (Math.random()>0.5) { if (greenBkgnd<245){ greenBkgnd += 10;}//end if }else {if(greenBkgnd>10){ greenBkgnd -= 10;}//end if }//end elseif (Math.random()>0.5) { if (redBkgnd<245){ redBkgnd += 10;}//end if }else {if(redBkgnd>10){ redBkgnd -= 10;}//end if }//end else}//end else bkgndColor = (redBkgnd<<16) + (greenBkgnd<<8) + blueBkgnd;setStyle("backgroundColor", bkgndColor); setStyle("backgroundAlpha",0.5);}//end processBackgroundColor //--------------------------------------------------////This function processes the alpha values of the// normal and flipped sky images. // The change in alpha values of the overlapping// images makes it appear that the clouds are // moving.private function makeTheCloudsMove():void {//Change the decreasing or increasing direction of // the changes in the alpha value for the normal// sky image when the alpha value hits the limits. if (normalAlphaDecreasing&&(normalAlpha<= 0.1)) { normalAlphaDecreasing = false;}else if (!normalAlphaDecreasing&&(normalAlpha>= alphaLim)) { normalAlphaDecreasing = true;}//end if //Increase or decrease the alpha value for the// normal sky image. if (normalAlphaDecreasing) {normalAlpha -= 0.005; }else {normalAlpha += 0.005; }//end else//Cause the alpha value for the flipped sky image // to go down when the value for the normal sky// image goes up, and vice versa. flippedAlpha = alphaLim - normalAlpha;//Change the alpha values for both sky images.normalSky.alpha = normalAlpha; flippedSky.alpha = flippedAlpha;}//end makeTheCloudsMove //--------------------------------------------------////This function creates a flash of lightening. It// also makes the tree more visible during // the flash and plays a sizzle sound followed by a// clap of thunder. This method simply initiates these // actions. They are completed later by an event// handler registered on the SoundChannel object. private function flashLightening():void {//Make the tree more visible. Apparently// setting the alpha property has no effect on the // alpha byte values that have been individually// set. Otherwise, the blue background would // become visible.newTreeImage.alpha = 1.0;//Play a sizzle sound to accompany the flash of // lightening. Set a flag to prevent another sizzle// sound from being played before this one finishes. sizzlePlaying = true;channel = sizzle.play(); //Register an event listener that will be called// when the sizzle sound finishes playing. channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);//Change the background color to a dark yellow. redBkgnd = 128;greenBkgnd = 128; blueBkgnd = 0;}//end flashLightening//--------------------------------------------------////This method is called each time the sizzle sound // finishes playing. Each time it is called, it plays// a thunder sound and clears a flag making it // possible for another sizzle sound to be played. It// also restores the background color to a dark cyan, // erases the lightening bolt, and causes the tree to// become almost invisible. private function soundCompleteHandler(e:Event):void {//Allow another sizzle sound to be played now that// this one is finished. sizzlePlaying = false;//Play the thunder immediately following the end of // the sizzle sound.thunder.play();//Switch the background color from dark yellow // to the normal background color.redBkgnd = 0; greenBkgnd = 128;blueBkgnd = 128;//Erase the lightening bolt. Note that this will // also erase the yellow circle.canvasObj.graphics.clear(); //Make the tree almost invisible.newTreeImage.alpha = 0.2;}//end soundCompleteHandler //--------------------------------------------------////This method draws a yellow segmented lightening// bolt that is generally random but always ends up // at the location where the tree is standing.private function drawLightening():void {lighteningStartX = Math.floor(Math.random() * canvasObj.width / 3)+ canvasObj.width / 3; lighteningStartY =Math.random() * canvasObj.height / 10; lighteningEndX = canvasObj.width / 2 -6; lighteningEndY =canvasObj.height - treeBitMap.height + 10;//Draw a zero width dark yellow line to the starting // point of the lightening bolt.canvasObj.graphics.lineStyle(0, 0x999900); canvasObj.graphics.lineTo(lighteningStartX, lighteningStartY);//Set the line style to a bright yellow line that is // four pixels thick.canvasObj.graphics.lineStyle(4, 0xFFFF00);//Declare working variables. var tempX:uint;var tempY:uint = lighteningStartY; var cnt:uint;//Use a for loop to draw a lightening bolt with// twenty random segments. for (cnt = 0; cnt<20; cnt++ ) { //Compute the coordinates of the end of the next// line segment. tempX = Math.floor(Math.random()* canvasObj.width / 3) + canvasObj.width / 3;tempY = tempY + Math.floor(Math.random() * (lighteningEndY - tempY)/5);//Draw the line segment. canvasObj.graphics.lineTo(tempX,tempY);}//end for loop//Draw a line segment to the top of the tree. canvasObj.graphics.lineTo(lighteningEndX, lighteningEndY);//Make the lightening go to ground. canvasObj.graphics.lineTo(lighteningEndX, lighteningEndY + treeBitMap.height - 20);}//end drawLightening //--------------------------------------------------////This method is a click handler on the button. It// causes the lightening flash to occur and the // lightening bolt to be drawn.private function onClick(event:MouseEvent):void { //Don't create another lightening bolt while the// previous one is still in progress. if(!sizzlePlaying){flashLightening(); drawLightening();}//end if }//end onClick//--------------------------------------------------////This method identifies all of the pixels in the // incoming bitmap with a pure blue color and sets// the alpha bytes for those pixels to a value of // zero. Apparently those bytes are not affected by// later code that sets the alpha property of the // Image object to another value.private function processChromaKey(bitmap:Bitmap):void{ //Get the BitmapData object.var bitmapData:BitmapData = bitmap.bitmapData; //Get a one-dimensional byte array of pixel data// from the bitmapData object. Note that the // pixel data format is ARGB.var rawBytes:ByteArray = new ByteArray(); rawBytes = bitmapData.getPixels(new Rectangle(0,0,bitmapData.width,bitmapData.height));var cnt:uint; var red:uint;var green:uint; var blue:uint;for (cnt = 0; cnt<rawBytes.length; cnt += 4) { //alpha is in rawBytes[cnt]red = rawBytes[cnt + 1];green = rawBytes[cnt + 2];blue = rawBytes[cnt + 3];if ((red == 0)&&(green == 0 )&&(blue == 255)) {//The color is pure blue. Set the value // of the alpha byte to zero.rawBytes[cnt] = 0;}//end if }//end for loop//Put the modified pixels back into the bitmapData // object.rawBytes.position = 0;//this is critical bitmapData.setPixels(new Rectangle(0,0,bitmapData.width,bitmapData.height), rawBytes);} //end processChromaKey method//--------------------------------------------------// } //end class} //end package

Miscellaneous

This section contains a variety of miscellaneous materials.

Housekeeping material
  • Module name: Combining Sound with Motion and Image Animation
  • Files:
    • ActionScript0170\ActionScript0170.htm
    • ActionScript0170\Connexions\ActionScriptXhtml0170.htm
PDF disclaimer: Although the Connexions site makes it possible for you to download a PDF file for thismodule at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should beaware that some of the HTML elements in this module may not translate well into PDF.

-end-

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Object-oriented programming (oop) with actionscript. OpenStax CNX. Jun 04, 2010 Download for free at http://cnx.org/content/col11202/1.19
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Object-oriented programming (oop) with actionscript' conversation and receive update notifications?

Ask