This tutorial is on a project made by my friend Peter Blaho(warloxk@gmail.com)
The message board will be dyanmic in the sense that it will load the text from an external XML file.
To start hit Ctrl+J to bring up the Document properties window. Set the width to 400 pixels and the heigh to 60. Set any background color.It won't be visible
Draw a 400x60 Rectangle with the color #F4EED4. Align its centre so that it completely covers the stage.
Create a new layer and name it Actions.
Now Hit Ctrl+F8 to bring up the New Symbol window. Set its name to trigger_left and select Export For Actionsript.Go to the Color Window and set the type to Linear.Set the color of the left end color marker to #F4EED4 and alpha to 100%. Set the right one to #F4EED4 and this time the alpha to 0%.
Draw a 60x60 square and go to the Align panel to align the left edge. It should look like this
Now repeat the same process but instead of the left orientaion, it should be right. Set the name as trigger_right. This should look like this
Open the New Symbol window again and set the name to trigger_bottom. Remember to select Export For Actionscript. Draw a 300x60 rectangle of any color. Align its centre and set its alpha to 0.
Now select the first frame of the Actions Layer and copy and paste the following code
//////////////////////////////////////////////
// FlashVars
var flash_vars:Array = new Array();
var keyStr:String;
var valueStr:String;
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
for (keyStr in paramObj) {
valueStr = String(paramObj[keyStr]);
flash_vars[keyStr] = valueStr;
}
//////////////////////////////////////////////
var text_array:Array = new Array();
var curr_text_id:int = 0;
var text_speed:int = 2;
var text_speed_s:int = text_speed;
var margin:int = 10;
////////////////////////////////////////////////
var myTextField:TextField = new TextField();
addChild(myTextField);
var myFormat:TextFormat = new TextFormat();
var trigger_left_t:trigger_left = new trigger_left;
trigger_left_t.x = 0;
trigger_left_t.y = 30;
addChild(trigger_left_t);
var trigger_bottom_t:trigger_bottom = new trigger_bottom;
trigger_bottom_t.x = 200;
trigger_bottom_t.y = 30;
addChild(trigger_bottom_t);
var trigger_right_t:trigger_right = new trigger_right;
trigger_right_t.x = 400;
trigger_right_t.y = 30;
addChild(trigger_right_t);
////////////////////////////////////////////////
////////////////////////////////////////////////
// load xml
var xml_loader:URLLoader; //the xml loader
flash_vars['xml_path'] = 'message.xml';
//loadXML(flash_vars['xml_path'] + "?ticker=" + Math.random() * 1.000000E+010); //load the xml
loadXML(flash_vars['xml_path']); //load the xml
function loadXML(Uri:String):void {
xml_loader = new URLLoader();
xml_loader.addEventListener(Event.COMPLETE, on_complete);
xml_loader.addEventListener(IOErrorEvent.IO_ERROR, on_error);
xml_loader.load(new URLRequest(Uri));
}
////////////////////////////////////////////////
function on_error(evt:ErrorEvent):void {
trace("cannot load xml file");
}
function on_complete(evt:Event):void {
text_array = get_xml_data(xml_loader.data.toString());
myTextField.htmlText = text_array[curr_text_id].msg;
myTextField.width = 0;
myTextField.x = 400 + margin;
myTextField.y = 16;
myTextField.selectable = false;
myTextField.autoSize = TextFieldAutoSize.LEFT;
myFormat.color = 0x000000;
myFormat.size = 24;
myTextField.setTextFormat(myFormat);
}
function get_xml_data(XMLData:String):Array {
var menuXML:XML = new XML(XMLData);
//just in case
menuXML.ignoreWhitespace = true;
//get XML item's entrys
var XMLItems = menuXML.descendants("core");
//load all items into an array
var itemsArray:Array = new Array();
var itemObj:Object;
for(var i in XMLItems) {
itemObj=new Object();
itemObj.msg = str_replace('[', '<', str_replace(']', '>', XMLItems[i].@msg));
itemObj.msg_link = XMLItems[i].@msg_link;
itemsArray.push(itemObj);
}
return itemsArray;
}
function main_function(event:Event) {
var max:int = myTextField.width;
if (myTextField.x <= ((0 - max) - margin)) {
if ((text_array.length - 1) > curr_text_id) {
curr_text_id++;
}
else {
curr_text_id = 0;
}
myTextField.x = 700 + margin;
myTextField.htmlText = text_array[curr_text_id].msg;
myTextField.setTextFormat(myFormat);
myTextField.autoSize = TextFieldAutoSize.LEFT;
}
if (myTextField.x > 710) myTextField.x = 710;
myTextField.x -= text_speed;
}
function text_speed_up(event:MouseEvent):void {
text_speed *= 2;
}
function text_reverse(event:MouseEvent):void {
text_speed = 0 - text_speed;
}
function text_normal(event:MouseEvent):void {
text_speed = text_speed_s;
}
function text_stop(event:MouseEvent):void {
text_speed = 0;
}
function str_replace(search, replace, string):String {
var array = string.split(search);
return array.join(replace);
}
addEventListener(Event.ENTER_FRAME, main_function);
trigger_left_t.addEventListener(MouseEvent.MOUSE_OVER, text_reverse);
trigger_left_t.addEventListener(MouseEvent.MOUSE_OUT, text_normal);
trigger_bottom_t.addEventListener(MouseEvent.MOUSE_OVER, text_stop);
trigger_bottom_t.addEventListener(MouseEvent.MOUSE_OUT, text_normal);
trigger_right_t.addEventListener(MouseEvent.MOUSE_OVER, text_speed_up);
trigger_right_t.addEventListener(MouseEvent.MOUSE_OUT, text_normal);
Hit Ctrl+Enter to test the movie.
Download the .fla file here
Upload your files for free at www.fileden.com
Monday, October 26, 2009
Tuesday, September 22, 2009
Create an Advanced Explosion/Fireworks Effect
In the root directory of the .fla file create a new folder and name it script. Now open you favourite text editor and copy and paste the following code
package script
{
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Spark extends Sprite
{
private var spark:Sprite = new Sprite();
/*origination coordinates of the spark*/
private var X;
private var Y;
/*the Y coordinate at which the spark will busrst*/
private var burstPoint;
/*sppeds along the X and Y axes*/
private var xSpeed;
private var ySpeed;
/*whether the spark will burst or jus fade away*/
private var willBurst;
/*the size(width) of the spark*/
private var size;
/*gravity will be acting on all sparks.*/
private var gravity = 0.15;
/*flag the spark for removal*/
private var removeSpark = false;
/*
*The Constructor takes parameters in the following order
X Coordinate,
Y Coordinate,
burstPoint,
vertical Speed,
Horizontal Speed,
willBurst,
size.
Only the first three are mandatory
*/
public function Spark(xc:Number,yc:Number,brstPnt:Number,ySd:Number=2,
xSd:Number=0,burst:Boolean=false,sz:Number=2)
{
X=xc;
Y=yc;
burstPoint=brstPnt;
ySpeed=ySd;
xSpeed=xSd;
willBurst=burst;
size=sz;
spark.x=X;
spark.y=Y;
addChild(spark);
spark.addEventListener(Event.ENTER_FRAME,moveDown);
}
private function moveDown(e:Event)
{
/*if the spark is flagged for removal*/
if(removeSpark)
{
spark.graphics.clear();
spark.removeEventListener(Event.ENTER_FRAME,moveDown);
spark=null;
return
}
/*Increment the Y axis speed to simulate gravity*/
ySpeed+=gravity;
/*Move the spark*/
spark.y+=ySpeed;
spark.x+=xSpeed;
/*
Draw the spark and simulate the trail.
If the spark will ultimately burst it
has a shorter trail. The trail also
depends on the speed of the spark;
*/
spark.graphics.clear();
if(willBurst)
{
for(var i=0;i<5;i+=1)
{
spark.graphics.lineStyle(size,0xFFFFFF,1/(i+1));
spark.graphics.moveTo(-xSpeed*i/3,-ySpeed*i/3);
spark.graphics.lineTo(-xSpeed*(i+1)/3,-ySpeed*(i+1)/3);
}
}
else
{
/*reduce the alpha*/
spark.alpha-=0.02;
if(spark.alpha<=0)
removeSpark=true;
/*
the trail length will reduce as the
alpha falls to simulate a
simutaneous fade out and slow down
effect
*/
for(i=0;i<15*spark.alpha;i+=1)
{
spark.graphics.lineStyle(size,0xFFFFFF,1/(i+1));
spark.graphics.moveTo(-xSpeed*i,-ySpeed*i);
spark.graphics.lineTo(-xSpeed*(i+1),-ySpeed*(i+1));
}
}
/*If the burst Point has been reached*/
if(spark.y<=burstPoint)
{
/*
if the spark does not have to burst
flag it for removal
*/
if(!willBurst)
removeSpark=true;
/*
the burst effect will be obtained by
creating a random number of instances
of the Spark class and sending them
in random directions;
*/
else
{ /*number of fragments will range from 20-40*/
var burstFragments = 20+Math.ceil(Math.random()*20);
for(var j=0;j<burstfragments;j++)>
{
var d:Spark =new Spark(spark.x,burstPoint,burstPoint-100,-7+Math.random()*14,-7+Math.random()*14,false,2)
addChild(d);
}
/*flag the original spark for removal*/
removeSpark=true;
}
}
}
//class ends
}
//package ends
}
This will be your custom class. Save this file in the folder named "script", with the name "Spark.as". Now open your .fla file and hit Ctrl+J to bring up the Document Properties window and set both the Width and Height to 400 and the Background Color to0x222222 (Black).
Click on Ok and then select the first frame of the layer and hit F9. In the Actions window that pops up, Copy the following lines of code.
import script.Spark;
function showSpark() {
/*random X coordinate of origin*/
var X = Math.random()*400;
/*
variable xSpeed so that sparks originating
from the left side of the stage move towards
the right and vice-versa
*/
var xSpeed = 0.05*(200-X);
/*
random burst point so that each spark
bursts at a different level
*/
var burstPoint = 50+Math.random()*100;
var d:Spark = new Spark(X,350,burstPoint,-15,xSpeed,true,3);
addChild(d);
/*add a random shade to the spark*/
var color:ColorTransform = new ColorTransform();
color.blueMultiplier = Math.random();
color.greenMultiplier = Math.random();
d.transform.colorTransform = color;
}
showSpark();
Hit Ctrl+Enter To test the movie. The code will add only one instance of the Spark class to the stage. Add your own method to add more instances
Download the orginal source code files here
You can improve the code by adding sounds to each explosions
Saturday, September 19, 2009
Imitate the Flash CS4 Color Palette in Actionscript 3
Open your .fla file and hit Ctrl+J to bring up the Document Properties window. Change the height and width to 400 and 240 pixels respectively and the Background color to 0x000000(Black)
Select the first frame and Hit F9 to bring up the Actions window. Copy and Paste the following code
/*size of each small square representing a color*/
var squareSize=13;
/*number of small squares in each side of a color set*/
var paletteSize = 6;
/*parent sprite container*/
var palette:Sprite = new Sprite();
palette.x = 10;
palette.y = 45
addChild(palette);
/*the square whose color is to be changed*/
var colorSampler:Sprite = new Sprite();
colorSampler.graphics.beginFill(0xFFFFFF);
colorSampler.graphics.drawRect(280,80,100,100);
colorSampler.graphics.endFill();
addChild(colorSampler);
/*create the palette*/
for(var k=0;k<
{
for(var i=0;i
{
for(var j=0;j
{
var square:Sprite = new Sprite();
square.graphics.beginFill(0xFFFFFF);
square.graphics.drawRect(0,0,squareSize,squareSize);
square.graphics.endFill();
square.x = (squareSize+1)*paletteSize*(k%3)+i*(squareSize+1);
square.y = (squareSize+1)*paletteSize*(Math.floor(k/3))+j*(squareSize+1);
/*add a gradual color to each small square.
By this distribution, the palette will have 6
color sets each made up of 6x6 small
squares. In all of these color sets there will
be an increasing amount of the GREEN mask along
the horizontal direction, and the BLUE mask along
the vertical direction. The red mask is distributed
over these 6 sets.
*/
var color:ColorTransform = new ColorTransform();
color.greenMultiplier = i/(paletteSize-1);
color.blueMultiplier = j/(paletteSize-1);
color.redMultiplier = k/(paletteSize-1);
square.transform.colorTransform=color;
palette.addChild(square);
/*listen for a click on the small square*/
square.addEventListener(MouseEvent.CLICK,clickHandler);
}
}
}
/*change the color of the square*/
function clickHandler(e:MouseEvent) {
/*the color masks are actually found by processing
the position of the clicked small square*/
var X=e.currentTarget.x;
var Y=e.currentTarget.y;
X=X/(squareSize+1);
Y=Y/(squareSize+1);
var Z=Math.floor(X/paletteSize)+Math.floor(Y/paletteSize)*3;
X=X-Math.floor(X/paletteSize)*paletteSize;
Y=Y-Math.floor(Y/paletteSize)*paletteSize;
/*apply the new color*/
var color:ColorTransform = new ColorTransform();
color.greenMultiplier =X/(paletteSize-1);
color.blueMultiplier =Y/(paletteSize-1);
color.redMultiplier = Z/(paletteSize-1);
colorSampler.transform.colorTransform=color;
}
Thats it!! Hit Ctrl+Enter to Test your movie.
Change the code to make the palette more detailed and sensitive.
Just like the color palette in Flash CS4, you can add a slider that darkens any given color. This can be achieved by gradually decreasing all the color masks simutaneously.
Wednesday, September 16, 2009
Create a very Realistic, custom Class, Dynamic Smoke Effect in Actionscript 3
In the root directory of the .fla file create a new folder and name it script. Now open your favourite text editor and copy and paste the following code
/*
*The smoke effect is achieved by creating small circles
*They are continuously moved upwards
*A BlurFilter is applied to make them look realistic
*As they float above their dimensions are increased and the alpha reduced
*Actually only 40 particles are present and they are continuosly
recycled to prevent the main memory occupied by the .swf file
from increasing.
*/
package script{
import flash.display.Sprite;
import flash.display.Shape;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.filters.BlurFilter;
import flash.utils.Timer;
public class Smoke extends Sprite
{
/*this will be the parent container*/
private var smoke_mc:MovieClip = new MovieClip();
/*color of the smoke*/
private var color:uint;
/*radius of each smoke particle*/
private var partRadius:Number = 1;
/*BlurFilter for the smoke particles*/
private var blur:BlurFilter = new BlurFilter(8,8,2);
/*timer to attach smoke particles*/
private var timer:Timer = new Timer(100);
/*
the constructor takes 3 parameters-
X and Y coordinates of the point of origination
and the color of the smoke
*/
public function Smoke(xc:Number,yc:Number,col:uint)
{
/*attach the parent movieClip*/
smoke_mc.x=xc;
smoke_mc.y=yc;
addChild(smoke_mc);
/*assign the color*/
color=col;
/*start the timer*/
timer.start();
/*listener for the timer. the function startSmoke
is called every 100 miliseconds*/
timer.addEventListener(TimerEvent.TIMER,startSmoke);
}
/*attaches one smoke particle to the stage*/
private function startSmoke(e:TimerEvent)
{
/*if 40 particles has been attached
stop attaching any more */
if(smoke_mc.numChildren>40)
{
/*stop the timer*/
timer.stop();
/*remove the timer listener*/
timer.removeEventListener(TimerEvent.TIMER,startSmoke);
}
/*atach a particle to the parent movieclip*/
smoke_mc.addChild(smokeParticle());
}
/*Create and return a fully formed smoke particle*/
private function smokeParticle():Sprite
{
var smokePart:Sprite = new Sprite();
smokePart.graphics.beginFill(color);
/*create the particle at a random point
between +2 and -2 pixels from the given
X coordinate*/
var randX = -2+Math.random()*4;
smokePart.graphics.drawCircle(randX,0,partRadius);
smokePart.graphics.endFill();
/*blur the particle*/
smokePart.filters=[blur];
/*add more randomness to the X coordinate*/
var randDist = -10+Math.random()*20;
smokePart.x+=randDist;
/*move the particles*/
smokePart.addEventListener(Event.ENTER_FRAME,moveUp);
return smokePart;
}
/*
move and resize the particles
change the values to see their
effects on the smoke
*/
private function moveUp(e:Event)
{
/*if the particle is visible*/
if(e.currentTarget.alpha>0)
{
/*move it upwards*/
e.currentTarget.y-=1;
/*increase the width*/
e.currentTarget.width+=0.5;
/*incraese the height at a lesser rate*/
e.currentTarget.height+=0.3;
/*reduce the alpha*/
e.currentTarget.alpha-=.004;
}
/*if the particle is not visible
restore Y to 0 ,X to a random
value, width and height to the
original radius and the alpha to 1*/
else
{
e.currentTarget.y=0;
var randDist = -5+Math.random()*10;
e.currentTarget.x+=randDist;
e.currentTarget.width=partRadius;
e.currentTarget.height=partRadius;
e.currentTarget.alpha=1;
}
}
}
}
This will be your custom class. Save this file in the folder named "script", with the name "Smoke.as". Now open
your .fla file and hit Ctrl+J to bring up the Document Properties window and set the Width and Height to 200
and 300 and the Background Color to 0x000000 (Black).
Click on Ok and then select the first frame of the layer and hit F9. In the Actions window that pops up, Copy
the following lines of code
/*import the custom class*/
import script.Smoke;
/*call the constructor to create a new instance of the Smoke class
change the X and Y coordinates and the Color of the smoke here.
*/
var smoke:Smoke=new Smoke(100,150,0xBBBBBB);
/*add the instance to the stage*/
addChild(smoke);
Thats it. Hit Ctrl+Enter to test your movie.
**
Add Objects to your movie and create multiple instances with different colors for a more complicated effect
Download the source files here
Saturday, September 12, 2009
Create a 3-D Image Reflection Effect with and advanced apllication of Bitmaps
This tutorial is insprired by the one i saw here but my application is actually different. I will use flters instead of masks
The 3-D effect is achieved with the application of the flash.display.BitmapData class and various Filters.
First we import an image on to the libray Through File->Import->Import to Library.. .here I am using a 200x200 album cover of Flipsyde's first album "We the People".
Now go to the library and right click on the image and select Properties. In the Linkage properties select Export For Actionscript and set the class name as pic;
Create a new movieclip to rotate your image and its reflection. Mine looks like this
Drag two instances of this on to the stage and rotate one to point to the right. give them instance names "l_mc" and "r_mc".
That done select the first frame of the Layer and copy and paste the following code
/*image dimensions*/
var imageHt=200;
var imageWd=200;
/*indicates the magnitude of rotation*/
var rot=0;
/*flags the direction of rotation*/
var goLeft:Boolean = false;
var goRight:Boolean = false;
/**load the image from the library into a bitmap data*/
var bitmap:BitmapData=new pic(imageHt,imageWd);
/*declare the container Sprites. "actual" will hold the image
"reflection" will hold the reflection and "container" will
hold these two*/
var container:Sprite = new Sprite();
var actual:Sprite = new Sprite();
var reflection:Sprite = new Sprite();
/*load the bitmap data into two bitmaps to
display the image and its reflection resp.*/
var imgage:Bitmap= new Bitmap(bitmap);
var refl:Bitmap = new Bitmap(bitmap);
/*
Filters for the reflection. the parameters are
Blur Filter - (blurX,blurY,quality).
Bevel Filter - (distance, angle, highlight color,highlight alpha,
shadow color,shadow alpha,blurX,blurY,quality,
strength,type).
notice the filter is applied just to the container bitmap,
not the bitmap data itself.
*/
var _blur:BlurFilter = new BlurFilter(3,3,1);
var _bevel:BevelFilter = new BevelFilter(50,90,0x000000,1,0x003366,.2,1,70,1,1,"inner");
refl.filters=[_blur,_bevel];
/*attach the image to the top Sprite container*/
actual.addChild(imgage);
actual.x = -imageHt/2;
actual.y = 0;
container.addChild(actual);
/*flip the reflection along the X axis and attach
the image to the top Sprite container*/
reflection.rotationX = 180;
reflection.addChild(refl);
reflection.x = -imageHt/2;
reflection.y = 2*imageWd+1;
container.addChild(reflection);
/*attach the top level container to the stage*/
container.x=175;
container.y = 40;
addChild(container);
/*this creates an improved rotational effect.
change the value of pp.fieldOfView to see
what happens*/
var pp:PerspectiveProjection=new PerspectiveProjection();
pp.fieldOfView=15;
container.transform.perspectiveProjection=pp;
/*add listeners*/
addEventListener(Event.ENTER_FRAME,rotate)
l_mc.addEventListener(MouseEvent.MOUSE_OVER,rotLeft);
r_mc.addEventListener(MouseEvent.MOUSE_OVER,rotRight);
l_mc.addEventListener(MouseEvent.MOUSE_OUT,stopLeft);
r_mc.addEventListener(MouseEvent.MOUSE_OVER,stopRight);
/*start left rotation*/
function rotLeft(e:MouseEvent)
{
goLeft=true;
}
/*start right rotation*/
function rotRight(e:MouseEvent)
{
goRight=true;
}
/*stop left rotation*/
function stopLeft(e:MouseEvent) {
goLeft=false;
}
/*stop right rotation*/
function stopRight(e:MouseEvent) {
goRight=false;
}
/*rotate by the given amount*/
function rotate(e:Event) {
container.rotationY=rot;
if(goLeft)
rot+=4;
else if(goRight)
rot-=4;
}
Hit Ctrl+Enter to test your movie. Change the background to suit your visual needs.
Download the .fla file here
Enjoy.
Thursday, September 10, 2009
Create a Funky Menu
We will create a nice menu with an advanced mouseOver handler for the buttons.
This tutorial is actually inspired by the pretty cool one I saw
here
But there the person used a special pre-scripted class called "TweenMax". I will try to do it with my own custom class. The animation is a little different because I haven't used the Tween Class at all.
To begin create a New Folder in your .fla root directory and name it "script". Inside it create a file with the name "menuButton.as". Copy and paste the follwing code in it. This will give you the custom class
package script{
import flash.display.Sprite;
import flash.display.Shape;
import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldAutoSize;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.ColorTransform ;
import flash.utils.Timer;
public class menuButton extends Sprite
{
/*the parent movie clip*/
private var button:MovieClip = new MovieClip();
/*name of the button*/
private var buttonName:String;
/*X coordinate of the button*/
private var X:Number;
/*X coordinate of the button*/
private var Y:Number;
/*text field to display the name*/
private var buttonText_txt:TextField=new TextField();
/*timer to monitor the random movements*/
private var timer:Timer = new Timer(100);
/*the constructor takes 3 parameters,the button
name and the x and y coordinates */
public function menuButton(str:String, xc:Number, yc:Number)
{
buttonName=str;
X=xc;
Y=yc;
}
/*create the button*/
public function getButton()
{
/*assign x and y coordinates*/
button.x = X;
button.y = Y;
/*create the background of a 8x4 array of
small squares*/
for(var i=0;i<4;i++)
{
for(var j=0;j<8;j++)
{
var rect:Sprite = new Sprite();
rect.graphics.beginFill(0x896434);
rect.graphics.drawRect(j*9,i*9,8,8);
rect.graphics.endFill();
button.addChild(rect);
}
}
/*format in which to display the name*/
var format:TextFormat = new TextFormat();
format.font = "verdana";
format.color = 0xFFFFFF;
format.size = 18;
/*create the text field and display the
button name*/
buttonText_txt.selectable = false;
buttonText_txt.x=2;
buttonText_txt.y=5;
buttonText_txt.text = buttonName;
buttonText_txt.setTextFormat(format);
buttonText_txt.autoSize = TextFieldAutoSize.LEFT;
button.addChild(buttonText_txt);
/*attach the button to the stage*/
addChild(button);
/*create mouse listeners*/
button.addEventListener(MouseEvent.MOUSE_OVER,mouseOverHandler);
button.addEventListener(MouseEvent.MOUSE_OUT,mouseOutHandler);
}
private function mouseOverHandler(e:MouseEvent) {
/*start the timer to start the random
movement of the background squares*/
timer.start();
timer.addEventListener(TimerEvent.TIMER,moveRandom);
/*loop through each of the small squares
set it to a random color and an alpha of 0.6*/
for(var i=0;i<button.numChildren-1;i++)
{
var obj:Object = button.getChildAt(i);
var color:ColorTransform = obj.transform.colorTransform;
var randx = -30+Math.random()*60;
var randy = -30+Math.random()*60;
obj.x=randx;
obj.y=randy;
color.color=0x00000;
/*multiplying by 2 gives brighter colors*/
color.redMultiplier = Math.random()*2;
color.blueMultiplier = Math.random()*2;
color.greenMultiplier = Math.random()*2;
obj.transform.colorTransform = color;
obj.alpha =0.6;
}
}
private function mouseOutHandler(e:MouseEvent) {
/*stop the timer and the random movements*/
timer.stop();
/*restore previous values of x and y coordinates
and the color*/
for(var i=0;i<button.numChildren-1;i++)
{
var obj:Object = button.getChildAt(i);
var color:ColorTransform = obj.transform.colorTransform;
color.color=0x896434;
obj.transform.colorTransform = color;
obj.x = Math.floor((i%8)/9);
obj.y = Math.floor(Math.floor(i/8)/9);
alpha = 1;
}
}
/*move the background squares randomly*/
private function moveRandom(e:TimerEvent) {
for(var i=0;i<button.numChildren-1;i++)
{
var obj:Object = button.getChildAt(i);
/*find random values for x and y coordinates*/
var randx = -1+Math.random()*2;
var randy = -1+Math.random()*2;
/*assign the random coordinates*/
obj.x-=randx;
obj.y-=randy;
}
}
}
}
Now open your .fla file and hit Ctrl+J to bring up the Document Properties window.Change the height to 150 and the background color to 0x00000.
That done, select the first frame and hit F9. Copy and paste the following script
/*import the custom class*/
import script.menuButton;
/*this array will contain the names of all the buttons you want in your menu*/
var labels:Array=["Home","Gallery","Login","Submit"];
/*display the buttons*/
for(var i=0;i<labels.length;i++)
{
var b:menuButton = new menuButton(labels[i],100*(i+1),60);
b.getButton();
addChild(b);
}
Hit Ctrl+Enter to test your movie!
Download the .fla file
Wednesday, September 9, 2009
Create a XML Driven, dynamic Word Jumble Puzzle
We will make a game where the player has to unjumble a given jumbled word. The words will be stored in an external XML file so that words can be easily changed and/or added.
First we create the XML file. open your favourite text editor and copy in the following.
<?xml version="1.0"?>
<gamedata>
<word>raffle</word>
<word>elephant</word>
<word>diamond</word>
<word>centre</word>
<word>giraffe</word>
<word>papyrus</word>
<word>dominate</word>
<word>raccoon</word>
<word>lizard</word>
<word>monitor</word>
<word>country</word>
<word>forest</word>
<word>bottle</word>
<word>carton</word>
<word>transfer</word>
<word>calendar</word>
<word>cricket</word>
<word>football</word>
<word>spoken</word>
<word>terminate</word>
<word>trailer</word>
<word>acoustic</word>
<word>bubble</word>
<word>yellow</word>
<word>national</word>
<word>language</word>
<word>shampoo</word>
</gamedata>
Save it as words.xml and then open your new .fla file. Remeber the .swf and .xml files should be in the same directory.
Hit Ctrl+J and bring up the Document Properties window and set the hieght and width to 200 and the background color to #99CC99.
Now select the Text Tool and draw a Dynamic text field. Go to the Propertoes Window and make sure the "Show Border around Text" and "Selectable" are not selected.Go to the Propertes window and type in its instance name as "jumble_txt" Now draw an Input text field with the "Show Border around Text" selected.This time its instance name will be "input_txt".Your Stage should look like this.
With the Text tool selected, draw two Static text boxes as label for the above fields, like so
Now hit Ctrl+F8 to bring up the New Symbol Window, change the name to "checker" and click OK. Draw you own button. Mine looks like this
Similarly draw another button. Name it "next"
Now go to the main stage and drag the two buttons onto the stage.
The instance name of the "checker" button should be check_mc and the other should be "next_mc"
That done Create a new layer and name it Actions. Select the first frame and hit F9. Copy and paste the following code.
var xmlLoader:URLLoader= new URLLoader();
/*load the xml file*/
xmlLoader.load(new URLRequest("words.xml"));
/*on completion of loading invoke the "parseXML" function*/
xmlLoader.addEventListener(Event.COMPLETE, parseXML);
var words:Array = new Array();
function parseXML(e:Event):void {
var i,j;
var menuLength;/*length of the word array*/
var XMLData:XML = new XML(xmlLoader.data);
menuLength = XMLData.word.length();
/*populate the globally defined array*/
for (i=0; i<len;i++)
words[i]=XMLData.word[i];
/*show the jumbled word*/
showWord();
}
var actualWord;/*the word being displayed in unjumbled form*/
var input;/*input typed in by the player*/
/*listen for mouse click*/
check_mc.addEventListener(MouseEvent.CLICK,checkAnswer);
next_mc.addEventListener(MouseEvent.CLICK,newWord);
/*show a jumbled word to solve*/
function showWord() {
/*choose a random index of the words array
and choose the word.Thus we choose a random
word everytime*/
var randChoice = int(Math.random()*words.length);
actualWord = words[randChoice];
/*display the jumbled word from the random array index*/
jumble_txt.text = jumbled(actualWord);
jumble_txt.autoSize = TextFieldAutoSize.LEFT;
/*show the button if hidden*/
check_mc.visible=true;
}
/*receive a string and return it after random jumbling*/
function jumbled(word:String):String {
var len=word.length;
var rand;
var c;
var wordArray:Array = new Array();
var jumbledWord:String = new String();
/*convert the string to an array to avail
better indexed access*/
for(var i=0;i<len;i++)
wordArray[i]=word.charAt(i)
/*randomise the array. The algorithm
sequentually picks a letter and swaps it
with a random letter coming after it */
for(i=0;i<len;i++)
{
rand = i+int (Math.random()*(len-i));
c=wordArray[i];
wordArray[i]=wordArray[rand];
wordArray[rand]=c;
}
/*reconvert array to string*/
for(i=0;i <len;i++)
jumbledWord+=wordArray[i];
/*return the jumbled string*/
return jumbledWord;
}
/*trim whitespaces from the given string*/
function trim(word:String):String {
/*remove from front*/
word = word.replace( /^\s*/g, "" );
/*remove from end*/
word = word.replace( /\s*$/g, "" );
return word
}
/*check the answer typed in by the player*/
function checkAnswer(e:Event) {
input=input_txt.text;
/*remove any whitespaces entered*/
input = trim(input);
/*remove anything typed in by the user*/
input_txt.text="";
/*hide the clicked button*/
check_mc.visible=false;
/*input is correct*/
if(input==actualWord)
jumble_txt.text = actualWord+" :-))";
else/*if input is wrong*/
jumble_txt.text = actualWord+" :-((";
}
/*show a new word*/
function newWord(e:MouseEvent) {
showWord();
}
Hit Ctrl+Enter to test your movie!
Subscribe to:
Posts (Atom)