Foundation Actionscript 3.0 Animation

Keith Peters

Mentioned 8

Flash has long been one of the most approachable, user-friendly tools for creating web-based animations, games, and applications. This has contributed to making it one of the most widely used programs for creating interactive web content. With each new version of Flash, ActionScript, its built-in scripting language, has become more powerful and a little more complex, too. ActionScript, now at version 3.0, has significantly matured as a programming language, bringing power and speed only previously dreamed about to Flash-based animation, going far beyond traditionally used keyframes and tweens. The material inside this book covers everything you need to know to harness the power of ActionScript 3.0. First, all the basics of script-based animation and setting up an ActionScript 3.0 project are covered. An introduction to object-oriented programming follows, with the new syntax, events, and rendering techniques of ActionScript 3.0 explained, giving you the confidence to use the language, whether starting from scratch or moving up from ActionScript 2.0. The book goes on to provide information on all the relevant trigonometry you will need, before moving on to physics concepts such as acceleration, velocity, easing, springs, collision detection, conservation of momentum, 3D, and forward and inverse kinematics. In no time at all, you'll both understand the concepts of scripted animation and have the ability to create all manner of exciting animations and games.

More on Amazon.com

Mentioned in questions and answers.

I am new to actionscript 3.0 and I'm experiencing difficulty trying to pass a variable that is created and set in frame 1 to a dynamic text box that is added to the stage in frame 4.

on frame 1 the variable is set from information entered by the user: var input_dia = ""; input_dia = pdia_input.text;

and should be displayed in a dynamic text box on frame 4: dia_alert.text=input_dia;

I'm receiving the following error: 1120: Access of undefined property input_dia.

frame scripting is, in my opinion, ghetto and should be avoided.

that being said, you problem could be solved a few ways. first, you create an "Actions" layer that is accessible to all frames by stretching the layer as long as your timeline, but all your actionscript is on the first frame. second, by placing your text field on a separate layer, accessible in frame one but only becomes visible in frame 4 (assuming you don't want it to appear until frame 4).

however, OOP and and a descent design pattern as Glycerine suggests is definatly the way to go, especially if you are new and plan on further investment in the flash platform.

some book suggestions: Colin Moock's Essential ActionScript 3.0, The ActionScript 3.0 Quick Reference Guide, Kieth Peter's Foundation Actionscript 3.0 Animation: Making Things Move! and AdvancED ActionScript 3.0 Animation. these books will certainly give you some solid ground in proper development for the flash platform. if you read them you wont regret it.

I'm using Flex and AS3 to try and create a game, and I'm wondering how I can animate things easily. I would prefer to use sprite sheet images. I'm going to go a head and post the code (It's really short) I got so far, can someone look over it and tell me the best/simplest/easiest way to add animation support? Thank you in advance.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
  styleName = "plain"
    xmlns="cyanprime.*" 
    layout="absolute"
    width="600"
    height="400"
    frameRate="100"
    applicationComplete="initApp()">

    <mx:Script>
        <![CDATA[
            public function initApp():void
            {
                stage.addEventListener(KeyboardEvent.KEY_UP, keyUp); 
                stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown); 
                Mouse.hide();
                canvas.init();

            }

            private function keyDown(event:KeyboardEvent):void
            {
                canvas.KeyDownHandler(event);
            }

            private function keyUp(event:KeyboardEvent):void
            {
                canvas.KeyUpHandler(event);
            }
        ]]>
    </mx:Script>

  <MyGameCanvas id="canvas" width="100%" height="100%" themeColor="#ff0000" />
</mx:Application>

...

package cyanprime{

    import mx.core.UIComponent;
    import mx.controls.Image;
    import flash.events.*;
    import flash.utils.*;
    import flash.display.*;
    import flash.ui.Keyboard;

    public class MyGameCanvas extends UIComponent{
        [Embed(source="player.gif")]
        private var playerImage:Class;
        private var playerSpeed:int = 5;
        private var keys:Array = new Array();
        private var player:DisplayObject = new playerImage();
        private var ticker:Timer;



        public function init():void{
            // set up player
            player.x = 50;
            player.y = 50;
            addChild(player);

            for(var i:int = 0; i < 300; i++)
            {
                keys[i] = false;
            }

            ticker = new Timer(10); 
            ticker.addEventListener(TimerEvent.TIMER, onTick);
            ticker.start();

        }

        public function controls():void{
            if(keys[Keyboard.RIGHT])
                player.x += playerSpeed;

            if(keys[Keyboard.LEFT])
                player.x -= playerSpeed;

            if(keys[Keyboard.UP])
                player.y -= playerSpeed;

            if(keys[Keyboard.DOWN])
                player.y += playerSpeed;
            }

        public function KeyDownHandler(event:KeyboardEvent):void{   
            keys[event.keyCode] = true;

        }

        public function KeyUpHandler(event:KeyboardEvent):void{
            keys[event.keyCode] = false;
        }

        public function onTick(evt:TimerEvent):void {
            controls();
        }       
    }
}

You can use a tween library such as TweenLite, which is probably the easiest way. If you want to learn the nuts and bolts of animating in Actionscript, the book Actionscript 3.0 Animation by Keith Peters is second to none.

Possible Duplicate:
Beginner Actionscript reference

Hi everyone, could you please help me, how can I learn ActionScript 3.0?

I know Flash very well, but I don't know ActionScript.

buy/read books. learn the right way as well as starting your own developer's library that you can reference from years to come. don't waste your time with sporadic, often misguided or incomplete online tutorials.

i recommend the following:

  1. Appitizer - ActionScript 3.0 for Adobe Flash Professional CS5 Classroom in a Book
  2. Full Course Meal - Essential ActionScript 3.0
  3. Desert - Adobe Flex 4: Training from the Source, Volume 1
  4. Icing - Actionscript 3.0 Animation: Making Things Move
  5. Updated Icing - AdvancED ActionScript 3.0 Animation

I'd suggest you start off with the basics.

Here is an excellent link:

http://www.kirupa.com/developer/flash/index.htm#ActionScript_Basics

With that, you need to understand datatypes and how they work. Flash is a strongly-typed language, so you need to keep track of datatypes at all times.

This is the reference for the current (Flash Player 10) build of Actionscript 3.0 (compatible with Adobe Flash CS4 and up):

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/index.html

I'd suggest you start off the the flash.display section. That contains the classes beginners are most familiar with, those of course being flash.display.MovieClip and flash.display.Sprite. Here's a link to that package:

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/package-detail.html

Primarily, you need to have a extensive knowledge of the following in Flash to be successful:

  • MovieClips
  • Sprites
  • Arrays
  • ints
  • Numbers
  • Strings

With a good knowledge of those datatypes, you should be well on your way. I guess a good question here would be "how familiar are you with programming logic?". Actionscript 3 is a direct descendant of the ECMAScript spec, ergo, a sibling to Javascript. They each have their own special quirks, but Actionscript 3 and Javascript are quite similar. I've found when learning them in conjunction, comprehension comes much quicker than learning them separately.

Failing these online resources, Essential Actionscript 3.0 by Colin Moock is a must in my opinion. It's a wonderful reference with well-detailed examples that will get you off the timeline (presuming you were on it to begin with) and into Object-Oriented Programming.

Google Books has a free preview of that book here:

http://books.google.ca/books?id=gUHX2fcLKxYC&printsec=frontcover&dq=essential+actionscript+3.0&hl=en&ei=BkVGTcPYPIP4sAOOwMSgCg&sa=X&oi=book_result&ct=result&resnum=1&ved=0CC4Q6AEwAA#v=onepage&q&f=false

Finally, just use Google for any quick snippets or questions you're looking for. I've found googling "(your problem here) as3" can have sufficient results for smaller, more popular issues. Good luck!

-Matt

I want to learn actionscript but I don't know wether to learn AS2 or AS3. Isn't AS3 an upgrade of AS2? I studied Lingo Scripts for Macromedia Director years back... 1998. (intermediate level) Are there any similarities with Action Script and Lingo scripts? Please advice.

Thank you. PpD

Definitely learn ActionScript 3.0 It is more similar to many other languages (in my opinion) and is much more powerful. Admittedly I liked AS2 a lot because it was very flexible and let you get away with terrible code practices, but this is precisely why AS3 is a better choice; it forces you to become a good programmer.

If you are interested in creating games and applets I recommend Foundation ActionScript 3.0 Animation. It has been at my side since AS3 came out

I hav bee struggling with a collision response method, im writing in actionscript 3, for a long time now, and I am hoping someone can explain what this code means, for I have only modified it. I did not write it from scratch. also I am using the Collision Detection Toolkit to find where the collisions are happening.
What im trying to do is make it so that Ball (which is the object that you move around the screen with your keyboard) hit's a wall or object it will not go through the wall or object.

my understanding of this is that you are finding the angle that the collision is happening at and then you need to find the angle which is adjacent which is the new vector and push back the object by however much it's overlapping, but I dont understand how this function works for instance what is

vx0:Number = ball.vx * cos + ball.vy * sin;

finding?. in addition I dont want the ball to accelerate I want it's velocity to be constant until it hits an object. also would it be faster to search through this array backwards?

-- I appreciate any one who takes the time to try and help me with this, and im sorry if I have some misspellings.

     for(i = 0; i < collisions.length; i++) 
        {
            var collision:Object = collisions[i];

            var angle:Number = collision.angle;
            var overlap:int = collision.overlapping.length;
            var ball:Ball = collision.object1;

            var sin:Number = Math.sin(angle);
            var cos:Number = Math.cos(angle);

            var vx0:Number = ball.vx * cos + ball.vy * sin;
            var vy0:Number = ball.vy * cos - ball.vx * sin;

            vx0 = .4;
            ball.vx = vx0 * cos - vy0 * sin;
            ball.vy = vy0 * cos + vx0 * sin;

            ball.vx -= cos * overlap / ball.radius;
            ball.vy -= sin * overlap / ball.radius;
        }

Keith Peters has a wonderful book called Foundation Actionscript 3.0 Animation: Making Things Move.

Chapter 9 covers the topic you're having trouble with.

This page in particular should be of assistance.

http://books.google.ca/books?id=nzyu5TytMEUC&lpg=PP1&dq=actionscript%203.0%20animation&pg=PA235#v=onepage&q&f=false

He uses home-baked, trigonometric collision testing, but you should be able to replace his distance checking with the functions and properties built into Collision Detection Kit.

I am trying to build a stickman in Flex who will a) move across the screen with speed- based on slider value b) do something different (jump/ sit down) when he reaches end of screen

I presume will need to switch between 3-4 images to simulate illusion of movement with parts of body moving. would this approach be right? Are there any similar examples I can learn from?

It depends on how realistic you want it to look.

What you are saying could probably work, but if you wanted to get it looking/behaving really nicely I would recommend the book "ActionScript Animation." There were a couple of chapters in the book about kinetics that walked you through building a man that walked/jumped etc with sliders that could control not only his speed, but gravity, body segments size, etc.

I read the first edition that was on ActionScript 2 but there is a new one for ActionScript 3.

edit

You would want to check out Chapter 13 Forward Kinematics: Making Things Walk

I want to write a game in which there will be some balls on the stage, that will move randomly. They must have unique starting speed and angle and should interfere with each other just like real billiard balls. Is there any physics engine in AS3 that might be useful for this purpose, or will I have to write and model their behavior from the scratch?

well, doing so "from scratch" isn't really much of a challenge if you know what to do. if you're interested in learning i would suggest you pick up Keith Peters' Foundation ActionScript 3.0 Animation book. one benefit from studying the lessons in the book (and perhaps the book's sequel) is that all of the algorithms and logic are easily portable to other languages.

that being said, i believe the most popular physics engine for Flash currently is the popular C++ engine Box2D, which was recently ported to AS3 using Adobe's Alchemy. included in the ActionScript port is a "World Construction Kit" component for Flash Professional.

more here: Box2d Flash Alchemy Port + World Construction Kit

When you have such great tween libraries around, like tweenlite - are mathbased animations becoming obsolete? I'm talking especially about Keith Peters book - Foundation Actionscript 3.0 Animation: Making Things Move!. Can someone skilled in actionscript sort out the differences?