Sandbox
From AUFlashWiki
Contents |
Add any experiments you want to share with others here
- Include the swf and fla.
- Comments would be helpful
- Leave your name in case there are questions
Manipulating Movie Clips in AS3
While working on my project this semester, I was able to learn a lot about movie clip manipulation in Action Script 3. One common use of movie clip objects, and the reason I used them in my game so much, is because it enables you to use the same symbol over and over again. One specific example, and you'll see it if you look at my game, is a dialog box. In the case of my project, I have several "research boxes" which come up when one clicks on a specific research topic. to accomplish this I began by creating a movie clip object. In the box that comes up, you are asked to name your object. For the purposes of this example, let's call it "dialogBox." Once you have entered the same, look down and you will see a text box that asks if you want to "Export for Action Script." Check that box and click "ok." A warning box will then come up and tell you that there is no class for this object, but Action Script will create one when you export. This is what you want so click "ok." What you have just done is tell Flash to create a new class for you when you run the program with your object so that you don't have to hard code it. Now, what to do with it? Well, in my case I was constantly calling it into being to display research info. That being the case my dialog box contained two Dynamic Text Fields. One was called boxTitle and the other boxText. So, what we have now is a movie clip object of the class "dialogBox" which contains two dynamic text fields called "boxTitle" and "boxText." So when you are ready to use them... You have to begin by creating an instance of the movie clip on the stage. But, since it's not on your stage or timeline, you have to really CREATE it. Done as follows:
var infoBox:dialogBox = new dialogBox();
You will notice that this line of code looks a bit odd. Where did the "infoBox" come from you ask? Well, basically what this line of code says is this: create a new variable, called infoBox, that is an instance of the dialogBox class. Now you need to place your new movie clip instance on the stage. Do this like so:
infoBox.x = 100.0; infoBox.y = 100.0; stage.addChild(infoBox);
So above what we've done is told the program that we want the instance of dialogBox called infoBox at (100,100). Then we told the program to place the object called infoBox on the stage. And now, when you run the program, you'll get the box on the screen. In my case I added this code to a button function so that the box appeared at the touch of a button, so to speak.
Now, when you want to do something with this object, say put some text in the fields, you must do it this way:
infoBox.boxTitle.text = "AS3 Tutorial"; infoBox.boxText.text = "Some stuff about as3, blah, blah, blah.";
Notice that when you want to work with things inside movie clips you must include the movie clip instance name in the code. The same holds true if you had a button in your movie clip, for example. Say I had a button to close the box called closeBtn. The code would look like this:
infoBox.closeBtn.addEventListener(MouseEvent.CLICK, closeBox);
See? Most of what you need to know is to remember to reference the movie clip's name before you reference stuff inside it, no matter what it is. Then, finally, when you want to rid yourself of the movie clip, use this code:
stage.removeChild(infoBox);
Easy. Hope this helps someone out there...
Todd
Constrained walking and other game actions
Here is a flash file that I found on a tutorial that illustrates overhead constrained walking. This might be helpful with making a maze or having boundaries in a game where a character wouldn't be able to pass. Hope this helps somewhere! Kelly
media:Constrianwalkingoverhead.fla
I came across these other flash files when I was looking for action script for making objects move with the arrow keys, moving objects on a path and other game related movement. Kelly
media:Arrowkey8directionmove.fla
media:Snowmobileridingpixelhills.fla
StartDrag function
I can't EXACTLY explain why this is, but I've experimented enough within my own project to let you know a couple things you should look out for when using startDrag();
- First, create the draggingobject you want and place it on a movieclip.
- Then, you can start drag either FIRSTMOVIECLIP.onPress = function () { draggingobject.startDrag();} OR if you just want it to start right away you can just say FIRSTMOVIECLIP.draggingobject.startDrag();
- Unless you want your dragger to go willy-nilly, set up some parameters. You do that within the startDrag parenthesis. (EXAMPLE: FIRSTMOVIECLIP.draggingobject.startDrag (draggingobject, BOOLEAN, y-top, x-left, y-bottom, x-right);
- The Boolean tells the draggingobject whether it should stick right under your mouse or not. True = it will stick to mouse, false = it won't.
- The Flash help says the coordinates are for left, top, right, bottom. This DID NOT work for me. If you are having the same issue, use the ones I just listed (i.e. y-top is top of the y axis, etc). See my file for more explanation).
- To stop the dragger on release use, FIRSTMOVIECLIP.draggingobject.onRelease = function() {stopDrag();} OR you can stop it onPress (<-this is what I did in order to let users click where they want it to go);
- To see where it landed you can ask if (draggingobject._x == NUMBER) or if (draggingobject._y == NUMBER)
- One last tip: my dragger was moving far from the mouse even though I had the boolean set to true, and I couldn't figure out why. BUT, when I was first setting up the movie clip I decided to give the dragger a location with a 0 axis. This helped fix it. So if you're having the same issue, just tell your dragger where to go first. (i.e. draggingobject._x = 0; etc.)
Hope this is helpful for someone! Let me know if you figure out any of the mysteries associated with drag. Here is my example if you want to look closer at the code. It is in the action layer at the end of the "platform" label. Media:KJarmul_flashproject_platform.fla -Katharine
AS3 for Streaming Media
One of the best ways to use video with flash is to stream it from a server, as opposed to embedding it in the flash (which makes for a massive swf file).
There are a series of steps to do this:
1. First you must convert your video file into an ".flv" file.
2. To create an .flv file, find the Flash Video Encoder in the Flash CS3 folder on our computer.
3. "Add" your file to the Queue and press "Start Queue."
4. Upload this new file to a web server somewhere
5. Use the following code in your flash file to load and control the video, replace "myfilesURL" with the URL location of your file.
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.play("myfilesURL");
function asyncErrorHandler(event:AsyncErrorEvent):void {
//ignore error
}
var vid:Video = new Video();
vid.attachNetStream(ns);
this.addChild(vid);
7. You will have to use the various properties of the Video class to position and size the video.
Scroll around inside a large picture
I think someone asked about how to scroll around inside a larger picture one time in class. I thought I'd contribute with this panorama scroller I made. I made a slider out of two graphics, a box and a groove, then linked them with the first part of the Actionscript. Then I made a motion tween of the picture, automatically creating a filmstrip. That way, I can retrieve the horizontal pixel location of the slider and tell it to go to that frame number; I inserted as many frames as there were pixels in the groove, which had the side effect of making a very smooth scroll at a low hit to the total file size.
Check out the code in the 'Actions' layer. If you have a question about it, ask me or post it.
-Casey
media:Panorama.fla
For those of you who are using other programs to create your flash movies, I found this script to break your photoshop layers up easier for after effect so you can use the z space while maintaining scale. in otherwords it helps create 3-d looking images which you can then import into flash.
http://www.aenhancers.com/viewtopic.php?t=498
-maura
Simple Photo Viewer
If you re interested in some code that will allow you to make a simple photo viewer, here it is:
import flash.events.MouseEvent;
this.stop();
function gotoNext1(event:MouseEvent):void { gotoAndPlay("photo2"); }
function gotoPrev1(event:MouseEvent):void { gotoAndPlay("photo1") }
photoTwoPrev.addEventListener(MouseEvent.CLICK, gotoPrev1); photoTwoNext.addEventListener(MouseEvent.CLICK, gotoNext1);
Do note that this code requires you to create new button instances for each set of buttons. See Laraine's final project for implementation of this code.
If you're interested in the AS3 that makes the following animation go, here it is:
import flash.events.MouseEvent;
this.stop();
function abductMan(event:MouseEvent):void { this.play(); }
abductSucka.addEventListener(MouseEvent.CLICK, abductMan);
FLA link:media:HyperspaceCat_abduction2.fla
Skeleton Files
Narrative Game Skeleton
- Use for any Flash project with buttons that jump you to a timeline.
- media:Narrativegame_skeleton.fla
-Brian
Game Skeleton
- Use for a keyboard controlled game.
- It can help you structure your game.
- media:game_skeleton.fla
Sim Skeleton
- Use to manage different states in a game.
- Also demonstrates use of Flash drawing tools.
- media:sim_skeleton.fla
Drops Skeleton
- Generates multiple drops from a MovieClip.
- It can help you structure your game.
- media:drops_skeleton.fla
Dynamic Process Skeleton
- Use to manage dynamically created MovieClips.
- Also shows how to detect boundaries when moving a MovieClip with ActionScript.
- media:dynamicprocess_skeleton.fla
Tutorials
I found these websites with free tutorials that are pretty cool:
http://www.freeflashtutorials.com/ you can download specific tutorials on compression, drawing and shape tweening.
http://www.video-animation.com/flashcs3_001.shtml has various tutorials for specific flash tasks like hyperlinking, scrolling backgrounds, making particles, advanced matte effecte and such.
http://www.actionscript.org/actionscripts_library/ has a searchable action script library which might come in handy, if I only knew what it meant..
or try this site which has beginner, intermediate and advanced tutorials for interactivity and actionscripting.
http://www.actionscript.org/resources/articles
Maybe it will come in handy? KD
This tutorial helped me a ton with hittest and linkage: http://www.kirupa.com/developer/actionscript/vertical_shooter.htm
-Maura
02/26/2008
Marina Dzougoutov
I learned "signature" from online tutorial but it does not work that way so I create on my own and it worked...
Here is step by step and hope it is easy to follow it.
1. Write the Text:
In a flash document, write the text as you want it to appear at the end of the animation. Use text tool, selecting the font Bickham Script Pro Regular or Edwardian Script ITC. Then go to Modify - Break Apart. The text will become individualized.
2. Work Backward: Create a keyframe for the final image. For a simple word, 20 frames is about right. Select the frame and press F6 to create the keyframe. Now select frame 20 and pressing the Option key, drag the keyframe back to frame 19. Then remove the last letter of text. In the sample signature, the last text would have been the "y." Next select the keyframe and press Option to drag it back to a frame. Continue remove a text each time you create a keyframe. Pressing option as you drag the keyframe copies contents of current keyframe. So you don't have to remove the section all over again.
3. Add a stop action:
By default, Flash looks for movies, but we want the writing to appear and then stop on the screen. So we need to add a stop action. Select the final frame. Press F9 and open the action panel. Choose timeline control and then double click stop to apply. Press Cmd+Return to test the animation.
3/1/2008
1. Here's a really good basic Flash actionscripting tutorial I found on YouTube. Actionscript really is like a different language. I'd recommend watching it on a separate computer or screen so you can work on your own Flash at the same time. [[1]]
2. Here's videoblogger ZeFrank's site. He has a lot of old Flash interactives that use a very basic interface. Take a look at his projects to get some ideas.[[2]] --Dandennis 00:19, 2 March 2008 (EST)
4/2/08
Here's some cool inspiration from Smashing Magazine: http://www.smashingmagazine.com/2008/04/02/39-creative-flash-designs/
--Brad
4/9/08
I found this code written by http://www.flashstar.de/ and posted on flashdevils forum for randomizing objects with a variety of different sizes, movements, etc.
You just need to use the identifier "blase" when exporting your object to actionscript in the advanced menu of convert to symbol window.
function setBubbles(obj, depth, xPos, yPos, maxNum, randHeight, randWidth, Height, Width) {
this.createEmptyMovieClip(obj, depth);
this[obj]._x = xPos;
this[obj]._y = yPos;
for (i = 1; i <= maxNum; i++) {
this[obj].attachMovie("blase", "blup" + i,depth + i);
this[obj]["blup" + i].tempo = random(7) + 5;
this[obj]["blup" + i].randVal = random(4);
this[obj]["blup" + i].direction = -1;
this[obj]["blup" + i].ZS = random(50) + 10;
this[obj]["blup" + i]._xscale = this[obj]["blup" + i].ZS;
this[obj]["blup" + i]._yscale = this[obj]["blup" + i].ZS;
this[obj]["blup" + i]._y = random(randHeight);
this[obj]["blup" + i]._x = random(randWidth);
this[obj]["blup" + i].onEnterFrame = function() {
this._y -= this.tempo;
this._x -= this.randVal;
this.randVal += this.direction;
if (this._y <= 0) {
this._y = Height;
this.randVal = random(4);
this.tempo = random(7) + 5;
this.ZS = random(50) + 10;
}
if (this._x <= 0) {
this._x = Width - this._width;
}
if (this._x >= Width) {
this._x = 0 + this._width;
}
if (this.randVal < -random(3)) {
this.direction = +1;
}
if (this.randVal > random(3)) {
this.direction = -1;
}
};
}
}
setBubbles("room", 1, 0, 0, 30, 400, 550, 400, 550);
========================
I found these sites to be helpful when working on my project -Kyle
http://lukamaras.com/ http://www.tutorialized.com/tutorials/Flash/Games/1 http://www.learnflash.com/
========================
Learnflash.com, which Kyle mentioned above, has some good video podcasts. Another source for video tutorials is http://www.flashgameu.com. You can access their podcasts in iTunes from http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=261154936
--Brad
Adding sound to buttons
This is the code I used to get rollover sound for the buttons in my Rhyming Rhinos game (see it here). This particular string is for the cat button on the first screen:
// create new sound object
var q_sound = new Sound(this);
// attach the sound to the object...note need sound in the library
// needs linkage property identifier (export for actionscript checked)
q_sound.attachSound("cat");
// button action (onRollOver) triggers sound to play but not repeat
catQ_btn.onRollOver = function() {
q_sound.stop();
q_sound.start();
};
Be sure to add a linkage identifier to the sound file (in my case, it was "cat").
--Brad
Adding Input Fields to Your Piece with AS3
I had posted this on my wiki page as an example of proof of concept. This is a calculator, for all intents and purposes, that works by running whatever numbers you input through the equations that make up the Salt Marsh model and spitting out final values. One of the major problems I had when I was working on this was conversion of strings to numbers and back again for output. Below is the beginning of the code I used:
//Inital values.
var gi:Number;
var si:Number;
var ci:Number;
var ni:Number;
//Temporary values.
var gtm:Number;
var st:Number;
var ct:Number;
var nt:Number;
//Final values.
var gf:Number;
var sf:Number;
var cf:Number;
var nf:Number;
//Event listener for calculate button.
calcBtn.addEventListener(MouseEvent.CLICK, calcModel);
//calcModel function.
function calcModel(event:MouseEvent):void {
//Conversions of inital value input fields.
gi = Number(iniGrass.text);
si = Number(iniSnails.text);
ci = Number(iniCrabs.text);
ni = Number(iniNit.text);
//Conversions for temp values input fields.
gtm = Number(tmpGrass.text);
st = Number(tmpSnails.text);
ct = Number(tmpCrabs.text);
nt = Number(tmpNit.text);
You will note that I began by creating the variables I would be using. Then, with the lines:
gi = Number(iniGrass.text);
I was able to convert the Strings which were input by the user into the iniGrass box, collect them and convert them directly to numbers so that the program could use them. What the line of code above says is: the variable "gi" is now equal to the value of whatever is in "iniGrass.text" in number form.
But you'll also notice that this conversion did not take place until the calcBtn was pressed.
Then, when I was ready to output, I used the following code:
fnGrass.text = String(gf);
Again, I used the same method to make the conversion. What this line says is: in the text field called "fnGrass" place the value of the variable "gf" in String form. Easy. Hope you can use this in the future.
Todd
Using Tweens
//in actionscript3
//import necessary packages
import fl.transitions.easing.*;
import fl.transitions.Tween;
//create a new shape, draw a circle
var shape:Shape = new Shape();
shape.graphics.lineStyle(2,0x000000);
shape.graphics.drawCircle(0,0,100);
//add the shape to the stage
this.addChild(shape);
//set the starting position of the shape
shape.x = 100;
shape.y = 200;
//create the tween
var tween:Tween = new Tween(shape,"x",Regular.easeIn, shape.x, shape.x+200, 3, true);
tween.start();
You can use a tween to interpolate between any value for the specified object. For instance, if you wanted to instead change the alpha parameter of the shape over time, you could do this:
//create the tween
var tween:Tween = new Tween(shape,"alpha",Regular.easeIn, shape.x, shape.x+200, 3, true);
tween.start();
Specifying a tween is done using the following format:
- The first value is a reference to the object that you want to tween
- The second parameter is a string which names the property of the object you want to change
- The third parameter is the easing function (found in the fl.transitions.easing package)
- The forth parameter is the starting value
- Fifth is the end value
- The sixth parameter is a value representing the length of time for the tween
- The final parameters is a boolean; if it is true, then the sixth parameter is considered in seconds, if it is false, the sixth parameter is considered to be a number of frames for the tween to last
-John

