Flash AS3: Random Number Function, Returns a Random Number in Range

Here’s a little Flash AS3 (ActionScript 3) function that returns a random number in a range given two numbers. Comes in handy when doing many things that require random values within a set range.

function randomRange(minNum:Number, maxNum:Number):Number {
var myRandomNum:Number = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;
return myRandomNum;
}

//usuage
randomRange(2,22);

Related Posts:

Flash AS3 (actionscript 3) Helps: Flip MovieClip Horizontally with Matrix Class

The Flash Actionscript 3 Matrix class represents a transformation matrix that determines how to map points from one coordinate space to another. You can perform various graphical transformations on a display object by setting the properties of a Matrix object, applying that Matrix object to the matrix property of a Transform object, and then applying that Transform object as the transform property of the display object. These transformation functions include translation (x and y repositioning), rotation, scaling, and skewing.

Here’s a sample that uses the Matrix class to flip a Movie Clip horizontally:

function flipHorizontal(dsp:DisplayObject):void {
var matrix:Matrix=dsp.transform.matrix;
matrix.transformPoint(new Point(dsp.width/2,dsp.height/2));
if (matrix.a>0) {
matrix.a=-1*matrix.a;
matrix.tx=dsp.width+dsp.x;
} else {
matrix.a=-1*matrix.a;
matrix.tx=dsp.x-dsp.width;
}
dsp.transform.matrix=matrix;
}

//usuage
flipHorizontal(myMC)

Related Posts:

Flash AS3 Helps: Catching XML Load Errors, Asynchronously

Not all errors in ActionScript 3 happen when you call a function. Some errors can occur sometime after the call. A common example of this is loading content from the web like XML or other content. Here is a sample of how to catch these types of errors

var myLoader:URLLoader = new URLLoader();

myLoader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError);
function catchIOError(event:IOErrorEvent){
trace("Error caught: "+event.type);
}

myLoader.load(new URLRequest("Invalid XML URL"));
trace("Error, continuing...");

This will output:
Error, continuing...
Error caught: ioError

Related Posts:

AS3 Listen for the Enter Key to be pressed

Here’s a little Flash AS3 snippet that listens for the pressing of ENTER key using the Keyboard even listener.

this.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyEnterHandler);
function keyEnterHandler(event : KeyboardEvent) : void
{
if (event.keyCode == Keyboard.ENTER)
{
returnSavings_mc.visible=true;
}
}

Related Posts:

  • No Related Posts

How To Embed YouTube Videos In HTML5 And Flash Mode – SoftSailor

Found this tutorial on youtube how to’s, embedding Flash and HTML5

How To Embed YouTube Videos In HTML5 And Flash Mode – SoftSailor.

The YouTube video website contains millions of videos and most of them are being embedded to other websites with the Flash videotechnology. This is a great feature of Youtube videos and considering that all theweb browsers contain theAdobe Flash Player plug-in installed and so you are able of watching the embedded Youtube videos without any problems. But, when you’re using your mobile’s web browser the things change, because of the fact that mobile web browsers aren’t capable of understanding the Flash technology. Still, some newer mobile phones received support for HTML5, which is a technology which offers support for playing embedded Youtube videos by using the element, which makes all videos supported on the

mobile phones.

How To Embed Youtube Videos In An IFRAME

If you want your website to be used by both types of web browsers, mobile and desktop-based editions, then you need to embed videos on both Flash and HTML5 formats, and by doing this the PC users can view the Flash video and the mobile users can view th HTML5 video. So, the videos based on the IFRAME embedding code will automatically display FLASH or HTML5 video player, depending on what kind of web browser you’re using. This is done because the IFRAME automatically knows what type of browser or OS that you use and so it will use the HTML5 embedding code for mobile web browsers and the FLASH embedding code will be used for computers.

How to Embed YouTube Videos in both HTML5 and Flash Versions

Despite the fact the all the YouTube videos contain support for IFRAME video embedding code, the embed code needs to be written by you manually. In the near future the IFRAME format will be the default video embedding format used for YouTube, because it supports Flash and HRML5 video embedding formats.

Related Posts:

  • No Related Posts

Flash Book: ActionScript 3.0 for Adobe Flash CS4 Professional Classroom in a Book

You need to get this Flash book: ActionScript 3.0 for Adobe Flash CS4 Professional Classroom in a Book. CLICK HERE TO GET IT.

Here’s what it’s all about: The fastest, easiest, most comprehensive way to learn ActionScript® 3.0 for Adobe Flash CS4 Professional

ActionScript® 3.0 for Adobe Flash CS4 Professional Classroom in a Book contains 14 lessons. The book covers the basics of learning ActionScript and provides countless tips and techniques to help you become more productive. You can follow the book from start to finish or choose only those lessons that interest you.

Learn to add interactivity to Flash files using ActionScript 3.0: Control timelines and animation, write event-handling functions, and control loading of and interaction with data, text, video, sound, and images.

“The Classroom in a Book series is by far the best training material on the market. Everything you need to master the software is included: clear explanations of each lesson, step-by-step instructions, and the project files for the students.” —Barbara Binder, Adobe Certified Instructor, Rocky Mountain Training

Classroom in a Book®, the best-selling series of hands-on software training workbooks, helps you learn the features of Adobe software quickly and easily. Classroom in a Book offers what no other book or training program does—an official training series from Adobe Systems Incorporated, developed with the support of Adobe product experts.

Related Posts:

  • No Related Posts

Flash CS5 on the iPhone, Apps

At the MAX conference yesterday, Adobe announced that designers and developers will be able to use Adobe Flash Professional CS5 to create rich, interactive applications for the iPhone and iPod Touch.

This is NOT Flash Player running on the iPhone. There is no new information about Flash Player on the iPhone. This announcement means that Flash designers and developers can use Flash Professional CS5 and ActionScript 3 to build native applications that can be distributed and downloaded via the Apple App Store.

This new feature was demonstrated in a sneak peak of Flash Professional CS5. The new features of Flash Professional CS5 also include a new text engine for creative freedom and control with text, XML based FLAs to boost team collaboration on projects, prebuilt code snippets for rapidly adding interactivity, as well as integrations with Adobe Flash Builder to improve ActionScript editing. A beta of Flash Professional CS5 will be available later this year via Adobe Labs.

Adobe announces ability to publish ActionScript 3 projects to run as native iPhone apps. More info at http://www.adobe.com/go/iphone

Adobe Flash Pro CS5 beta coming, supporting native iPhone apps. Sign up and more info at http://www.adobe.com/go/flashprobeta

You can learn more about this announcement in the FAQ below as well as in the following places • Adobe News Room (http://www.adobe.com/aboutadobe/pressroom/) •

Information about apps for iPhone on Adobe Labs (http://www.adobe.com/go/iphone) • Information about Flash Professional CS5 on Adobe Labs (http://www.adobe.com/go/flashprobeta)

More about Flash Professional CS5

What did Adobe announce at MAX regarding Flash Professional?
Adobe previewed an early version of the next major version of Flash, Adobe Flash Professional CS5. Adobe also announced that a public beta of Flash Professional CS5 will be available for download from Adobe Labs later this year. That beta will include support for the ability to compile ActionScript 3® projects in Adobe Flash Professional to run as applications for iPhone. Interested designers and developers can go to Adobe Labs to sign up and to be notified when the beta is available.

What are the new features of Flash Professional CS5?
There are many new and exciting features in Flash Professional CS5. These include
• New text capabilities via the Text Layout Framework (TLF). Get unprecedented control and creativity with text in Flash projects. Advanced styling and layout, including right to left text, columns, threaded text blocks let you work with text in Flash like never before.
• XML based FLA files let you manage and modify project assets using source control systems, and enable teams to easily collaborate on files.
• Code Snippets panel provides pre-built code that can be injected into projects for greater interactivity and also reduces the ActionScript 3 learning curve. The panel includes code for timeline navigation (ie: click to go to the next scene) actions (ie: drag and drop), animation (ie: move with keyboard arrows), audio and video, event handlers (ie: mouse events) and loading and unloading of assets.
• Flash Builder integration. Use Flash Builder to write ActionScript code within Flash projects.
• Improved ActionScript editor, including custom class code-hinting and completion

When will the Flash Professional CS5 beta be available for download?
The beta will be available for download from Adobe Labs before the end of 2009. How much will Flash Professional CS5 or Creative Suite cost? We are not announcing any pricing at this time. Where can customers go to be notified when the beta is available? You can sign up to be notified: https://www.adobe.com/cfusion/mmfor/index.cfm?name=fpcs5_notify

More information about applications for iPhone
Q: When will Adobe Flash Platform tooling support building applications for iPhone?
A public beta of Flash Professional CS5 including support for building applications for iPhone is planned for later this year. Sign up to be notified when the beta is available.: https://www.adobe.com/cfusion/mmform/index.cfm?name=fpcs5_notify

Q: How does the Flash Platform tooling update help developers?

The tooling update allows developers to use Flash technologies to develop content for iPhone and iPod touch, devices that were previously closed to them. Developers can write new code or reuse existing web content to build applications for iPhone. Because the source code and assets are reusable across the Flash Platform runtimes,—Adobe AIR and Flash Player—it also gives developers a way to more easily target other mobile and desktop environments.

Q: How is this different from Adobe Flash Player 10 coming to iPhone? Will iPhone users be able to view web content built with Flash technology in the iPhone browser?

The new support for iPhone applications in the Flash Platform tooling will not allow iPhone users to browse web content built with Flash technology on iPhone, but it may allow developers to repackage existing web content as applications for iPhone if they choose to do so. Flash Player uses a just-in-time compiler and virtual machine within a browser plug-in to play back content on websites. Those technologies are not allowed on the iPhone at this time, so a Flash Player for iPhone is not being made available today. Flash Professional CS5 will enable developers to build applications for iPhone that are installed as native applications. Users will be able to access the apps after downloading them from Apple’s App Store and installing them on iPhone or iPod touch.

Q: Can applications for iPhone built with Flash Platform tooling be delivered through Apple’s App Store?

Yes. Developers can deliver applications built with Flash Platform tooling just like any other iPhone application. This will require the developer to be a member of the iPhone Developer Program and follow the program guidelines.

Q: Do developers need to participate in Apple’s iPhone Developer Program in order to develop or deploy applications for iPhone using the Flash Platform tools?

Yes. A developer certificate from Apple is required in order to test and deploy applications to iPhone. Apple provides information on its developer programs at http://developer.apple.com/iphone/.

Q: Are applications for iPhone built with Flash Platform tools interpreted at runtime?

No. iPhone applications built with Flash Platform tools are compiled into standard, native iPhone executables, just like any other iPhone application.

Q: Can applications load SWF files or other code at runtime, such as a module from a website?

No. iPhone applications built with Flash Platform tools are compiled into standard, native iPhone executable packages and there is no runtime interpreter that could be used to run ActionScript bytecode within the application.

Q: Which version of the iPhone SDK/operating system is supported by the applications?

Applications can be built targeting iPhone OS 3.0 and later.

Q: Will applications built with Flash Platform tools work on iPod touch? iPhone 1.0? iPhone 3G? iPhone 3GS?

Applications should work on all iPhone and iPod touch devices. However, as the hardware specifications of the devices are widely divergent, content performance may vary between devices and device generations.

Related Posts:

  • No Related Posts

Flash Helps Site Launched

Looking for Adobe Flash actionscript 3 helps? Check out: http://dsmith.tv/

Related Posts:

  • No Related Posts

Flash Helps: Create Text Field or Text Fields Dynamically

Here’s a simple little example of creating actionscript 3 text fields dynamically.  It is also a great example of using functions to do all the dirty work for you.

In order for this to work you need to put a button component in the library.

This sample will create an input text field instance and a button instance.  When the user click on the button, it will create a new text field and set its x,y to random.

Here is the code:

import fl.controls.Button;
import flash.text.TextField;
import flash.text.TextFieldType;

//create a button
var myButton:Button = new Button();
myButton.label = "set text random x,y";
myButton.emphasized = true;
myButton.width = 150;
myButton.move(50, 100);
addChild(myButton);

var tf1:TextField = createTextField(10, 10, 400, 22, true);
tf1.type = TextFieldType.INPUT;

//create an input text field function
function createTextField(x:Number, y:Number, width:Number, height:Number, border:Boolean):TextField {
     var result:TextField = new TextField();
     result.x = x;
     result.y = y;
     result.width = width;
     result.height = height;
     result.background = true;
     result.border = border;
     addChild(result);
     return result;
}

//event that listens for the button to be clicked
myButton.addEventListener(MouseEvent.CLICK,setRandomXY);

//function that creates the new text field and sets the text
function setRandomXY(e:Event){
     var randomX = Math.random()*stage.width;
     var randomY = Math.random()*stage.height;
     var tf2:TextField = createTextField(randomX,randomY,50,20,false)
     tf2.type = TextFieldType.DYNAMIC;
     tf2.text = tf1.text;
}

Related Posts:

Flash Helps: Tile Component

When Flash CS3 came out one of the new components was the Tile Component. The Tile Component in AS3 is similar to the Datagrid component in that it uses columns and rows to render data and images. The Tile Component can come in very useful in many instances of design and implementation.

Flash has a few examples of using the Tile Component in the helps. I’ve taken one of those examples and tweaked it a bit below. I put a text field on the stage with an instance name of myText and created a movieClip on the stage as well with the instance name of myMC.

The actionscript for using the Tile Component is as follows.  You’ll notice that it has some of the same properties as the DataGrid…like I mentioned.

import fl.controls.ScrollPolicy;
import fl.controls.TileList;
import fl.data.DataProvider;
import fl.controls.UIScrollBar;
import fl.events.ScrollEvent;
import fl.controls.ScrollBarDirection;

myText.text = "Select an Image";

//add a bunch of images and labels
var dp:DataProvider = new DataProvider();
dp.addItem({label:"Image 1", source:"http://www.helpexamples.com/flash/images/image1.jpg"});
dp.addItem({label:"Image 2", source:"http://www.helpexamples.com/flash/images/image2.jpg"});
dp.addItem({label:"Image 3", source:"http://www.helpexamples.com/flash/images/image3.jpg"});
dp.addItem({label:"Image 4", source:"http://www.helpexamples.com/flash/images/image1.jpg"});
dp.addItem({label:"Image 5", source:"http://www.helpexamples.com/flash/images/image2.jpg"});
dp.addItem({label:"Image 6", source:"http://www.helpexamples.com/flash/images/image3.jpg"});
dp.addItem({label:"Image 7", source:"http://www.helpexamples.com/flash/images/image1.jpg"});
dp.addItem({label:"Image 8", source:"http://www.helpexamples.com/flash/images/image2.jpg"});
dp.addItem({label:"Image 9", source:"http://www.helpexamples.com/flash/images/image3.jpg"});
dp.addItem({label:"Image 10", source:"http://www.helpexamples.com/flash/images/image2.jpg"});
dp.addItem({label:"Image 11", source:"http://www.helpexamples.com/flash/images/image2.jpg"});
dp.addItem({label:"Image 12", source:"http://www.helpexamples.com/flash/images/image3.jpg"});

var myTileList:TileList = new TileList();
myTileList.dataProvider = dp;
myTileList.scrollPolicy = ScrollPolicy.ON;
myTileList.columnWidth = 100;
myTileList.rowHeight = 67;
myTileList.setSize(400,67);
myTileList.columnCount = 3;
myTileList.rowCount = 1;
myTileList.move(10, 300);
addChild(myTileList);

myTileList.addEventListener(MouseEvent.CLICK,itemClicked);
function itemClicked(e:Event):void {
//myText
myText.text = myTileList.selectedItem.label;
//myMC
var i =new Loader();
i.load(new URLRequest(myTileList.selectedItem.source));
myMC.addChild(i);
}

Here are the sample files:

tileComponent.swf
tileComponent.fla

Related Posts:

Flash Samples: Mini MP3 Music Player in AS3

Here is a little Flash Sample in AS3 ( actionscript 3 ) I made that is a mp3 player.  It looks for a file variable called ‘myURL’ and loads that into the player.

Sample:
http://www.smithmediafusion.com/sotwPlayer.swf?myURL=TheStrokes1251.MP3

Files:
mini MP3 Player.fla

The code uses a flashvar which is the filename / URI of the mp3 file. It also utilizes other Flash Classes including the progressBar, Sound and SoundChannel Classes.

Code:

var myURL = root.loaderInfo.parameters.myURL;

playBtn.visible = true;
pauseBtn.visible = false;
pb.setSize(80.9, 14);
import fl.controls.Label;
import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
import fl.controls.ProgressBar;
import fl.controls.ProgressBarMode;
myLoadingTxt.text = "Press to play";
myProgressBar.visible = false;
var sp:Sound;
var songControls:SoundChannel;
var positionPrev:Number;
var mypaused:Boolean;

var t:Timer = new Timer(1000);
t.addEventListener(TimerEvent.TIMER, timerHandler);
function onPlayBtnPress(event:MouseEvent):void {
pb.setSize(80.9, 7);
playBtn.visible = false;
pauseBtn.visible = true;

if(mypaused == true){
trace("is paused true: "+myProgressBar.value*1000);

songControls=sp.play((myProgressBar.value*1000));
t.start();
mypaused = false;
}else{
myProgressBar.setProgress(0, myProgressBar.maximum);
sp = new Sound();

var req:URLRequest = new URLRequest(myURL);
sp.load(req);

var dataPath:String = myURL;
var loader:URLLoader = new URLLoader();
loader.load(new URLRequest(dataPath));

songControls=sp.play();
songControls.addEventListener(Event.SOUND_COMPLETE,soundCompleteHandler);
trace("songControls.position: "+songControls.position);
sp.addEventListener(Event.COMPLETE,updateTotalTime);

myProgressBar.visible = true;

myProgressBar.indeterminate = false;
myProgressBar.mode = ProgressBarMode.MANUAL;

addChild(myProgressBar);
var myLabel:Label = new Label();
myLabel.text = "";
myLabel.autoSize = TextFieldAutoSize.LEFT;
myLabel.move(myProgressBar.x, myProgressBar.y + myProgressBar.height);
addChild(myLabel);

pb.source = loader;
addChild(pb);
myLoadingTxt.text = "Playing...";

t.start();
}
}
function onPauseBtnPress(event:MouseEvent):void {
pb.setSize(80.9, 14);
playBtn.visible = true;
pauseBtn.visible = false;
trace("pause");

positionPrev=songControls.position;
songControls.stop();
mypaused=true;

t.stop();
}

function soundCompleteHandler(event:Event):void {
playBtn.visible = true;
pauseBtn.visible = false;
myProgressBar.visible = false;
mypaused = false;
trace("done");
myLoadingTxt.text = "Press to play";
t.stop();

}

playBtn.addEventListener(MouseEvent.CLICK, onPlayBtnPress);
pauseBtn.addEventListener(MouseEvent.CLICK, onPauseBtnPress);

function updateTotalTime(e:Event):void {

myProgressBar.maximum = sp.length/1000;
trace("sp.length: "+myProgressBar.maximum);
var minutes=Math.floor((sp.length/1000)/60);
var seconds=Math.floor((sp.length/1000)%60);
//myLoadingTxt.text=((minutes<10)?("0"+minutes):minutes)+":"+((seconds<10)?("0"+seconds):seconds);
}

function timerHandler(event:TimerEvent):void {
myProgressBar.setProgress(myProgressBar.value + 1, myProgressBar.maximum);

}
function stopTimer(event:TimerEvent):void {
trace("stopped");
}

Related Posts:

  • No Related Posts

Flash Helps: Flashvars in AS3

Another new feature in AS3 ( actionscript 3 ) is the new method of calling and setting flashvars in your actionscript.  Back in actionscript 2, you just call them after setting them in your html code.  AS3 is different.  While there are a few methods to do this, the simplest way I’ve found is this:

//the name of my flashvar is myVar

myText.text = root.loaderInfo.parameters.myVar;

Then you can use the Flash AS3 global variable method I use here to set your flashvar in as3 as a global variable.

MyGlobal.myString = root.loaderInfo.parameters.myVar;

Related Posts:

Flash Helps: AS3 Duplicate Movie Clip

The easiest way to duplicate a movieClip in Flash AS3 that resides in your library is to first create your clip; then, in the library, right click on it and select Linkage…, and finally check the Export for ActionScript check box.

Here’s a step by step in case you got lost while doing the initial steps to duplicate your movieClip using AS3.

1. Create your Clip.  I just made a simple rectangle for an example with a motion tween.

duplicate clip AS3

2. Right Click your clip in the library and select “Linkage…” and then check “Export for ActionScript”.

What this does is make a class called “myMC” that we can now call using actionscript 3.

3.  Put the following actionscript on frame one of your main timeline:

addEventListener(MouseEvent.CLICK,makeABox);

var i:Number = 1; //i will be the total number of boxes

function makeABox(e:Event):void {
trace(“new box #” + i);
var newBox:myMC = new myMC();
addChild(newBox);
newBox.x = stage.mouseX;
newBox.y = stage.mouseY;
i++;
}

So what this all means is, we use addEventListener to listen for a mouse click.  When a mouse click is detected, it runs the function makeABox.  This function calls our new class “myMC” and adds a new child clip using addChild.  We set the X and Y of the clip by detecting the X and Y of the mouse on the stage.

Here’s a screen shot:

Flash AS3 helps duplicateMovie

Here are the source files, happy flash actionscript 3 – ing:

duplicateMovieAS3.fla

duplicateMovieAS3.swf

Related Posts:

  • No Related Posts

Flash Help: AS3 Anchor Object to a Point

Here’s a little helpful Flash AS3 sample that connects two object using Flash Actionscript 3.  Drag either of the objects (the green point or the cloud popUp) and they’ll stay connected.  Something like this might come in handy for a Flash map point sort of a thing or you could even motion tween the green point and have the popUP stay in the same place. This also uses the ENTER_FRAME eventListener method that calls graphics.lineTo and graphics.beginFill on frame enter.

Here’s the actionscript:

import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Graphics;

//drag the two objects on the stage popup and myPoint
popup.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
function mouseDown(event:MouseEvent):void {
popup.startDrag();
}

popup.addEventListener(MouseEvent.MOUSE_UP, mouseReleased);
function mouseReleased(event:MouseEvent):void {
popup.stopDrag();
}

myPoint.addEventListener(MouseEvent.MOUSE_DOWN, pointMouseDown);
function pointMouseDown(event:MouseEvent):void {
myPoint.startDrag();
}

myPoint.addEventListener(MouseEvent.MOUSE_UP, pointMouseRelease);
function pointMouseRelease(event:MouseEvent):void {
myPoint.stopDrag();
}

//draw the connecting shage
var triangle_mc = new Shape();
addChild(triangle_mc);

popup.addEventListener(Event.ENTER_FRAME,popUPEnter);
function popUPEnter(evt:Event) {

triangle_mc.graphics.clear();
triangle_mc.graphics.beginFill(0xFFFFFF,100);
triangle_mc.graphics.lineStyle(4,0xFFFFFF,100);
triangle_mc.graphics.moveTo(myPoint.x,myPoint.y);

triangle_mc.graphics.lineTo(myPoint.x,myPoint.y);

if (popup.y<myPoint.y) {

triangle_mc.graphics.lineTo((popup.x),(popup.y+40));
triangle_mc.graphics.lineTo((popup.x),(popup.y+80));
triangle_mc.graphics.endFill();
}
if (popup.y>myPoint.y) {

triangle_mc.graphics.lineTo((popup.x),(popup.y));
triangle_mc.graphics.lineTo((popup.x),(popup.y)+30);
triangle_mc.graphics.endFill();
}
}

Here are the source files:
anchorTest – AS3.fla
anchorTest – AS3.swf

Related Posts:

  • No Related Posts

Flash Helps: onEnterFrame in AS3 is Event.ENTER_FRAME

I have many fond memories of onEnterFrame in actionscript 2…so many I that I really don’t recall. I’d slap my movieClip instance on the stage and put onEnterFrame on there and I could call the same actionscript over and over again all day long.

With object oriented programing and actionscript 3 onEnterFrame is now Event.ENTER_FRAME.  So it essensitially does the same thing.  Since it is an event it is located in the Event class. Here’s a little snippet:

myMC.addEventListener(Event.ENTER_FRAME,myMCEnterFrame);
function myMCEnterFrame(evt:Event){

trace(“this is myMC”); //traces ‘this is myMC’   over and over

};

Pretty simple and straight forward.

Related Posts:

  • No Related Posts

« Previous Entries