Basic AS3

Hi,
I'm trying to learn AS3. I was very comfortable with AS2, but
now even the most basic things seem impossible for me. If someone
could give me a hand with this I would really appreciate it. This
is a basic AS2 example that I want to be able to replicate in AS3
and from them learn more about the logic behind it:
In AS2:
I could have a movie clip act like a button, and add
properties to it to be called later.
// myClip is a movie clip on the stage
// create a new property for it: temperature
myClip.temperature = '57F';
// have the clip trace the value of temperature once it is
pressed
myClip.onPress = function(){
trace (this.temperature);
so the question is, how do you do something like this in AS3.
I have tried many different ways and none seem to work.
Thanks so much for any help.

SummerLongSince,
> I'm trying to learn AS3. I was very comfortable with
AS2,
> but now even the most basic things seem impossible for
me.
Have you read any of the migration articles published in
Adobe's Dev
Center? These may likely give you a good, general purpose
start with the
new stuff.
> In AS2:
> I could have a movie clip act like a button, and add
properties
> to it to be called later.
This hasn't changed in AS3; not in principle, anyway. In
your example
code, the event handling syntax has changed.
> myClip.temperature = '57F';
> myClip.onPress = function(){
> trace (this.temperature);
> }
In AS3, that could be rendered like this:
myClip.buttonMode = true;
myClip.temperature = "57F";
myClip.addEventListener(
MouseEvent.MOUSE_DOWN,
function(evt:MouseEvent):void {
trace(evt.target.temperature);
Let's take a quick look at the differences. The first line
instructions
Flash Player to show the finger cursor when the mouse is
rolled over the
myClip instance. Without that line, the event handling still
takes place,
but because this is a movie clip symbol and not a button, the
cursor does
not automatically change from the default arrow shape.
The second line is identical to the first line in your
example. I used
double quotes, but it doesn't make any difference in this
case.
The remaining lines show the biggest difference. The
structure of AS3
event handling goes like this:
object.addEventListener(eventToListenFor, functionToPerform);
There are additional parameters (optional) you may provide
after these
first two, but the ones shown are the basic necessities: what
am I
listening for? what should I do when I encountered the
dispatched event.
As you can see, I split these two parameters over a number
of lines, but
the principle is the same (and honestly, not unlike the
principle in the AS2
version ... even there, the same concept applies: what am I
listening for?
what should I do when that thing occurs?).
AS3 event handling is similar to one of the *four* (yes,
four!) ways
event handling was possible in AS2. There was the
on()/onClipEvent()
approach, the newer dot notation approach (as used in your
example), the
addListener() method, and finally (for v2 Components) the
addEventListener()
method. In AS3 -- barring a teensy example or two in video
programming --
event handling is managed the same way. This consistency,
alone, marks a
significant improvement to me. Once you know it, you know it.
Not that instead of the global "this" property, the AS3
version's
trace() statement refers to the expression evt.target. The
variable evt
(short for "event") is found between the parentheses of the
function
literal. The name evt is arbitrary, but it refers to the
MouseEvent
instance passed into the function when the
MouseEvent.MOUSE_DOWN event is
dispatched. The MouseEvent instance features a target
property, and in AS3,
that property refers to the object that dispatched the event
in the first
place, which makes the expression "evt.target" equivalent to
"this" in this
case. An alternative would simply be to replace
avt.target.temperature with
myClip.temperature in the trace() statement.
David Stiller
Co-author, Foundation Flash CS3 for Designers
http://tinyurl.com/2k29mj
"Luck is the residue of good design."

Similar Messages

  • Help with some basic AS3 repeating scripts?

    Hello everyone,
    I have been asked to put together what I thought was a simple flash banner for a corporate site.  I am using Flash 8 and AS3, and the code is contained on a layer on frame 1.
    What I am attempting to do is slide a graphic from the right side of the page to the left.  Wait for 5 seconds, and the slide it down the page, and off the screen.  As the graphic is sliding down, a new graphic is sliding in from the right.  I have six different graphics that I need to do this with, and when the last one slides down, the whole thing repeats.
    I seem to be stuck and can't figure out how to do this....
    import fl.transitions.*;
    import fl.transitions.easing.*;
    import flash.display.Sprite;
    import flash.events.*
    var myIconArray:Array = new Array();
    myIconArray=[icon1, icon2, icon3, icon4, icon5, icon6];
    function SlideTextIn(myMC_Text, myMC){
      var myHoriTween1:Tween = new fl.transitions.Tween(myIconArray[myMC], "x", fl.transitions.easing.Strong.easeOut, 700, 250, 2, true);
      myHoriTween1.addEventListener(TweenEvent.MOTION_FINISH, finishedTween);
    function SlideTextDown (myMC_Text, myMC){
      var myHoriTween4:Tween = new fl.transitions.Tween(myIconArray[myMC_Text], "y", fl.transitions.easing.Strong.easeOut, 140, 600, 2, true);
    if(ArrayCounter+1 == 6){
      ArrayCounter=-1;
      SlideTextIn(0,0);
    function finishedTween(event:Event):void {
    SlideTextDown(ArrayCounter,ArrayCounter);
    ArrayCounter++;
    if(ArrayCounter >= 6){
       loopCounter++
      ArrayCounter=0;
    SlideTextIn(ArrayCounter,ArrayCounter)
    function finishedTextDown(event:Event):void {
      myIconArray[ArrayCounter].x = 700;
      myIconArray[ArrayCounter].y = 100;
      ArrayCounter=ArrayCounter+1;
        if(ArrayCounter>=6){
         ArrayCounter=0;

    Okay, I went back a attempted to clean up my code...this is what it looks like now:
    function SlideTextIn(myMC_Text, myMC){
    myText.text = ArrayCounter;
    myHoriTween1= new fl.transitions.Tween(myIconArray[myMC_Text], "x", fl.transitions.easing.Strong.easeOut, 700, 250, 2, true);
    myHoriTween1.addEventListener(TweenEvent.MOTION_FINISH, finishedTween)
    function finishedTween(e:TweenEvent):void {
    myHoriTween1.removeEventListener(TweenEvent.MOTION_FINISH, finishedTween);
    trace("loopCounter : " + loopCounter +" " +ArrayCounter)
    SlideTextDown(ArrayCounter,ArrayCounter);
    function SlideTextDown (myMC_Text, myMC){
    trace("Inside SlideTextDown " + myMC_Text)
    myHoriTween4= new fl.transitions.Tween(myIconArray[myMC_Text], "y", fl.transitions.easing.Strong.easeOut, 140, 300, 2, true);
    myHoriTween4.addEventListener(TweenEvent.MOTION_FINISH, finishedTextDown);
    function finishedTextDown(event:Event):void {
    myHoriTween4.removeEventListener(TweenEvent.MOTION_FINISH, finishedTextDown);
    myIconArray[ArrayCounter].x = 800;
    myIconArray[ArrayCounter].y = 80;
    ArrayCounter++
    if(ArrayCounter>=6){
      ArrayCounter=0;
    SlideTextIn(ArrayCounter,ArrayCounter);
    This will loop through all six graphics without a problem, and then start over again.  But, I can't seem to find a good way of sliding one graphic in from the right whilst the one is sliding down off the screen.

  • Basic AS3 Question

    I have a function that I want to use to add a movie clip from
    the library to the stage. Anyone have the code for that?

    If you have a movie clip in libruary, right click on it and
    chose "linkage", then check "Export for Action Script", and write
    down the name in "Class" field. After that you can use this name as
    usual class name, for example:
    var myClip:myClipClassName= new myClipClassName();
    addChild(myClip);

  • Basic AS3 (Listeners and Variables)

    I have 10 buttons on stage. Each button has been given an
    initial alpha of 0.2. Instead of creating an EventListener for each
    button (used for alpha=1.0), I am using the evt.target method with
    a single Listener which works great.
    For each button , I want to create another Listener that will
    play a different sound clip for each button respectively. I know I
    can do this by creating a Listener for each button, but I want to
    keep it simple and use the evt.target method again. This time I
    must tell the Listener to play a specific sound that has been
    assigned to the evt.target.
    Is there a simple way of doing so? I'm assuming I must assign
    a new variable to each button referencing its specific sound. The
    Listener would then call the evt.target.sound[sound1]. This is what
    I think is correct, but the various attempts have failed.
    Thanks as always!

    Thanks for response oP.
    I have actually gotten the effect by using a simple if/else
    statement.

  • Anyone: as2 vs as3?

    was looking at summerLongSince's post, basic as3, and it
    occurred to me that the as3 version of what had been previously
    done using as2 was more complicated and involved (see script
    below). i am still relatively new to actionscripting and am
    currently using/learning as2, so i am ignorant to the benefits as3
    has to offer at this point. could anyone tell me what benefits the
    as3 code below has over the as2 that precedes it? they both seem to
    accomplish the same goal, only as3 seems to take more time and code
    to do so. also, is moving to as3 worth the hassles that come with
    learning an entirely new scripting language? i haven't even
    mastered as2 and the thought of losing all the work i have put in
    thus far is somewhat sickening. lastly, couldn't as3's benefits
    have been implemented into flash without restructuring the entire
    programming language?
    thanks in advance,
    _name

    AS 3.0 comes with great features and 10 time faster than AS
    2.0. you may find some link on adobe.com site.
    for your current code. see this.

  • AS3 stop() doesn't work when saved to a USB drive

    Demonstarting basic AS3 to my Flash class tonight I discovered a strange anomoly. I created a scene with multiple frames and added a stop(); action on the first frame. Simple! But when i save the fla file to a USB drive and test the movie or even publish it to an exe, the stop command no longer functions. Save the fla to the hard drive and test/publish, it works fine. I tried this on multiple computers using CS4 with different USB drives and even different fla files created from scratch. The problem is consistent. gotoAndStop( ) also ceases functioning when the fla file is saved to the USB drive and then tested/published. Any ideas as to the difference? (BTW, I also tried to do it with AS2 and the stop() command functions correctly on both the USB and hard drive). Anybody else encounter this strange behavior?

    I confirm what dmennenoh says cause I also work on a network drive and never had problems compiling SWFs. However I tried to an external USB drive and in fact it seems that any AS3 code is simply not included in the file therefore it cannot work!
    Doesn't seem to be a security issue but some kind of bug from Adobe...
    Correction:
    Sorry, tested to USB drive with an "already faulty" file. It works fine either external USB drive or pen drive!
    Can it be OS related?! I'm using Flash CS4 on Vista.
    (note: The file I tested has external classes, imports some xml and images but has no play and stop actions)

  • XML Photo Gallery

    Hello,
    I am creating a very basic AS3 XML Gallery.
    The problem I am having is including the description or
    "caption" along with the photo.
    I have been going around it for awhile, but I can't seem to
    get my head around it.
    These are the basics I have for my XML.
    <?xml version="1.0" encoding="utf-8"?>
    <images>
    <image>
    <url>pics/first.jpg</url>
    <big_url>big_pics/first.jpg</big_url>
    <description>The first time</description>
    </image>
    </images>
    Here is my AS3 code attached.
    I believe that my main problem is the very last line.
    Thanks for any help that you can provide.

    Hello Dear,
    I was reading in this forum about XML gallery and found your thread. I am having a very similar problem to yours. I am making a XML driven flash gallery. I was able to make scrolling thumbnails that show larger images using XML. But the problem I am having now is displaying the description text. While reading your conversation with KG.Glad, it seems like you figured out the solution. But I couldn't really get a hold of it. Would you mind sharing your solution with me? I am new to XML and flash. I am spending weeks without much success. So desperately needing a help. If you could share a code or file, it would be nice.
    Thank you.
    generalbatzorig

  • Embedding interactive swf into a Tumblr post?

    Hi everyone,
    This is my first post/question. I'm trying to figure out if I can embed an interactive swf (with basic AS3 Code Snippets added to movie clips) into a Tumblr post.
    I found this post which explains how to use Dropbox as a repository for the file, but I couldn't make it work.
    I'm wondering if anyone has successfully posted an interactive swf to Tumblr before? If so, I'd be grateful for instructions.
    I'm not that familiar with Blogger, but if anyone has successfully done this there, that would be helpful to know too - I'll perhaps use it instead.
    Many thanks!!

    THen you can use the Loader class to load the file.  Just get loading it to work first to see if the file works as hoped when it is loaded.
       var ldr:Loader = new Loader();
       ldr.load(new URLRequest("yourswf.swf"));
       addChild(ldr);
    (hopefully I didn't miss something basic in that)
    After is is loaded and working you can deal with placement and adding dressing for it.  If you want to you can add it into whatever skin movieclip using...
       skinMCName.addChild(ldr);
    instead of the last line above.

  • Randomly play single item from array?

    Super rookie here to Flash.
    Is there some basic AS3 code to have, when the swf loads, a single video play from a collection of videos in an array? And can said code also apply to sound without video?
    I just found out the tutorial I was using to randomize doesn't work with audio - as it just plays everything at once - you might 'see' one video - but you hear all them.
    So from what I am reading, I need to us an array (that seems simple enough), but I don't want to play all the clips - I want it to randomly select and play one. Not sure exactly how I set up the video playback area (so the video plays where I want, at the size I want).
    Also, I have other pages that are just audio - does audio need some sort of player or something for this?
    ty

    The length part of that code is the length property, which is like any other property for any object in the sense that you use the word as shown "length" (not its value like you tried) and it will hold the value of that property.
    To keep the size of your file down, do not import the files into your fla, just load the selected one from where they are dynamically when the file is running.  The video will stream from its external location and your swf file will be happier for it. To get the FLVPlayback to play the video you need to assign it to the source property. 
    var my_videos:Array=new Array ("cat1.flv","cat2.flv"); // actual filenames
    var randomIndex = Math.floor(Math.random()*my_videos.length);
    yourFLVPlaybackName.source = my_videos[randomIndex];
    You should look up the FLVPlayback component in the help documents and familiarize yourself with all of it is properties, methods, and events.  In fact, you should learn to do this for any object you want to use in your designs.  Every class of object that you will use in a design has those three elements, properties, methods, and events, that not only define the object but are also your keys to making use of them.  So anytime you wonder how an object works, the first thing you oughta do is look it up in the help documents to see what properties, methods, and events support it.  Hopefully repetition of the words properties, methods, and events in this paragraph will help drive home the point that the help documents are an excellent resource to find information you need to make things work (properties, methods, events... and sometmes CONSTANTS)

  • End of flv triggers event(?)

    Hello
    I'm asking if this is possible, if so; how to approach it?
    I'm using FLCS4 (AS3) and I've built a very basic site, simple pages on various frames. Three of the frames/pages contain video components that auto-play a flv clip.
    What I'm asking is it possible to know when the video clip is finished and at that point display a button.
    (So the user cant proceed forward until the video clip is finished playing)
    {captive audience, so to speak}
    Anyways, is this possible, if so; how do I approach it?
    FYI - I have basic AS3 skills - not new, but not thinking 'in' AS3, yet....
    Thank you for your time and attention
    benn

    If you are using the FLVPlayback component, then you should be able to assign an event listener to each instance to listen for the COMPLETE event.
    flvName.addEventListener(VideoEvent.COMPLETE, doSomething);
    function doSomething(evt:VideoEvent):void {
         // btn.visible = true; or whatever

  • Float behavior confusion

    I always thought that setting a float property resulted in non-floated objects acting as if the floated object was not there
    however look at this code
    <div style="width:100px; height:100px; background-color:#03C;"></div>
    <div style="width:100px; height:100px; background-color:#F36;"></div>
    <div style="width:100px; height:100px; background-color:#F36; float:left;"></div>
    <div style="width:100px; height:100px; background-color:#F36; float:left;"></div>
    some divs are floated some are not
    if i place the non floated ones on top the floated ones appear bellow where they would if there was no floating at all.
    but if i place the floated ones on top the non floated ones position themselves where the floated ones are as if the floated ones do not exist.
    so why is it that floated/non floated elements ignore each other if the non-floated element comes first but not if its the other way arround

    when applying clear which block do i apply it to?
    if i apply it to the final block before the block which i intend to change the behavior of will it changhe the behavior of the block that i applied it to
    if i apply it to the first block that should ignore the float then what happens if this block itself must also be floated in order to effect the behavior of blocks which come after it.
    is there any reason why float/clear cannot be unused and simply use display:block and display:inline instead?
    frankly the confusion caused by css float/clear, espcially when combined with different display properties really annoys me
    Basic css, mysql and javascript did not cause me this sort of headache, basic AS3 did but only because i tried to run before i could walk.
    css is far more basic than any of these technologies and yet it causes me more grief than any of them.

  • Tiling and collision methods for this app

    I plan on making a game where the player travels down though a level. I have created basic player/objects collision games using AS2 & Mclips for browser/PC and some basic AS3 apps also, but I want to focus on making this one to run well/fast on iOS and Android via flash/AIR.
    The goal will be for the player to avoid colliding with rock/tiles.  There will not be too many enemies to track but a few powerups may be on the rock edges to pickup.
    Can someone give me any suggestions/links for current Tiling and Collision methods for this environment? Should I use starling?

    Thanks Glad, I hear that a pixel perfect collision method like bitmapdata hittest can be a tremendous overhead in CPU time, but I guess I will have to try it and see.

  • AIR NativeProcess on Mac gives Error:3219, all solutions failing

    hi guys,
    I've read up most solutions for this error and none seem to apply.
    I'm running a basic AS3 app in FlashBuilder, on OS-X.
    descriptor is set to extendedDesktop
    have set the profile in FB to 'extendedDesktop'
    am publishing as 'signed native installer'
    I've tried launching the file from both:
    app:/demo.sh
    file:///Users/visualife/Desktop/AE/demo.sh
    the target file is set to 777 (executable)
    the target file runs fine when directly targetted
    i'm running the exe on the same OS and machine it's created on
    changing the 'demo.sh' file to a jpg etc doesn't change anything
    No matter what I try I get told native process is support, everything runs fine until start is called then a Error: 3219 is thrown with no further information.
    all help greatly appreciated!
    I've included my code below:
    package {
       import flash.desktop.NativeProcess;
       import flash.desktop.NativeProcessStartupInfo;
       import flash.display.Sprite;
       import flash.errors.IllegalOperationError;
       import flash.events.Event;
       import flash.events.IOErrorEvent;
       import flash.events.NativeProcessExitEvent;
       import flash.events.ProgressEvent;
       import flash.filesystem.File;
       import flash.text.TextField;
       public class VauxhallController extends Sprite {
       private var debug_txt:TextField;
       public var process:NativeProcess;
       private var sh:File;
       public function VauxhallController() {
       if (stage) {
      init();
       } else {
       this.addEventListener(Event.ADDED_TO_STAGE, init);
       private function init($e:Event=null):void {
       this.removeEventListener(Event.ADDED_TO_STAGE, init);
      build();
       if (NativeProcess.isSupported) {
      initListeners();
      debugMe("Native process supported");
      go();
       } else {
      debugMe("Native not supported");
       private function build():void {
       // debug
      debug_txt  = new TextField();
      debug_txt.width = 300;
      debug_txt.height= 600;
       this.addChild(debug_txt);
       private function initListeners():void { }
       private function go():void {
      runShellFile();
       private function runShellFile():void {
       var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
       var essArgs:Vector.<String> = new Vector.<String>();  
       var file:File;
      file  = File.desktopDirectory.resolvePath("AE/demo.sh");
      nativeProcessStartupInfo.executable = file;
      nativeProcessStartupInfo.workingDirectory  = File.desktopDirectory;
      nativeProcessStartupInfo.executable = file;
      process = new NativeProcess();
      process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
      process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
      process.addEventListener(NativeProcessExitEvent.EXIT, onExit);
      process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
      process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
       try {
      process.start(nativeProcessStartupInfo);
       } catch (error:IllegalOperationError) {
      debugMe(error.toString());
       } catch (error:ArgumentError) {
      debugMe(error.toString());
       } catch (error:Error) {
      debugMe(error.toString());
       public function onOutputData(event:ProgressEvent):void {  debugMe("Got: "+ process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable));   }
       public function onErrorData(event:ProgressEvent):void {  debugMe("ERROR: "+ process.standardError.readUTFBytes(process.standardError.bytesAvailable));   }
       public function onExit(event:NativeProcessExitEvent):void { debugMe("Process exited with: "+ event.exitCode);   }
       public function onIOError(event:IOErrorEvent):void {  debugMe("IOError: "+ event.toString());   }
       private function debugMe(_str:String):void {  debug_txt.appendText(_str +"\n");   }

    Latest Version of Air won't install on my MAC! Help!
    Workaround mentioned in this thread by chris.campbell actually fixed same issue for me.

  • Papervision3D and Flash

    I have just started creating a basic papervision3D application, using its predefined class files and some basic AS3, that displays a sphere with a Earth texture mapped to it. I added some code to control the rotation of the camera so that the sphere has the illusion of rotating. But as it is the camera that is moving the sphere is made larger and smaller when the camera moves which is not what i want.
    What I think it is doing is, instead of rotating the sphere, it is keeping that static and moving the camera in and out of the z-axis so that the sphere looks as thought it is getting smaller and larger rather than simply rotating.
    I have tried altering the code so that it doesn't but nothing i do seems to stop the sphere from resizing. I was wondering if anyone has had the same problem and if so how did they fix it. Below is the code i have used and everything else is just the papervision3D classes and I have attached the .fla file and the jpg I used as the texture.
    import org.papervision3d.scenes.*;
    import org.papervision3d.cameras.*;
    import org.papervision3d.objects.*;
    import org.papervision3d.materials.*;
    var container:Sprite = new Sprite();
    container.x = stage.stageWidth * 0.5;
    container.y = stage.stageHeight * 0.5;
    addChild(container);
    var scene:Scene3D = new Scene3D(container);
    var camera:Camera3D = new Camera3D();
    camera.zoom = 5;
    var bam:BitmapAssetMaterial = new BitmapAssetMaterial("FlashIcon");
    bam.oneSide = false;
    bam.smooth = true
    for(var i:uint=0; i<1; i++)
        var p:Sphere = new Sphere(bam, 750, 32, 32);
        scene.addChild(p);
        //p.x = Math.random() * 1000 - 500;
        //p.y = Math.random() * 1000 - 500;
        //p.z = Math.random() * 1000 - 500;
        //p.rotationY = Math.random() * 360;
    this.addEventListener(Event.ENTER_FRAME, render);
    function render(e:Event):void
        camera.x += stage.mouseX - (stage.stageWidth * 0.5);
        camera.y += stage.mouseY - (stage.stageHeight * 0.5);
        scene.renderCamera(camera);

    Here are links for learning papervision 3d effect : http://curiousmindsmedia.wordpress.com/2007/05/14/33/
    http://dev.papervision3d.org/category/tutorial/
    Away 3D : http://away3d.com/tutorials , http://www.flashmagazine.com/Tutorials/category/away3d/

  • Noob question: How to update very basic as2 code to as3.

    I've been asked to update a web banner with old as2 code, and not being a coder or a regular Flash user, I'm stuck with what I'm sure is a simple problem. The code in the opening frame is;
    function timeOut(pauseTime) {
      stop();
      pauseTimer = setInterval(this, "goPlay", pauseTime);
    function goPlay() {
      play();
      clearInterval(pauseTimer);
    After that there are a few frames that include timeOut(500); code, which seems basic enough, so I imagine my problems are all in the opening code.
    I get 4 errors that all refer to Frame 1;
    1120: Access of undefined property pauseTimer.
    1067: Implicit coercion of a value of type CapOne_MM_648x480b_fla:MainTimeline to an unrelated type Function.
    1067: Implicit coercion of a value of type String to an unrelated type Number.
    1120: Access of undefined property pauseTimer.
    Can anyone help or point me in the right direction? Thanks.

    For the code you show there would be no need to convert to AS3 since between AS2 and AS3 it hasn't changed.  One thing you do need to do is declare variables and since pauseTimer is used in mutliple functions it needs to be declared outside any functions.  Another thing you need to do is specify the variable types, including the arguments passed into function.  As for the setInterval call itself it appears to be written incorrectly....
    var   pauseTimer:Number;
    function timeOut(pauseTime:Number) {
          stop();
         pauseTimer = setInterval(goPlay, pauseTime);

Maybe you are looking for