Build a Simple Flash Frisbee Game With AS3
In this tutorial, we’ll build a really simple “keepy-uppy” game. Click the frisbee to send it skyward, then spin it with your mouse to stop it falling to the ground! Collect power-ups to change the size of the disc.
Final Result Preview
Let’s take a look at the final result we will be working towards:
Step 1: Brief Overview
Using pre-made graphic elements we’ll create good looking interface that will be powered by several ActionScript 3 classes.
The user will be able to move a character across the stage, collect upgrade items and beat gravity, you can modify the values in the class to customize the game.
Step 2: Flash Document Settings
Open Flash and create a 320 pixels wide, 480 pixels tall document. Set the Frame rate to 24fps.

Step 3: Interface

A colorful nice looking interface will be displayed, this involves multiple shapes, buttons and more.
Most of the graphics we used have been created in previous tutorials so it won’t be necessary to include their creation.
Step 4: Instance Names

The image above shows the Instance Names used in the MovieClips. The ones that start with a Capital Letter are Library Class Names and should not be on stage, there are also two clouds clips above this graphics, they are called clouds and clouds2.
Step 5: Tween Nano

We’ll use a different tween engine from the default included in flash, this will increase performace as well as it is easier to use.
You can download TweenNano from its official website. Learn how to add it to your project here.
Step 6: Create a new ActionScript Class

Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.
Step 7: Class Structure
Create your basic class structure to begin writing your code.
package
{
import flash.display.Sprite;
public class Main extends Sprite
{
public function Main():void
{
// constructor code
}
}
}
Step 8: Required Classes
These are the classes we’ll need to import for our class to work, the import directive makes externally defined classes and packages available to your code.
import flash.display.Sprite; import flash.events.MouseEvent; import flash.events.Event; import flash.net.navigateToURL; import flash.net.URLRequest; import com.greensock.TweenNano; import com.greensock.easing.Elastic; import flash.utils.Timer; import flash.events.TimerEvent;
Step 9: Variables
These are the variables we’ll use, read the comments in the code to know more about them, some of their names are self explaining so there will be no comment there.
private var firsttime:Boolean = true; private var gravity:int = 2; private var throwSpeed:int; private var xMouse:int; private var xSpeed:int; private var topHeight:int = 40; private var top:Boolean; private var score:int = 0; private var scoreVal:int = 1; private var timer:Timer = new Timer(10000); private var cancelBonus:Timer = new Timer(3000); private var upgrade:Sprite;
Step 10: Constructor
The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object or runs using the Document Class.
It calls the necessary functions to start the game. Check those functions in the next steps.
public function Main():void
{
addGameListeners();
}
Step 11: Add Listeners
In this function we add the initial game listeners required to start the game. We also set the buttonMode property of the Frisbee to true (this will show the hand cursor when mouse over) and hide the position indicator.
private function addGameListeners():void
{
frisbee.addEventListener(MouseEvent.MOUSE_UP, launchFrisbee);
frisbee.buttonMode = true;
indicator.visible = false;
}
Step 12: Launch Frisbee
The first move of the frisbee will activate the timers that are in charge of the upgrades and call the update function which is the principal function of the game.
private function launchFrisbee(e:MouseEvent):void
{
frisbee.removeEventListener(MouseEvent.MOUSE_UP, launchFrisbee);
frisbee.addEventListener(MouseEvent.MOUSE_UP, throwFrisbee);
stage.addEventListener(Event.ENTER_FRAME, update);
timer.addEventListener(TimerEvent.TIMER, showUpgrade);
timer.start();
xSpeed = 0;
xMouse = frisbee.mouseX;
throwSpeed = 0;
}
Step 13: Throw Frisbee
This function resets the variables used to make the frisbee move and fall; it runs every time the frisbee is clicked.
private function throwFrisbee(e:MouseEvent):void
{
xSpeed = 0;
xMouse = frisbee.mouseX;
throwSpeed = 0;
top = false;
}
Step 14: Display Upgrade Bubbles
A timed function will handle the upgrade bubbles. The timer was set in the variables declaration to have an interval of 10 seconds. The first thing to do is check for a previous bubble in screen and remove it if there is one.
private function showUpgrade(e:TimerEvent):void
{
/* Remove previous sprite */
if(upgrade != null)
{
removeChild(upgrade);
upgrade = null;
}
Step 15: Double Points Upgrade
The upgrades are bubbles that appear on screen that will give the player special abilities or enhancements.
The following code calculates a random number (it can be 0 or 1) and instantiates the double points upgrade if the number is 0.
var randomNumber:int = Math.floor(Math.random() * 2);
if(randomNumber == 0)
{
upgrade = new Double();
upgrade.name = 'd';
}
Step 16: Big Frisbee Upgrade
If the calculated number is 1, the big frisbee upgrade is added to the stage. A name is given to the upgrades to determine is value when hit.
else
{
upgrade = new Big();
upgrade.name = 'b';
}
upgrade.x = Math.floor(Math.random() * stage.stageWidth); //give a random x position
addChild(upgrade);
Step 17: Cancel Upgrades
Another timed function.
This will be called when the player grabs the upgrade bubble, counting 3 seconds to end the upgrade effect.
private function cancelUpgrade(e:TimerEvent):void
{
cancelBonus.stop();
cancelBonus.removeEventListener(TimerEvent.TIMER, cancelUpgrade);
scoreVal = 1; //cancel double points
scoreTF.textColor = 0xffffff;
frisbee.scaleX = 1; //Return Scale to normal
frisbee.scaleY = 1;
}
Step 18: Update Function
The principal function of the game, it will handle collisions with the walls, upgrades and the frisbee movement every frame. Being such an important and extensive function, we’ll take a look at it in the next part of this game tutorial.
private function update(e:Event):void
{
}
Step 19: Document Class

Add the class name to the Class field in the Publish section of the Properties panel to associate the FLA with the Main document class.
Step 20: Update Function
The principal function of the game, it will handle collisions with the walls, upgrades and the frisbee movement every frame, learn how it works in the next steps.
private final function update(e:Event):void
{
}
Step 21: Move Frisbee
The frisbee will be moved using the throwSpeed value. This value will change later in the code to make the frisbee go up, when this variable is 0, gravity will move downwards the frisbee.
frisbee.y -= throwSpeed;
Step 22: Gravity
The following code checks if the frisbee has reached the highest point allowed, if not, the throwSpeed variable increases to make it go up. At the same time gravity is applied to the variable causing it to eventually lose its positive value and making the frisbee fall.
if(throwSpeed >= topHeight)
{
top = true;
}
if(throwSpeed < topHeight && !top)
{
throwSpeed += 5;
}
if(throwSpeed <= 0)
{
throwSpeed = 0;
}
throwSpeed -= gravity;
frisbee.y += gravity * 3;
Step 23: Click Position
The x movement of the frisbee is calculated depending on the area the player clicks.
if(xMouse < frisbee.width * 0.5)
{
frisbee.x += xSpeed; //click the left side, so move it right
}
if(xMouse > frisbee.width * 0.5)
{
frisbee.x -= xSpeed; //click the right side, so move it left
}
Step 24: Reduce xSpeed
xSpeed is the value that makes the frisbee move left or right.
This code slows this movement by subtracting its value until the maximum height is reached.
if(xSpeed < topHeight * 0.01 && !top)
{
xSpeed += 1;
}
if(xSpeed <= 0)
{
xSpeed = 0;
}
Let’s stop here to make a quick test and make sure that our code is working:
Step 25: Rotation
To simulate the frisbee movement we rotate the a letter inside it. (This is a movie clip inside the Frisbee movie clip, which has an instance name of aLetter.)
frisbee.aLetter.rotationZ += 50;
Step 26: Score
The score increases when the frisbee leaves the stage and by the time that it’s invisible to the player. If you click it closer to the top the score gained will be higher.
if(frisbee.y < 0)
{
score += scoreVal;
scoreTF.text = String(score);
Step 27: Position Indicator
This indicator follows the x position of the frisbee while it isn’t in stage.
indicator.visible = true; indicator.x = frisbee.x + (frisbee.width * 0.5);
Step 28: Move Background
The next code moves the initial background (if it hasn’t been deleted) and the clouds that will be reused in the game.
if(bg != null){bg.y += throwSpeed;}
clouds.y += throwSpeed;
clouds2.y += throwSpeed;
}
Step 29: Delete Initial Background
The first background will appear only at the start of the game, so it will be deleted when the player can no longer see it.
if(bg != null && bg.y > stage.stageHeight)
{
removeChild(bg);
bg = null;
}
Step 30: Loop Clouds
The clouds backgrounds will appear all the time during the game duration. When a background in no longer visible, its position is reset.
if(clouds.y > stage.stageHeight)
{
clouds.y = -280;
}
if(clouds2.y > stage.stageHeight)
{
clouds2.y = -280;
}
Let’s stop once again to make a quick test and make sure that we have score, indicator, rotation, looping clouds and upgrades (though they do nothing yet…) :
Step 31: Double Points
Double points are added to the score when the 2x upgrade is active, we also change the score textfield color to make the change more visible.
if(upgrade != null && frisbee.hitTestObject(upgrade) && upgrade.name == 'd')
{
removeChild(upgrade);
upgrade = null;
scoreVal = 2;
scoreTF.textColor = 0xf3ba35;
cancelBonus.addEventListener(TimerEvent.TIMER, cancelUpgrade);
cancelBonus.start();
}
Step 32: Big Frisbee
When the player grabs the big bubble, the frisbee scale increases by 1, making it easier to click.
if(upgrade != null && frisbee.hitTestObject(upgrade) && upgrade.name == 'b')
{
removeChild(upgrade);
upgrade = null;
frisbee.scaleX = 2;
frisbee.scaleY = 2;
Step 33: Cancel Upgrades
The current upgrade will only be active for 3 seconds, when that time passes, its powers are cancelled.
cancelBonus.addEventListener(TimerEvent.TIMER, cancelUpgrade); cancelBonus.start();
Step 34: Difficulty
The game difficulty is the gravity, this code changes the gravity based on the score. When the score reaches 100 the gravity increases by 0.5.
if(score >= 100 && score < 102)
{
gravity += 0.5;
}
Step 35: Screen Borders
Invisible walls are used on the sides to prevent the frisbee from going offstage.
if(frisbee.x <= 0)//Left
{
frisbee.x = 0;
}
else if(frisbee.x >= (stage.stageWidth - frisbee.width))//Right
{
frisbee.x = (stage.stageWidth - frisbee.width);
}
Step 36: Game Over
If the frisbee falls all the way to the bottom, the game is over.
if(frisbee.y > stage.stageHeight)
{
gameOver();
}
Step 37: Remove Listeners
The next code disables all mouse events and stops the timer, this will stop the game from performing unwanted activity.
private final function gameOver():void
{
frisbee.removeEventListener(MouseEvent.MOUSE_UP, throwFrisbee);
stage.removeEventListener(Event.ENTER_FRAME, update);
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, showUpgrade);
Step 38: Alert
This function will stop the game and reveal the final score, it also adds a mouse listener to reset the game when clicked.
var alert:AlertView = new AlertView();
alert.buttonMode = true;
alert.x = stage.stageWidth * 0.5;
alert.y = stage.stageHeight * 0.5;
alert.scoreTF.text = scoreTF.text + '!';
alert.addEventListener(MouseEvent.MOUSE_UP, restart);
addChild(alert);
TweenNano.from(alert, 0.7, {y: -alert.height, ease:Elastic.easeOut});
}
Step 39:Restart
The next function will reload the swf, restarting any variable, method and returning to the first screen.
private final function restart(e:MouseEvent):void
{
navigateToURL(new URLRequest(stage.loaderInfo.url), '_level0');
}
We’re done! Try it out:
Conclusion
You’ve created a very entertaining game, try to add your own features and graphics.
I hope you liked this tutorial, thank you for reading!
View full post on Activetuts+

In this tutorial, we’ll build a really simple “keepy-uppy” game. Click the frisbee to send it skyward, then spin it with your mouse to stop it falling to the ground! Collect power-ups to change the size of the disc.
Final Result Preview
Let’s take a look at the final result we will be working towards:
Step 1: Brief Overview
Using pre-made graphic elements we’ll create good looking interface that will be powered by several ActionScript 3 classes.
The user will be able to move a character across the stage, collect upgrade items and beat gravity, you can modify the values in the class to customize the game.
Step 2: Flash Document Settings
Open Flash and create a 320 pixels wide, 480 pixels tall document. Set the Frame rate to 24fps.
Step 3: Interface
A colorful nice looking interface will be displayed, this involves multiple shapes, buttons and more.
Most of the graphics we used have been created in previous tutorials so it won’t be necessary to include their creation.
Step 4: Instance Names
The image above shows the Instance Names used in the MovieClips. The ones that start with a Capital Letter are Library Class Names and should not be on stage, there are also two clouds clips above this graphics, they are called clouds and clouds2.
Step 5: Tween Nano
We’ll use a different tween engine from the default included in flash, this will increase performace as well as it is easier to use.
You can download TweenNano from its official website. Learn how to add it to your project here.
Step 6: Create a new ActionScript Class
Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.
Step 7: Class Structure
Create your basic class structure to begin writing your code.
package { import flash.display.Sprite; public class Main extends Sprite { public function Main():void { // constructor code } } }Step 8: Required Classes
These are the classes we’ll need to import for our class to work, the
importdirective makes externally defined classes and packages available to your code.Step 9: Variables
These are the variables we’ll use, read the comments in the code to know more about them, some of their names are self explaining so there will be no comment there.
Step 10: Constructor
The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object or runs using the Document Class.
It calls the necessary functions to start the game. Check those functions in the next steps.
public function Main():void { addGameListeners(); }Step 11: Add Listeners
In this function we add the initial game listeners required to start the game. We also set the
buttonModeproperty of the Frisbee to true (this will show the hand cursor when mouse over) and hide the position indicator.private function addGameListeners():void { frisbee.addEventListener(MouseEvent.MOUSE_UP, launchFrisbee); frisbee.buttonMode = true; indicator.visible = false; }Step 12: Launch Frisbee
The first move of the frisbee will activate the timers that are in charge of the upgrades and call the
updatefunction which is the principal function of the game.private function launchFrisbee(e:MouseEvent):void { frisbee.removeEventListener(MouseEvent.MOUSE_UP, launchFrisbee); frisbee.addEventListener(MouseEvent.MOUSE_UP, throwFrisbee); stage.addEventListener(Event.ENTER_FRAME, update); timer.addEventListener(TimerEvent.TIMER, showUpgrade); timer.start(); xSpeed = 0; xMouse = frisbee.mouseX; throwSpeed = 0; }Step 13: Throw Frisbee
This function resets the variables used to make the frisbee move and fall; it runs every time the frisbee is clicked.
private function throwFrisbee(e:MouseEvent):void { xSpeed = 0; xMouse = frisbee.mouseX; throwSpeed = 0; top = false; }Step 14: Display Upgrade Bubbles
A timed function will handle the upgrade bubbles. The timer was set in the variables declaration to have an interval of 10 seconds. The first thing to do is check for a previous bubble in screen and remove it if there is one.
private function showUpgrade(e:TimerEvent):void { /* Remove previous sprite */ if(upgrade != null) { removeChild(upgrade); upgrade = null; }Step 15: Double Points Upgrade
The upgrades are bubbles that appear on screen that will give the player special abilities or enhancements.
The following code calculates a random number (it can be 0 or 1) and instantiates the double points upgrade if the number is 0.
var randomNumber:int = Math.floor(Math.random() * 2); if(randomNumber == 0) { upgrade = new Double(); upgrade.name = 'd'; }Step 16: Big Frisbee Upgrade
If the calculated number is 1, the big frisbee upgrade is added to the stage. A name is given to the upgrades to determine is value when hit.
else { upgrade = new Big(); upgrade.name = 'b'; } upgrade.x = Math.floor(Math.random() * stage.stageWidth); //give a random x position addChild(upgrade);Step 17: Cancel Upgrades
Another timed function.
This will be called when the player grabs the upgrade bubble, counting 3 seconds to end the upgrade effect.
private function cancelUpgrade(e:TimerEvent):void { cancelBonus.stop(); cancelBonus.removeEventListener(TimerEvent.TIMER, cancelUpgrade); scoreVal = 1; //cancel double points scoreTF.textColor = 0xffffff; frisbee.scaleX = 1; //Return Scale to normal frisbee.scaleY = 1; }Step 18: Update Function
The principal function of the game, it will handle collisions with the walls, upgrades and the frisbee movement every frame. Being such an important and extensive function, we’ll take a look at it in the next part of this game tutorial.
private function update(e:Event):void { }Step 19: Document Class
Add the class name to the Class field in the Publish section of the Properties panel to associate the FLA with the Main document class.
Step 20: Update Function
The principal function of the game, it will handle collisions with the walls, upgrades and the frisbee movement every frame, learn how it works in the next steps.
private final function update(e:Event):void { }Step 21: Move Frisbee
The frisbee will be moved using the throwSpeed value. This value will change later in the code to make the frisbee go up, when this variable is 0, gravity will move downwards the frisbee.
Step 22: Gravity
The following code checks if the frisbee has reached the highest point allowed, if not, the throwSpeed variable increases to make it go up. At the same time gravity is applied to the variable causing it to eventually lose its positive value and making the frisbee fall.
if(throwSpeed >= topHeight) { top = true; } if(throwSpeed < topHeight && !top) { throwSpeed += 5; } if(throwSpeed <= 0) { throwSpeed = 0; } throwSpeed -= gravity; frisbee.y += gravity * 3;Step 23: Click Position
The x movement of the frisbee is calculated depending on the area the player clicks.
if(xMouse < frisbee.width * 0.5) { frisbee.x += xSpeed; //click the left side, so move it right } if(xMouse > frisbee.width * 0.5) { frisbee.x -= xSpeed; //click the right side, so move it left }Step 24: Reduce xSpeed
xSpeed is the value that makes the frisbee move left or right.
This code slows this movement by subtracting its value until the maximum height is reached.
if(xSpeed < topHeight * 0.01 && !top) { xSpeed += 1; } if(xSpeed <= 0) { xSpeed = 0; }Let’s stop here to make a quick test and make sure that our code is working:
Step 25: Rotation
To simulate the frisbee movement we rotate the a letter inside it. (This is a movie clip inside the Frisbee movie clip, which has an instance name of aLetter.)
Step 26: Score
The score increases when the frisbee leaves the stage and by the time that it’s invisible to the player. If you click it closer to the top the score gained will be higher.
if(frisbee.y < 0) { score += scoreVal; scoreTF.text = String(score);Step 27: Position Indicator
This indicator follows the x position of the frisbee while it isn’t in stage.
Step 28: Move Background
The next code moves the initial background (if it hasn’t been deleted) and the clouds that will be reused in the game.
if(bg != null){bg.y += throwSpeed;} clouds.y += throwSpeed; clouds2.y += throwSpeed; }Step 29: Delete Initial Background
The first background will appear only at the start of the game, so it will be deleted when the player can no longer see it.
if(bg != null && bg.y > stage.stageHeight) { removeChild(bg); bg = null; }Step 30: Loop Clouds
The clouds backgrounds will appear all the time during the game duration. When a background in no longer visible, its position is reset.
if(clouds.y > stage.stageHeight) { clouds.y = -280; } if(clouds2.y > stage.stageHeight) { clouds2.y = -280; }Let’s stop once again to make a quick test and make sure that we have score, indicator, rotation, looping clouds and upgrades (though they do nothing yet…) :
Step 31: Double Points
Double points are added to the score when the 2x upgrade is active, we also change the score textfield color to make the change more visible.
if(upgrade != null && frisbee.hitTestObject(upgrade) && upgrade.name == 'd') { removeChild(upgrade); upgrade = null; scoreVal = 2; scoreTF.textColor = 0xf3ba35; cancelBonus.addEventListener(TimerEvent.TIMER, cancelUpgrade); cancelBonus.start(); }Step 32: Big Frisbee
When the player grabs the big bubble, the frisbee scale increases by 1, making it easier to click.
if(upgrade != null && frisbee.hitTestObject(upgrade) && upgrade.name == 'b') { removeChild(upgrade); upgrade = null; frisbee.scaleX = 2; frisbee.scaleY = 2;Step 33: Cancel Upgrades
The current upgrade will only be active for 3 seconds, when that time passes, its powers are cancelled.
Step 34: Difficulty
The game difficulty is the gravity, this code changes the gravity based on the score. When the score reaches 100 the gravity increases by 0.5.
if(score >= 100 && score < 102) { gravity += 0.5; }Step 35: Screen Borders
Invisible walls are used on the sides to prevent the frisbee from going offstage.
if(frisbee.x <= 0)//Left { frisbee.x = 0; } else if(frisbee.x >= (stage.stageWidth - frisbee.width))//Right { frisbee.x = (stage.stageWidth - frisbee.width); }Step 36: Game Over
If the frisbee falls all the way to the bottom, the game is over.
if(frisbee.y > stage.stageHeight) { gameOver(); }Step 37: Remove Listeners
The next code disables all mouse events and stops the timer, this will stop the game from performing unwanted activity.
private final function gameOver():void { frisbee.removeEventListener(MouseEvent.MOUSE_UP, throwFrisbee); stage.removeEventListener(Event.ENTER_FRAME, update); timer.stop(); timer.removeEventListener(TimerEvent.TIMER, showUpgrade);Step 38: Alert
This function will stop the game and reveal the final score, it also adds a mouse listener to reset the game when clicked.
var alert:AlertView = new AlertView(); alert.buttonMode = true; alert.x = stage.stageWidth * 0.5; alert.y = stage.stageHeight * 0.5; alert.scoreTF.text = scoreTF.text + '!'; alert.addEventListener(MouseEvent.MOUSE_UP, restart); addChild(alert); TweenNano.from(alert, 0.7, {y: -alert.height, ease:Elastic.easeOut}); }Step 39:Restart
The next function will reload the swf, restarting any variable, method and returning to the first screen.
private final function restart(e:MouseEvent):void { navigateToURL(new URLRequest(stage.loaderInfo.url), '_level0'); }We’re done! Try it out:
Conclusion
You’ve created a very entertaining game, try to add your own features and graphics.
I hope you liked this tutorial, thank you for reading!
In this post you’ll learn about a language extension called Traits, a feature of a new Beta of RASE, a smart and modern IDE for Adobe Flash based on Jetbrains MPS. Traits will allow you to use multiple inheritance in your projects, so a class can effectively extend two other classes.
The sample project was created with ActionScript 3.0 with Traits language extension using Realaxy ActionScript Editor (RASE). If you want to do it the same way, RASE can be downloaded here (if you are new to RASE please follow the Beginners guide here)
Why Use Multiple Inheritance?
ActionScript is a modern object-oriented language. At the moment, actual OOP defenition and interpreting assume that multiple inheritance is a vicious practice. Thus, AS itself does not permit multiple inheritance, and only the using of interfaces provides an alternative. It’s all well and good, no need to argue.
However, sometimes it seems unbearable. It happens that owing to this missing feature we make our code too sophisticated or even probably messy.
For instance, we have a class
Creature, which already extendsSprite. We want to teach it how to speak. "A proper OOP" imposes us to make a composition. So we need to:ISpeakerinterface.speak()method toISpeaker.Speakerclass.Creatureclass should be inherited fromISpeaker.Creatureclass. Thespeakmethod would redirect calling ofspeak()to the delegate.Let’s imagine we have multiple inheritance. Then we make a
Speakerclass, inheriting ourCreatureclass from theSpeaker. That’s all, folks.Then, imagine our Creature should be able to do a lot things: to walk, to move arms and legs, to eat, to smile, to cry. Maybe also to fly. You never know what kind of requirements could become a part of the spec. As a result, we gain hundreds and thousands of lines of a “proper” OOP code, which is so redundant and verbose, that understanding its real purpose would be difficult even to its author.
We, skilled Flashers, understand that the situation described is purely artificial. Who would create a pack of interfaces for every aspect of behavior? Even if those would be applicable not only for
Creature. Indeed, the real code would look different, not so pretty and learnedly, but closer to the real world – that is to say, simpler.So it turns out that the best intentions of ECMAScript’s (and, later, ActionScript’s) designers to create a modern and correct OOP language accommodate badly for our everyday work.
Enough complaining! We have a tool to fix it. RASE. Realaxy ActionScript Editor. This solution is Traits, an AS3 language extension.
Let’s proceed to action.
Step 1
First, create a new project with
testTraitsmodule containing main-classCreature.Step 2
Enter the project details as shown here, and click Next:
Step 3
Create a new class called
Creature, in the packagecom.example:Step 4
This code should be created:
Step 5
Import a traits language by pressing Ctrl+L (or Command+L).
Step 6
Create a Speak interface with a single “speak” method.
Step 7
The lower part of the window has two tabs, “Interface” and “Trait“.
Select the “Trait” tab (colored with gray) and click on the empty editors field. A dialog box appears, offering us to create a new trait.
Step 8
After “OK” a default implementation is created by editor. Note how this is now
trait Speakrather thaninterface Speak:Step 9
Add a body to the “
speak” method: just trace “Hello!” to the console.Step 10
In the Creature class add a “Speak” interface to “implements“.
Step 11
The editor added an "i" to the right of the interface name. It means that the interface has a default implementation — it has trait behavior.
Step 12
RASE recognizes such behavior and does not highlight any error when methods are added to class.
That’s it! Our
Creaturecan talk now! Add a call of methodspeak()to a class constructor to prove it.Step 13
Edit the run-configuration.
Step 14
You’ll see this dialog:
Step 15
Press the “+” button to add a new Configuration, and select ActionScript.
Step 16
Enter the details as shown here:
(This way we can be sure we’ll see the trace.)
Step 17
Run the compiled SWF. A "Hello!" message appears in the console.
Here’s what we obtain:
Impl“.implementedlist.Creatureclass is not “littered” with excessive entities. We’ve just ordered the Creature to talk.As a result, we have behavior that is really like multiple inheritance but stands on “proper and correct” OOP recommendations.
Step 18
Let’s see how it works, by looking at the code we’re actually generating.
Click “Build->Generate (obsolete)->Generate Text from Current Model“. The newly generated code of the
Creatureclass appears in the Output window.The code demonstrated above implements a classical composition. The trait language extension hides redundant entities and organizes relationships between code artifacts. In fact, we operate a “pure” OOP code.
Now we see a new fast and easy way to teach our
Creaturehow to do everything. The main thing is the behavior: we apply the same ground rules to another classes.Let’s do it in 5 minutes.
Step 19
Add some new traits — one for each limb — just as we did before:
Step 20
The Creature class gets now a lot of new skills, but its code remains easily-readable and clean. Without the Traits language extension it would be completely different:
It’s time to say goodbye. I’m waiting for your questions, suggestions and comments.
Remember, if RASE is new to you, please read the “Beginners Guide“.
Each month, we bring together a selection of the best tutorials and articles from across the whole Tuts+ network. Whether you’d like to read the top posts from your favourite site, or would like to start learning something completely new, this is the best place to start!
Psdtuts+ — Photoshop Tutorials
Introduction to Digital Art
Photoshop is an excellent tool for manipulating photographs but it can also be used as a means to create stunning digital art. This tutorial is part of a 25-part video tutorial series demonstrating everything you will need to know to start producing digital art in Photoshop. Digital Art for Beginners, by Adobe Certified Expert and Instructor, Martin Perhiniak will begin by teaching you how to draw in Photoshop. At the conclusion of this series you will know all you need to produce your own concept art and matte paintings in Photoshop.
Visit Article
The Making of the Nutty Boat Trip
Most of you probably know how hard it can be to find the perfect stock images for your designs. That means you will often have to get creative and find new ways to create the perfect composition. In this tutorial, we will demonstrate how to place a couple of squirrels in a coffee mug that is floating in a body of water.
Visit Article
Create a Devastating Tidal Wave in Photoshop
Matte painting is a technique that filmmakers use to create backgrounds for scenes that can’t or don’t exist in real life. In the early days, matte paintings were actually painted onto glass. Today, modern filmmakers use digital applications such as Photoshop to produce the backdrops that they need. We have published many matte painting tutorials on this site meant for intermediate and advanced users. This tutorial is part of a series of tutorials that we will be publishing on this meant for those of you who may be relatively new to Photoshop or matte painting in general.
Visit Article
Nettuts+ — Web Development Tutorials
Recently in Web Development (July Edition)
Web development is an industry that’s in a state of constant flux with technologies and jargon changing and mutating in an endless cycle. Not to mention the sheer deluge of information one has to process everyday.
Visit Article
Build your First Game with HTML5
HTML5 is growing up faster than anyone could have imagined. Powerful and professional solutions are already being developed…even in the gaming world! Today, you’ll make your first game using Box2D and HTML5′s
canvastag.Visit Article
Should You Start Using CSSLint?
Getting our code reviewed by a pro is a great way of improving code quality but what happens if you don’t have access to a rockstar programmer? You do the next best thing and grab a ‘lint’ for that language.
Visit Article
Vectortuts+ — Illustrator Tutorials
Community Project: Vectortuts+ Custom Character Jam
Vectortuts+ loves Illustration and discovering new talent, so today we are proud to be launching a new community project that combines both, the Vectortuts+ Custom Character Jam. The best thing is, you can be a part of it! Find out how to get involved, at the jump.
Visit Article
Brandable, Free, Vector People Graphics: Mascots and Character Designs
Need a character or awesome vector mascot for your next design project, grab a set for free today. We’ve rounded up a collection of highly brandable vector people character packs and one off graphics. We have on display a customizable Tuts+ Guy website mascot set, creative mascot graphic pack made by Pasquale D’Silva, a top of the evolutionary ladder geek, a male and female character broken into outfits and parts – ready for animation, and more. Now’s the time to download these vector freebies, so get to it.
Visit Article
Create a Marker Text Effect in Illustrator
In the following tutorial I will show you how to create a marker illustration. This tutorial involves intermediate vector shape building skills in Illustrator to create the markers, along with some layering and script usage to create the text effects. Let’s get started.
Visit Article
Webdesigntuts+ — Web Design Tutorials
Extreme Makeover: jPaginator CSS3 Edition
jPaginator is a nifty jQuery plugin by Remy Elazare which combines pagination and scrolling in a simple user interface. Remy recently asked me if I would like to use it for something on Webdesigntuts+ and I figured it would be a great candidate for a style make-over.
Visit Article
Improving Your Productivity: Quick Tips for Photoshop
In this exclusive web series, Adi Purdila is going to walk you through how to use a handful of web design applications to improve your productivity. Work fast, smarter, and more efficiently! Today’s session: Quick Tips for Photoshop!
Visit Article
Super Simple Lightbox with CSS and jQuery
Rather than using a bloated plugin that has features you’ll never use, this tutorial shows you how to create a super simple lightbox for handling images. It’s perfect for image galleries, portfolios, and more!
Visit Article
Phototuts+ — Photography Tutorials
Everything You Need to Know About Lenses: Part 1
So you’ve purchased your first SLR system, welcome to a new world of photography. You’ve opened Pandora’s Box to a huge range of versatility. One of the major factors that sets SLR cameras apart is their ability to change lenses. In this two-part Basix tutorial, we’re going walk your through everything you’d ever want to know about lenses.
Visit Article
Tips on Creative Car Photography
If you’ve ever tried photographing a car, you’ll know that it’s often not as easy as first presumed. Although it can be simple enough to capture a clear and simple shot of the vehicle, it’s far more challenging to capture the design, detail and essence of the car in a photograph. To help, here are ten simple steps which will hopefully lead you through the basics of car photography.
Visit Article
Understanding the Fundamentals of Camera Sensors
Light travels through a lens, the shutter opens, and a moment is preserved by capturing it on the camera’s sensor. This chip is an absolute essential in creating digital images. However, you may not have a good idea of how it all works. If you’re wanting to demystify the magic of how your digital SLR works, look no further than today’s Basix article all about camera sensors.
Visit Article
Cgtuts+ — Computer Graphics Tutorials
Cgtuts+ Quiz: Know Your CG
Today we’re kicking off something a little different and giving you a chance to test your knowledge of all things computer graphics. This being the first ever Cgtuts+ quiz, we’re starting off fairly easy with 20 questions related to Cg in general. Will you succeed? Will you be victorious? We don’t know, but find out after the jump!
Visit Article
Product Rendering With Fryrender
In this tutorial by author Shaun Keenan, well look at setting up and rendering a product shot inside of RandomControls Fryrender. Shaun will start out by covering the process of setting up and preparing the scene in Maya, before exporting to Fry. Well look at creating light emitting geometry through shaders, as well as creating the jellybean and glass materials, finally well set up and tweak the render settings inside of Fry.
Visit Article
Animation Reference Pack: Facial Expressions – CG Premium Content
Animating characters can be an extremely difficult task, especially without the aid of good reference materials. Today we have the second, in a series of high quality reference footage packs aimed specifically at animators. These videos are available exclusively to our premium members and are available in both 720p and 1080p high definition. Reference pack 2 contains 29 different facial expressions and a total of 116 video files!, created by regular Cgtuts+ contributors Stefan Surmabojov and Georgi Zahariev.
Visit Article
Aetuts+ — After Effects Tutorials
Ink-redible!” Aetuts+ Premium Ink Reveal Bundle + Tutorial
Today’s Premium tutorial will walk you through how use mattes to spice up your next motion graphics piece. We have an amazing download of 12 Ink Mattes and 5 Particle Mattes that were create exclusively for Tuts+ Premium members.
Visit Article
Top Ten After Effects Keyboard Shortcuts – with FREE AE Starter Templates!
These are my Top Ten Favorite After Effects Keyboard Shortcuts that I use most often to help speed up workflow…. speeding up RAM previews, purging those previews, adding keyframes to any property, previewing and scrubbing audio only… check out the video below to see them all!
Visit Article
Aetuts+ Hollywood Movie Title Series -” Transformers – Day 1
Todays tutorial will explain how to make the ’TRANSFORMERS 3″ flying logo style. We will start with the modeling and animation technique of the letters in Cinema 4d. Then proceed with camera movement and the construction of the interior of the “O” letter, with a hi-tech coating. We will complete with the compositing in After Effects.
See your space! TRANSFORMERS.
Visit Article
Audiotuts+ — Audio & Production Tutorials
Quick Tip: How To Get A Clean John Frusciante Tone
In this tutorial I’m going to show how to get that classic and iconic clean-Stratish tone using just modeling technology. I’m using Guitar Rig 4 to get it, but you could use whatever software or real amp, as long as it gives you a Marshall-like tone.
Visit Article
How to Create the ‘Like a G6′ Bassline Sound
If you listen to the radio, go into upscale bars, or dance at the clubs you probably have heard Far East Movement’s ‘Like a G6′. Aside from the icy vocals from the artist Dev, G6 has a very memorable bass line. If you wanted to know how to recreate that sound for a remix or to have it as a sound option in your own track then read on like a G6!
Visit Article
An Introduction to ADSR
As audio engineers we deal with ADSR everyday, even without knowing it. I certainly didn’t know what ADSR was when I first heard it, but it’s the acronym for what happens with every waveform.
Visit Article
Activetuts+ — Flash, Flex & ActionScript Tutorials
Carve Up a Video in Real Time With AS3
Hello, code freaks! This tutorial will show you how to split a running video into blocks as if it has exploded. And all this using just ActionScript. For this tutorial we’ll use the camera as the video source, so you can see the changes live.
Visit Article
Get Control of Your AS3 Event Flow With Signals
In this screencast we’ll go over all you need to know about AS3 Signals – a light-weight strongly-typed alternative to the native Flash event system. Prepare to see events in a whole new way!
Visit Article
Fixing Bugs in AS3: Introduction
In this tutorial, I’ll describe some of the basic information you need to debug your Flash applications. Finding and resolving errors in your ActionScript is no small task, so this is actually just the first article of a series. In this installment, we’ll take a look at some of the general things you can do to help track down your bugs.
Visit Article
Wptuts+ —WordPress Tutorials
Tips for Creating WordPress Themes That Sell
The growing market for premium WordPress themes has made competition tougher than ever. Customers are demanding higher quality and greater functionality leaving theme developers searching for new ways to make their work stand out. Knowing what makes one theme sell better than another can be difficult, but remembering a few basic rules can make a big difference in your total sales.
Visit Article
Code Snippets WP Theme Developers Should Have on Speed Dial
One of the ways we endeavor to improve productivity when building WordPress templates is to have snippets of code available to us very quickly, through the use of tab-triggered shortcuts. In this article I will share with you 10 of my most-used snippets that I feel every developer should have at their fingertips.
Visit Article
The Definitive Check List for Publishing Your WordPress Plugin
When you are getting close to completing your WordPress plugin, it’s time to start thinking about releasing it to the broader public. Getting ready for publishing a plugin requires a lot of polishing, testing and fine tuning, and it’s easy to forget some steps in the process. This tutorial will guide you through publishing the plugin in the WordPress plugin directory and work as a check list to help you make sure your plugin will be ready for the prime time by the time you hit publish.
Visit Article
Mobiletuts+ — Mobile Development Tutorials
Android SDK: Enabling Google Analytics to Gather App Statistics
Google Analytics is a service provided by Google that makes it easy to track what users do. Recently, the Google Analytics team released an Analytics SDK for mobile platforms including Android, iOS (Apple), and mobile websites. In this tutorial, learn how to include and enable this technology within your Android projects to gather important information about how users are using your applications.
Visit Article
Corona SDK: Creating a Scrolling Background
The Corona SDK makes game development for the iPhone, iPad, and Android easy. Corona uses the Lua programming language to create cross-platform apps. In this tutorial we will explore how to create a scrolling background with the Corona SDK.
Visit Article
Better Apps By Design
Most mobile apps are missing that extra bit of design detail that could help them stand out from the App Store crowd. While there is no replacement for having a talented designer polish your app’s pixels for hours on end, the purpose of this series is to teach those with limited Photoshop experience and a low-to-no budget how to make apps that shine!
Visit Article
Thanks for Reading!
We love bringing you the latest and greatest tutorials each month, and would like to take this opportunity to say thanks for reading, subscribing, and offering your feedback. If you have any suggestions for tutorials, or Tuts+ in general, feel free to leave them below in the comments!
As ever, the best way to support the sites (and get your hands on superb, industry-leading tutorials) is to join our Premium program. It costs just $9 per month, and will be the best few dollars you ever spend! There’s also no risk, thanks to our 100% money-back guarantee.
Time for your latest fix of industry news. This week we learn about Adobe’s brand new HTML5 platform, Edge; a new resource for creative HTML5 and CSS3 demos; and a Google Chrome extension that lets you search the AS3 LiveDocs via the omnibox.
Adobe Edge Preview Available on Labs
Anyone who was at Adobe MAX last year will remember a prototype that was shown during the Sneaks called “Project EDGE” – which demonstrated an animation platform which targeted HTML5, JavaScript, and CSS3. Over the past few weeks, Adobe has been hinting that something would be coming down the pipeline and has released a number of short demo videos around a product called “Adobe Edge”. As of today, Adobe Edge Preview 1 is available for download on Adobe Labs (currently for free).
Note that this is a very early build of Edge. Many public previews are planned as functionality is added to the product and its features are enhanced. Check it out and let Adobe know what you think!
Read More on This Subject:
The Expressive Web (Beta)
Adobe has also just launched a new beta resource website, called The Expressive Web. This is a project which Adobe has put together with the goal of creating both a resource and showcase that highlights some of the most creative and expressive features being added to the web today.
In addition to highlighting and providing information on 12 new HTML5 and CSS3 features, the site itself makes extensive use of new features such as CSS3 Transitions, CSS3 Transform, Web Storage and more to provide a visually compelling resource for learning more about HTML5 and CSS3.
Read More on This Subject:
ActionScript 3.0 Search for Chrome
For ActionScript developers, there is an interesting new add on for the Google Chrome web browser that allows AS3 LiveDocs searching through the omnibox. Pretty convenient for Chrome users!
Read More on This Subject:
Twitter and Google+ are great places to keep up to date with what’s happening with Flash and Unity, and to find excellent tips shared by other people. I’ve rounded up the most interesting posts I’ve seen from the past two weeks; if you’re not on social networks, come and take a look at what you’re missing!
AS3 LiveDocs: Updated and Now Searchable From Chrome
Via @tekkie and @elsassph
The AS3 LiveDocs have been updated with a new version, containing preview content for Flash Player 11 and AIR 3.0. If you’re working with the beta versions (or just curious as to what’s new), take a look.
In other LiveDocs news, Michael Safyan has released a Chrome extension that lets you search the AS3 LiveDocs via the omnibox (address bar). Just type ‘AS3′ in the bar, hit Tab, then type whatever you want to search and press Enter.
Guide to Beginning Flash Game Development
Via @AdobeUK
Sam Rivello has written a wide-ranging guide on getting started with Flash platform game development. It offers a brief look at a huge number of topics: coming up with an idea, getting to grips with AS3, testing your creations, optimizing your code, monetizing what you’ve made, tracking stats, security…
Each piece of advice has links to other articles where you can learn more about the topic. Definitely worth a read, especially if you’re new to Flash or to game development in general!
Speed Up Your AS3 Lookups With an Unnecessary Cast
Via Merlin Gore
It turns out that if you replace this:
…with this:
…then you’ll speed up your lookups by a remarkable amount:
See Jackson Dunstan’s article for more.
Google+ Games Are Coming
Via John West
SlashGear reports that Google+’s help pages mention a “Games stream” — or, rather, mentioned, since the reference has since been removed. Anyone surprised? I don’t think it’s going out on a limb to assume that Flash and Unity games will be able to interface with this.
Adobe AIR Marketplace Will Shut Down on August 31st
Via Joseph Labrecque
The Adobe AIR Marketplace was launched as a place where AIR developers could sell or distribute their creations — like the App Store or Android Market, but exclusively for AIR apps. But, as Adobe explain in the recently-rewritten FAQ, the Marketplace will be shut down on August 31st.
Chester Grant’s Advice to Young Programmers
Via @JosephLabrecque
A snappy list of tips for new programmers of any platform. I wouldn’t say I agree 100% with all of them, but it’s great advice as a whole. The comments are worth a read, too.
Tip #6 has served me well:
…though there are plenty more advantages to having developer friends than gaining work referrals!
What’s the Deal With Signals?
Via @stray_and_ruby
Did you see Karl Macklin’s screencast introduction to Signals that we published recently? Augment it with this article by Justin J Moses.
Action Gameplay Flow
Via Alec Holowka
Not strictly to do with Flash or Unity, but relevant for game designers: great lessons on building and maintaining flow in action games, mainly influenced by Metroid Fusion:
Calculating Dimensions of Isometric Tiles
By Lorenzo Nuvoletta
Lorenzo has written a useful bite-sized tip on finding the angle and side length of a tile that’s been turned into an isometric rhombus.
New Version of Unity
Via Eric Heimburg
Unity 3.4 is out! The main improvements are:
Allegorithmic Substance Integration
Editor Improvements for More Efficient Game Development
Check out the full list here. If you’re new at Unity, check out Matt Stuttard’s Getting Started with Unity Session.
Mochi London, August 27th-28th
Via Merlin Gore
This sounds like fun: a day of presentations (by developers including Iain Lobb, Merlin Gore, and Mike Jones), followed by a day hanging out at the pub with fellow Flash game creators. It’s organized by Mochi Media, and it’s free, too! More details are available here.
Something for the Weekend: BioGems
Via Terry Paton
We’ll finish off with a great casual game: BioGems, which is a cross between a match-3 game and an RPG battler: match three “attack” gems to deal damage to your opponent; match three “health” gems to regain HP; and so on. The gameplay is solid and fun, the cartoon fighters are a strange mixture of adorable and deadly, and the music will be stuck in your head for hours afterwards. All in all, a fantastic casual game.
That’s It for Now!
If you want to get this kind of information sooner, follow all the people mentioned above! You can also follow me on Twitter and Google+, and you can follow @envatoactive on Twitter.
Imagine a chain of particles animating in symphony together: A train moving as all attached compartments follow suit; a puppet dancing as its master pulls its string; even your arms, when your parents hold your hands as they lead you in an evening walk. Movevment ripples down from the last node to the origin, abiding to constraints as it goes. This is inverse kinematics (IK), a mathematical algorithm that calculates necessary motions. Here, we’ll use it to create a snake that’s a little more advanced than the one from Nokia games.
Final Result Preview
Let's take a look at the final result we will be working towards. Press and hold UP, LEFT and RIGHT keys to make it move.
Step 1: Relationships in a Chain
A chain is constructed of nodes. Each node represents a point in the chain where translation and rotation may happen. In IK chain, motion ripples down in reverse from the last node (last child) to the first node (root node) as opposed to Forward Kinematics (FK) where kinematics traverse from the root node to the last child.
All chains begins with the root node. This root node is the acting parent unto which a new child node is attached. In turn, this first child will parent the second child in the chain, and this is repeated until the last child is added. The animation below depicts such a relationship.
Step 2: Remembering Relationships
The
IKshapeclass implements the notion of a node in our chain. Instances of IKshape class remember their parent and child nodes, with the exceptions of the root node which has no parent node and the last node which has no child node. Below are the private properties of the IKshape.Accessors of these properties are shown as below:
public function set IKchild(childSprite:IKshape):void { childNode = childSprite; } public function get IKchild ():IKshape { return childNode } public function set IKparent(parentSprite:IKshape):void { parentNode = parentSprite; } public function get IKparent():IKshape { return parentNode; }Step 3: Vector from Child to Parent
You may notice that this class does store a Vector2D that points from child node to parent node. The rationale for this direction is due to motion flowing from child to parent. Vector2D is used because the magnitude and direction of vector pointing from child to parent will be manipulated frequently while implementing behaviour of an IK chain. Thus, keeping track of such data is necessary. Below are methods to maniplate vector quantities for IKshape.
public function calcVec2Parent():void { var xlength:Number = parentNode.x - this.x; var ylength:Number = parentNode.y - this.y; vec2Parent = new Vector2D(xlength, ylength); } public function setVec2Parent(vec:Vector2D):void { vec2Parent = vec.duplicate(); } public function getVec2Parent():Vector2D { return vec2Parent.duplicate(); } public function getAng2Parent():Number { return vec2Parent.getAngle(); }Step 4: Drawing Node
Last but not least, we need a method to draw our shape. We shall draw a rectangle to represent each node. However, any other preferences can be put in by overriding the draw method here. Iv included an example of a class overriding the default draw method, the Ball class. (A quick switch between shapes will be demonstrated at the end of this tutorial.) With this, we complete the creation of the Ikshape class.
protected function draw():void { var col:Number = 0x00FF00; var w:Number = 50; var h:Number = 10; graphics.beginFill(col); graphics.drawRect(-w/2, -h/2, w, h); graphics.endFill(); }Step 5: The IK Chain
IKine class implements behaviour of an IK chain. Explanation regarding this class follows this order
Step 6: The Data in a Chain
Code below shows the IKine class private variables.
Step 7: Instantiate the Chain
IKine chain will store a Sprite datatype that remembers the relationship of its parent and child. These sprites are instances of IKshape. The resultant chain sees the root node at index 0, the next child at index 1, … until the last child in sequential manner. However, construction of chain is not from root to last child; it is from last child to root.
Assuming that the chain is of length n, construction follows this sequence: n-th node, (n-1)-th node, (n-2)-th node … 0-th node. The animation below depicts this sequence.
Upon instantiation of IK chain, the last node is inserted. Parent nodes will be appended later. The last node appended is the root. The code below are methods of IK chain construction, appending and removing nodes to chain.
public function IKine (lastChild:IKshape, distance:Number) { //initiate all private variables IKineChain = new Vector.<IKshape>(); constraintDistance = new Vector.<Number>(); constraintRangeStart = new Vector.<Number>(); constraintRangeEnd = new Vector.<Number>(); //Set constraints this.IKineChain[0] = lastChild; this.constraintDistance[0] = distance; this.constraintRangeStart[0] = 0; this.constraintRangeEnd[0] = 0; } /*Methods to manipulate IK chain */ public function appendNode(nodeNext:IKshape, distance:Number = 60, angleStart:Number = -1*Math.PI, angleEnd:Number = Math.PI):void { this.IKineChain.unshift(nodeNext); this.constraintDistance.unshift(distance); this.constraintRangeStart.unshift(angleStart); this.constraintRangeEnd.unshift(angleEnd); } public function removeNode(node:Number):void { this.IKineChain.splice(node, 1); this.constraintDistance.splice(node, 1); this.constraintRangeStart.splice(node, 1); this.constraintRangeEnd.splice(node, 1); }Step 8: Getting Chain Nodes
These following methods are used to retrieve nodes from the chain whenever there's a need.
public function getRootNode():IKshape { return this.IKineChain[0]; } public function getLastNode():IKshape { return this.IKineChain[IKineChain.length - 1]; } public function getNode(node:Number):IKshape { return this.IKineChain[node]; }Step 9: Constraints
We have seen how the chain of nodes is being represented in an array: Root node at index 0, … (n-1)-th node at index (n-2), n-th node at index (n-1), n being length of chain. We can conveniently arrange our constraints in such order as well. Constraints come in two forms: distance between nodes and degree of bending freedom between nodes.
Distance to maintain between nodes is recognised as a child node's constraint upon its parent. For the sake of referencing convenience, we can store this value as
constraintDistancearray with index similar to that of the child node's. Note that the root node has no parent. However, distance constraint should be registered upon appending the root node so that if the chain is extended later, the newly-appended "parent" of this root node can utilise its data.Next, the angle of bending for a parent node is restricted to a range. We shall store the start and end point for range in
constraintRangeStartandConstraintRangeEndarray. Figure below shows a child node in green and two parent nodes in blue. Only the node marked "OK" is allowed because it lies within the angle constraint. We can use similar approach in referencing values in these arrays. Note again that root node's angle constraints should be registered even though not in use due to similar rationale as previous. Plus, angle constraints does not apply to the last child because we want flexibility in control.Step 10: Constraints: Getting and Setting
The methods as follow may prove useful when you have initiated constraints on a node but would like to alter the value in future.
/*Manipulating corresponding constraints */ public function getDistance(node:Number):Number { return this.constraintDistance[node]; } public function setDistance(newDistance:Number, node:Number):void { this.constraintDistance[node] = newDistance; } public function getAngleStart(node:Number):Number { return this.constraintRangeStart[node]; } public function setAngleStart(newAngleStart:Number, node:Number):void { this.constraintRangeStart[node] = newAngleStart; } public function getAngleRange(node:Number):Number { return this.constraintRangeEnd[node]; } public function setAngleRange(newAngleRange:Number, node:Number):void { this.constraintRangeEnd[node] = newAngleRange; }Step 11: Length Constraint, Concept
The following animation shows the calculation of length constraint.
Step 12: Length Constraint, Formula
In this step, we'll have a look at commands in a method that help to constrain distance between nodes. Note the highlighted lines. You may notice only the last child is applied this constraint. Well, as far as the command goes, this is true. Parent nodes are required to fulfill not only length but angle constraints. All these are handled with the implementation of method vecWithinRange(). Last child need not be constrained in angle because we need maximum bend flexibility.
private function updateParentPosition():void { for (var i:uint = IKineChain.length - 1; i > 0; i--) { IKineChain[i].calcVec2Parent(); var vec:Vector2D; //handling the last child if ( i == IKineChain.length - 1) { var ang:Number = IKineChain[i].getAng2Parent(); vec = new Vector2D(0, 0); vec.redefine(this.constraintDistance[IKineChain.length - 1], ang); } else { vec = this.vecWithinRange(i); } IKineChain[i].setVec2Parent(vec); IKineChain[i].IKparent.x = IKineChain[i].x + IKineChain[i].getVec2Parent().x; IKineChain[i].IKparent.y = IKineChain[i].y + IKineChain[i].getVec2Parent().y; } }Step 13: Angle Constraint, Concept
First, we calculate the current angle sandwiched between the two vectors, vec1 and vec2. If the angle is not within the constrained range, assign the minimum or maximum limit to the angle. Once an angle is defined, we can calculate a vector that is rotated from vec1 together with the constraint of distance (magnitude).
The following animation offers another alternative to visualising the idea.
Step 14: Angle Constraint, Formula
The implementation of the angle constraints is as below.
private function vecWithinRange(currentNode:Number):Vector2D { //getting the appropriate vectors var child2Me:Vector2D = IKineChain[currentNode].IKchild.getVec2Parent(); var me2Parent:Vector2D = IKineChain[currentNode].getVec2Parent(); //Implement angle bounds limitation var currentAng:Number = child2Me.angleBetween(me2Parent); var currentStart:Number = this.constraintRangeStart[currentNode]; var currentEnd:Number = this.constraintRangeEnd[currentNode]; var limitedAng:Number = Math2.implementBound(currentStart, currentEnd, currentAng); //Implement distance limitation child2Me.setMagnitude(this.constraintDistance[currentNode]); child2Me.rotate(limitedAng); return child2Me }Step 15: Angle with Directions
Perhaps it is worthy to go through here the idea of getting an angle that interprets clockwise and counter-clockwise direction. The angle sandwiched between two vectors, say vec1 and vec2, can be easily obtained from the dot product of those two vectors. The output will be the shortest angle to rotate vec1 to vec2. However, there is no notion of direction as the answer is always positive. Therefore modification on the regular output should be done. Before outputing the angle, I used vector product between vec1 and vec2 to determine whether the current sequence is positive or negative rotation and incorporated the sign into the angle. I have highlighted the directional feature in lines of code below.
public function vectorProduct(vec2:Vector2D):Number { return this.vec_x * vec2.y - this.vec_y * vec2.x; } public function angleBetween(vec2:Vector2D):Number { var angle:Number = Math.acos(this.normalise().dotProduct(vec2.normalise())); var vec1:Vector2D = this.duplicate(); if (vec1.vectorProduct(vec2) < 0) { angle *= -1; } return angle; }Step 16: Orienting Nodes
Nodes that are boxes needs to be oriented to the direction of their vectors so that they look nice. Otherwise, you will see a chain like below. (Use the arrow keys to move.)
The function below implements the right orientation of nodes.
private function updateOrientation():void { for (var i:uint = 0; i < IKineChain.length - 1; i++) { var orientation:Number = IKineChain[i].IKchild.getVec2Parent().getAngle(); IKineChain[i].rotation = Math2.degreeOf(orientation); } }Step 17: Last Bit
Now that everything is set, we can animate our chain using
animate(). This is a composite function making calls toupdateParentPosition()andupdateOrientation().However before that can be achieved, we have to update relationships on all nodes. We make a call toupdateRelationships(). Again,updateRelationships()is a composite function making calls todefineParent()anddefineChild(). This is done once and whenever there's a change in the chain structure, eg nodes are added or dropped at runtime.Step 18: Essential Methods in IKine
In order to make IKine class work for you, these are the few methods you should look into. I’ve documented them in a table form.
Note that angle inputs are in radians not degrees.
Step 19: Creating a Snake
Now lets create a project in FlashDevelop. In the src folder you will see Main.as. This is the sequence of tasks you should do:
Step 20: Draw Objects
Object is drawn as we construct IKshape. This is done in a loop. Note if you'd like to change the outlook of the drawing to a circle, enable comment on line 56 and disable comment on line 57. (You’ll need to download my source files in order for this to work.)
private function drawObjects():void { for (var i:uint = 0; i < totalNodes; i++) { var currentObj:IKshape = new IKshape(); //var currentObj:Ball = new Ball(); currentObj.name = "b" + i; addChild(currentObj); } }Step 21: Initialise Chain
Before initialising the IKine class to construct the chain, private variables of Main.as are created.
For the case here, all nodes are constrained to a distance of 40 between nodes.
private function initChain():void { this.lastNode = this.getChildByName("b" + (totalNodes - 1)) as IKshape; currentChain = new IKine(lastNode, 40); for (var i:uint = 2; i <= totalNodes; i++) { currentChain.appendNode(this.getChildByName("b" + (totalNodes - i)) as IKshape, 40, Math2.radianOf(-30), Math2.radianOf(30)); } currentChain.updateRelationships(); //center snake on the stage. currentChain.getLastNode().x = stage.stageWidth / 2; currentChain.getLastNode().y = stage.stageHeight /2 }Step 22: Add Keyboard Controls
Next, we declare variables to be utilised by our keyboard control.
Attach onto stage the main loop and keyboard listeners. I’ve highlighted them.
private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); // entry point this.drawObjects(); this.initChain(); leadingVec = new Vector2D(0, 0); stage.addEventListener(Event.ENTER_FRAME, handleEnterFrame); stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown); stage.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp); }Write the listeners.
private function handleEnterFrame(e:Event):void { if (pressedUp == true) { currentMagnitude += increaseMag; currentMagnitude = Math.min(currentMagnitude, capMag); } else { currentMagnitude *= decreaseMag; } if (pressedLeft == true) { currentAngle -= Math2.radianOf(increaseAng); } if (pressedRight == true) { currentAngle += Math2.radianOf(increaseAng); } leadingVec.redefine(currentMagnitude, currentAngle); var futureX:Number = leadingVec.x + lastNode.x; var futureY:Number = leadingVec.y + lastNode.y; futureX = Math2.implementBound(0, stage.stageWidth, futureX); futureY = Math2.implementBound(0, stage.stageHeight, futureY); lastNode.x = futureX; lastNode.y = futureY; lastNode.rotation = Math2.degreeOf(leadingVec.getAngle()); currentChain.animate(); } private function handleKeyDown(e:KeyboardEvent):void { if (e.keyCode == Keyboard.UP) { pressedUp = true; } if (e.keyCode == Keyboard.LEFT) { pressedLeft = true; } else if (e.keyCode == Keyboard.RIGHT) { pressedRight = true; } } private function handleKeyUp(e:KeyboardEvent):void { if (e.keyCode == Keyboard.UP) { pressedUp = false; } if (e.keyCode == Keyboard.LEFT) { pressedLeft = false; } else if (e.keyCode == Keyboard.RIGHT) { pressedRight = false; } }Notice that I’ve used a Vector2D instance to lead the snake moving around the stage. I’ve also constrained this vector within the boundary of stage so it will not move out. The Actionscript performing this constraint is highlighted.
Step 23: Animate!
Press Ctrl+Enter to see your snake animate!. Control its movement using the arrow keys.
Conclusion
This tutorial does require some knowledge in Vector Analysis. For readers who would like to get a familiar look at vectors, do have a read on the post by Daniel Sidhon. Hope this helps you in understanding and implementing inverse kinematics. Thanks for the read. Do drop suggestions and comments as Im always eager to hear from audiences. Terima Kasih.
In this tutorial, I’ll describe some of the basic information you need to debug your Flash applications. Finding and resolving errors in your ActionScript is no small task, so this is actually just the first article of a series. In this installment, we’ll take a look at some of the general things you can do to help track down your bugs.
The Different Kinds of Error
First, let’s discuss what an error is. There are three broad categories of errors, in no particular order:
In order to differentiate between these, it’s helpful to understand the process of how a SWF is made and presented.
In the process of creating a Flash movie (or application, or whatever you want to call it), you write ActionScript and create graphical assets that are used by the movie. You may use Flash Professional, or Flash Builder and the Flex Framework, or a third-party editor and IDE like FlashDevelop or FDT. In all cases, the work you do to create your movie is known as authoring and the time you spend doing that is referred to as author-time.
At some point, you will want to see the things that you author presented as they would to the end user. Before you can see this, though, the author-time assets (ActionScript, drawings, images, fonts and text, etc) need to be compiled into the SWF that the end user sees. When you hit “Publish” or “Test Movie” in Flash, or “Run” in Flash Builder, you are compiling your SWF. The program you are using to author will take your author-time assets and compile them into a SWF. The time it takes to do this is called compile-time, as in, the things that happen in this stage are said to happen at compile-time.
Finally, you get to run the SWF in the Flash Player and see how it will look and work when presented. This happens in the browser with the Flash Player plugin, or right in Flash Professional when you choose “Test Movie”, or as an AIR application running on the desktop (or mobile device). No matter the specifics of how the SWF is being presented, it is now running and we are now experiencing run-time. The SWF is being executed by the Flash Player, and all of your compiled code and graphics are visible.
Usually, all of this happens for you; if you use Flash Professional, choosing “Test Movie” will compile the SWF and then run it in its own Flash Player. If you use Flash Builder, choosing “Run” will compile the SWF and then launch it in a browser. This three-stage process is generally something that you don’t think about, which is why I’m taking the time to discuss it in detail.
Now, on the to the errors, and how they relate to these stages.
Compiler Errors are errors in your code that pop up at compile-time. There is something so fundamentally wrong with your code that the compiler stops in its tracks and says, “Whoah, if we continue, your SWF will be seriously messed up. I can’t do it. I just can’t.” Well, OK, it’s not normally so melodramatic, but it will bail at the first sign of trouble and make sure you aren’t given the satisfaction of seeing your SWF run before you fix the problems.
These are generally syntax errors — like missing or mis-matched braces — or else type mis-matches; things that a machine can look at and know is wrong. These are errors that you will see in the Compiler Errors panel in Flash Professional.
The Compiler Errors Panel
The Compiler Errors Panel
Run-time Errors are errors that happen while the SWF is running. In this case, the code is syntactically correct, as it made its way past the compiler without errors (we know this because the SWF is running). But the code still has some flaw in it that caused it to run in a way that the Flash Player doesn’t like; it either doesn’t know what to do with this unexpected result or it’s causing an error to let you know that something failed at run-time.
In these cases, you get an official error detailing the problem and at least a general indication of where in your code it occurred. In Flash Professional, you’ll see these when you “Test Movie” in the Output panel.
A run-time Error in the Output Panel
Logical Errors are basically errors in how your program is controlled. These aren’t compiler errors; the SWF is compiled and running. These aren’t run-time errors; Flash Player hasn’t thrown up a big error message in your face. Everything is technically correct and working, but they’re not working the way you want them to. Maybe the grid you laid out programmatically has one too many columns, or the shopping cart total is not being calculated correctly, or a user-entered email address is being validated as unacceptable when really it is, or a sequence of images displays in the wrong order.
These are the hardest errors to find, because they can only be found by using the SWF the way it was intended to be used, and comparing the actual results closely with what you expected to happen. And once found, you don’t get any helpful error messages giving you any idea of what went wrong.
Even though we got this far without compiler or run-time error, something is wrong: we’re missing a zero on the price.
Compiler Errors: Finding the Problem
Compiler Errors are usually the easiest to deal with. That’s because, for one, the compiler stops in its tracks and tells you about the error, and for two, the compiler error itself tells you what’s wrong, tells you the file and line number, and even prints out that line of code for your reference.
Compiler errors show up in the Compiler Errors panel, so lets take a closer look at this particular element of the Flash IDE:
The Compiler Errors Panel, Again
As you can see in the annotated diagram above, each error is listed on it’s own line. Each line consists of the same basic information. In the first column, you’ll get the file name and line number on which the error was found. In the above example, the error occurs in a class file. If you wrote code directly in the Script panel, then you’ll get something like “
Scene 1, Layer 'Layer 1', Frame 1, Line 1” which is the same thing, only for non-text-file-based code.Knowing where the error happens is useful, but the second column contains information on why the error occurred. The first bit is the error number, which is like an ID. Each type of error gets its own number. This is followed by an textual description of the error. Now, to be fair, Adobe has some rather obtusely worded error descriptions, and in future articles in this series, we’ll try to decipher some of the more common ones so that you can more effectively deal with them. Until then, we can at least learn that the error number is associated with the error description. The text in the description might get customized to present some contextual relevance, like using the variable or function name from your source code, but the general error is tied to the number. For example, Error 1067 is a coercion error, regardless of whether it’s a coercion of a String to a DisplayObject or of an Array to an ExternalInterface.
A complete list of Complier Errors can be found at this page from Adobe’s ActionScript documentation:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/compilerErrors.html
Some errors are given more thorough explanations on this page.
Compiler Errors: Resolving the Problem
The great thing about compiler errors is that they are pretty easy to find. Not only do they pop up and prevent you from running your SWF, but you can get to the troublesome code very easily from the Compiler Errors panel. Just double-click any error in the panel and the relevant source file will open up, with your cursor on the right line. Now, if you use Flash Professional with an external editor, you will find yourself double-clicking your way into editing the file in Flash Professional. This may be against your reasons for using an external editor, but at least the error finding is usually pretty quick and you can get it done pretty painlessly. Even if you’re using CS5 with the tight Flash Builder integration, double-clicking the error brings up the file in Flash Professional, not Flash Builder. But Flash Builder has its own compiler error panel, which works in much the same way.
The Flash Builder Compiler Errors panel, or the "Problems" panel
At this point, it’s a matter of going to the line of code specified by the error, and fixing it.
Run-time Errors: Finding the Problem
Once you get through the compiler errors, your SWF will be able to run, but at this point you may run into run-time errors. These happen for any number of reasons — again, we’ll be exploring these later in this series — but for now, let’s explore the anatomy of a run-time error. Here is a typical run-time error as displayed while the SWF is running from “Test Movie” in Flash Professional:
The Output panel displaying a run-time error
There is potentially going to be a lot of text spit out at you when an error shows up. It may seem a little intimidating initially, but it’s really just two main sections:
The two main sections of the run-time error
As annotated above, the first bit of the error is the description of what happened. Like compile-time errors, each type of run-time error has an error number, which is associated with a short textual description. The description includes an error type as well as a nerd-speak sentence. The error type might be useful for getting a broad sense of what’s going on, but the description is what really tells you the problem. We’ll take a look at an example shortly.
The second main piece is any text following the first bit, called the stack track or call stack and we’ll get deeper into that in the next step.
Like compile-time errors, the textual descriptions leave a bit to be desired. Once you get a handle on what some of the more oft-seen errors mean, though, you’ll have an idea of what’s wrong and will know where to look.
A complete list of run-time errors is documented here, some of which have notes along with them:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/runtimeErrors.html
Run-time Errors: Understanding the Stack Trace
Let’s turn to the second main bit of the run-time error, the stack trace. It can range in length anywhere from one line to a finite-yet-very-large number of lines. The purpose of this stack trace is to notify you of where in your code the error occurred.
Each line in the stack trace represents a single function execution. The top-most line names the function in which the error actually occurred; it contains the line of code that blew everything up. The second line in the stack trace names the function that called the function that caused the error. The third line names the function that called the function that called the function in which the error occurred. And…you get the idea. But let’s illustrate it more practically. In the following code, the function
thirdwill cause a run-time error by trying to add “nothing” to the display list. However, we don’t call it right away; we start things off by calling thefirstfunction, which calls thesecondfunction, which in turn finally calls thethirdfunction:first(); function first():void { second(); } function second():void { third(); } function third():void { var s:Sprite; addChild(s); }If you paste that code in the Script panel of a brand new Flash file, and run it, you see the following error:
TypeError: Error #2007: Parameter child must be non-null. at flash.display::DisplayObjectContainer/addChild() at Untitled_fla::MainTimeline/third() at Untitled_fla::MainTimeline/second() at Untitled_fla::MainTimeline/first() at Untitled_fla::MainTimeline/frame1()Now, we know that the error was due to sending an uninitialized
Spritevariable toaddChild. The function that actually threw the error (that’s the technical term; when an error occurs, it means that the error was thrown by a specific line of code. I like to think of it as similar to throwing a tantrum) is theaddChildmethod, and so it’s at the top of the list. The next three lines are the functions we wrote, listed most-recent-first. It ends (or begins, depending on how you look at it) with a call toframe1in the main timeline. This is just the method that kicks off the SWF. If you had a document class set up, you’d see that instead. Since this example just used a script in the first frame, we getframe1.The point is that calling
frame1ultimately led to an erroneous call toaddChild, and you can follow that path of logic by reading the stack trace.This complete list of function calls might appear to just be a mess of information you don’t need, but there are a number of times when it can help you narrow in on your bug. If the error only occurs in the given function sometimes, you might be able to figure out the problem by tracing the steps taken to get to the function. For example, if there was a bit more interplay in the functions:
var s:Sprite = new Sprite(); first(); function first():void { second(); } function second():void { s = null; third(); } function third():void { addChild(s); }The
thirdfunction might be the most immediate offender, but a close examination would reveal that thesecondfunction was the one that actually madesanullvalue.Run-time Errors: The Flash Debug Player
An essential tool for the Flash developer is the debug version of the Flash Player. If you don’t have it installed already, you should stop what you’re doing (reading this article) and go download it right now. You will have to restart your browser, as it’s a re-installation of the Flash Player, so bookmark this page first!
Go here to download the appropriate installer:
http://www.adobe.com/support/flashplayer/downloads.html
(Chrome users: read this support note to find out how to override Chrome’s built-in Flash Player.)
Once you restart your browser, you won’t notice much different right away. But try it out on this SWF below. First you should see some text indicating your current Flash Player version, including whether it’s the debug version or not. But click on the big button, which is wired to a function that will ultimately throw an error. If you try this out without the debug player, you won’t see anything happen; the error will occur, but will fail silently. If you try it with the debug player, however, you’ll get a rather obtrusive and hard-to-miss error message:
If you’re feeling too lazy to actually install the debug player, or just want verification that you did it right, the error you see should look something like this:
The error window displayed when the debug player is installed.
Clearly, having the debug player installed is extremely useful for being alerted of errors while testing your SWFs in the browser. As you might imagine (or have already noticed), a SWF that runs just fine from the Flash IDE may find something to complain about when placed in a different environment, like your web server. Imagine that the SWF depends on an XML file to load, but if the path to that XML file is incorrectly resolved on the web server compared to your local dev environment, then a load error will occur. It would certainly be useful to know about this as soon as it happens, rather than being presented with a non-working SWF and no clues.
The downside to the debug player is that it’s rather all-or-nothing; you can’t not debug sites you aren’t developing. That is, if you’re just browsing the web, you will eventually trigger some runtime errors in other SWFs. It’s annoying, and gives you an idea of how little some developers pay attention to their testing process.
As an extra tip, you can easily tell if you have the regular or the debug version of the player by simply right-clicking on any SWF and looking for the “Show Redraw Regions” and “Debugger” options in it:
The Flash Player context menu, when invoked from a debug player
Run-time Errors: Permit Debugging
Whether or not you’re viewing run-time errors in the IDE or in the browser, an error is only informative to a point. If you have an error that occurs somewhere in a function, but that function happens to be 20 lines long, you may have a little trouble determining where the offending line of code is.
There are two techniques that have the same results, in that more information is provided in the form of the line of code in question for each function call.
The first technique is more immediate: instead of pressing Command-Return/Control-Enter to test your movie, press Command-Shift-Return/Control-Shift-Enter to debug your movie. This launches the SWF in the Flash Player Debugger, with a debugging session started. When a run-time error is triggered, you’ll bounce back to the Flash IDE (which should reconfigure itself into a debug workspace), and you’ll see a bit more information in the stack trace (note specifically the line numbers added to the output below):
Attempting to launch and connect to Player using URL /Users/dru/Library/Caches/TemporaryItems/Untitled-1.swf [SWF] Users:dru:Library:Caches:TemporaryItems:Untitled-1.swf - 2291 bytes after decompression TypeError: Error #2007: Parameter child must be non-null. at flash.display::DisplayObjectContainer/addChild() at Untitled_fla::MainTimeline/third()[Untitled_fla.MainTimeline::frame1:12] at Untitled_fla::MainTimeline/second()[Untitled_fla.MainTimeline::frame1:8] at Untitled_fla::MainTimeline/first()[Untitled_fla.MainTimeline::frame1:5] at Untitled_fla::MainTimeline/frame1()[Untitled_fla.MainTimeline::frame1:3] Cannot display source code at this location.As a bonus, if possible Flash will open up the file responsible for throwing the error, and point to the line in question. Many built-in errors actually occur inside of built-in classes, and so it’s not possible to display that code. But if you’d like to see it in action, try the following code:
function doIt():void { trace("do it"); } var functionRef:Function = doIt; functionRef("argument not expected");…and run it through Debug Movie. Line 7 should be called out.
As we’ve discussed, though, sometimes you need to be testing on a server and through a browser, and the Flash IDE’s debugging facilities are less useful in that regard. With the debug player that we installed in the last step, there is a way to get the line number information included in the run-time error window. This is as simple as enabling a publishing option.
In your Flash document, choose File > Publish Settings… and then click on the Flash tab. Towards the bottom, under the “Advanced” heading, you’ll see a checkbox option for Permit Debugging. Make sure this is enabled, then click “OK.”
The Permit Debugging option in the Flash Publish settings
Publish the SWF again, and do what you need to do to run it in your browser again. When a runtime error occurs now, you’ll see the same line number information.
Runtime error in the browser, with line numbers
You won’t get the ability to jump to the source code, but this line number trick can save you a bunch of time in tracking down errors.
However, be careful to turn of Permit Debugging when you are ready to deploy the SWF to the world. Flash needs to add extra information to the SWF in order to provide the line numbers, and the resulting file size of the SWF is typically 25 – 50% higher than it normally is. It’s a useful debugging tool, but not something you should just turn on for everything everywhere.
Run-Time Errors: Throw Your Own
I mentioned before that it’s possible to throw your own errors (and your own tantrums, but I’ll only describe how to do the former). This can be a helpful technique in debugging. If, for example, you have the following function:
function parseXML(xml:XML):void { // xml parsing ensues... }And this function is integral to the functionality of the rest of your movie (presumably we can’t proceed with the XML-driven piece if the XML isn’t parsed), then you might be in for an unpleasant turn of events if the XML object that gets passed into the function a
nullobject, or perhaps doesn’t conform to the structure you expect.You might therefore consider, in this important function, setting up some checks and, if the checks fail, throw some errors. It can be as simple as this:
function parseXML(xml:XML):void { if (xml == null) { throw new Error("The XML object passed in to parseXML cannot be null.") } // xml parsing ensues... }Strictly speaking, you would probably want to use the
ArgumentErrorinstead of the plain oldError, but the result is essentially the same. If you run this code:You’ll see a helpful error:
The runtime error
Additionally, you might anticipate that the XML might not be
null, but might be edited in a way that does not match the expectations of the parsing function. If you need a node named<entries>to be filled with child nodes named<entry>, but due to human error the XML file looked like this:<content> <entries> <item name="one" /> <item name="two" /> <item name="three" /> </entries> </content>Then the parsing would not work. You could protect against this:
function parseXML(xml:XML):void { if (xml == null) { throw new Error("The XML object passed in to parseXML cannot be null.") } // xml parsing begins... at some point: var entries:XMLList = xml.entries.entry; if (entries.length() == 0) { throw new Error("There were no entry nodes in the <entries> nodes. " + "Instead, it looked like this:\n" + xml.entries.toXMLString()); } else { // xml parsing ensues... } }And you should get this error:
Another helpful run-time error
You just might save yourself, or someone else, some time down the line when XML files are edited incorrectly.
Run-Time Errors: Get the Stack Trace Without an Error
Sometimes the stack trace is useful by itself, even if no error has occurred. For instance, every now and then I find myself with a method that is getting called more often than I think it should. If only I could see which other methods are calling it, then I could find where the extra call is coming from.
At first glance, throwing errors would seem a suitable solution. But an error tends to stop an Flash movie in its tracks. If the first error gives me a stack trace, it might prevent the second call from ever happening because the first error prevented it. In these situations, it’s nice to know a little bit more about
Errorobjects.Most useful is the
getStackTracemethod, which returns the stack trace as it would be presented were theErrorto be thrown. The nice thing, however, is that it does not need to actually be thrown to get this information. So, if you’re simply curious to see the stack trace without throwing errors, you can do something like this:function whoCalledme():void { var e:Error = new Error(); var stack:String = e.getStackTrace(); trace(stack); }If you view this in the Flash IDE, the differences between this and a thrown error will be hard to spot; they will both simply output a bunch of information to the Output panel. You might consider embellishing the trace to make it easier to tell the difference. If you’re testing in the browser, though, this code will not present the error window, but simply write to the flash log for your perusal (I’m getting ahead of myself, tracing from the browser is covered in a few steps).
Trace the Heck Out of Everything
Speaking of traces, when it comes to debugging, tracing is the best tool you have available. Sure, Flash Professional and Flash Builder both have debuggers, which let you set breakpoints, step through code, and inspect variables, but quite honestly, I find the quickest route between bug and gathering enough information to fix it is a handful of judiciously placed traces. Traces are useful for debugging both run-time and logical errors, but because we have tools available to get information about run-time errors, traces can be the first line of defense against logical errors.
If I’m debugging a logical error, I usually know about where to focus. The thing that isn’t working is usually localized to a class or two, and usually to a handful of methods and properties. So, within the potential problem areas, I trace the heck out of everything.
More practically speaking, I tend to do the following:
As a stylistic rule, I find it immensely useful to make sure the trace is labeled, too. That is, something like this:
trace("mySprite: " + mySprite);This way, after you’ve added a dozen traces to your code, you can identify the one that says
nullamong all of the other traces more easily.Additionally, you might even want to prepend the class (and method) name in your traces, just to help further identify the source of each trace.
There are no hard and fast rules for tracing, only my general recommendation to trace everything, even things you think you don’t need to, just to be sure. At this point, a question back to the readers is appropriate: what trace techniques do you rely on? Feel free to start a flame war in the comments.
[Editor's note: Please do not start a flame war in the comments.]
Tracing: Trace from the Browser
Another advantage of the debug player (to the Flash Developer, of course) is the ability to see your traces from the browser, so you can more effectively test and debug a SWF in its natural habitat.
Unfortunately, steps need to be taken to enable this tracing, and I won’t repeat what has been written elsewhere. A search on “flash debug trace” will yield many how-to articles, of which my favorite one is currently at the top of the list on Google, a detailed article on yourpalmark.com that covers various versions of the player on Mac, Windows, and Linux systems.
I will add a tip for Macintosh users. The Console application is mentioned in passing in the linked article, but not really explained or, in my opinion, made use of properly. Console is installed with Mac OS X, and resides in your /Applications/Utilities folder. It’s ideal for displaying log files, which your debug player traces actually are. It’s smart about scrolling to the bottom if you’re already at the bottom, but not scrolling if you’re not. It’s easy to filter and search the log, and I find it indispensable for Flash development.
The Mac’s Console application in use for Flash traces
The trick, however, is that while Console can open any text file, it only remembers files if they are in the standard log file locations on your system, and if they are
.logfiles. However, the Flash debug player only write traces to a file calledflashlog.txt, which is in a non-standard log file location. There is a simple terminal command you can issue to create a symbolic link in the right place:I wrote more about this trick on my company’s Flash blog here: http://summitprojectsflashblog.wordpress.com/2008/12/17/leopards-console-and-flash-debug-player-traces/
The Flash Debugger
As mentioned earlier, Flash Professional and Flash Builder both provide debugger environments. Personally, I find these of limited usefulness, as I prefer to rely on traces and run-time errors. Also, using the debugger effectively relies on being able to set breakpoints, which can only be (easily) done in code that is open in Flash Professional or Flash Builder. As a matter of personal preference I use TextMate as my editor of choice, which makes setting breakpoints cumbersome. I would be remiss, however, if I did not mention the Flash Debugger in an article about Flash debugging.
Here is a quick tour of the debugging tools you get with Flash Professional. Let’s return to our run-time error producing example from earlier. Paste this code into the script panel of a Flash file:
var s:Sprite = new Sprite(); first(); function first():void { second(); } function second():void { s = null; third(); } function third():void { addChild(s); }Before hitting Debug Movie, though, click to the left of the number “5” in the Script panel.
The breakpoints column
A red dot will show up in the column, indicating a breakpoint has been set. To remove a breakpoint, simply click it again. With the breakpoint set on line 5 (where
secondis called inside offirst), go ahead and Debug the Movie. Now, we’re expecting the debug workspace to take over because of the error, but if you notice what’s happening, the error hasn’t actually happened (yet). There is a yellow arrow pointing at line 5, indicating that the program execution is paused at our breakpoint. At this point, we have the ability to step through the code one line at a time, and in the process inspect the value of variables, helping us find our bug.We’ve hit the breaking point
Move your attention to the Variables panel, in the lower right corner.
The Variables panel
Twiddle open the
thisentry, and you’ll see a nested list of all properties belonging to “this”, which is the main timeline of our SWF. Scroll down and you’ll see “s”, ourSpritevariable. You might need to make the panel wider, but the second column should have a value in it, likeflash.display.Sprite, indicating that it contains a value.The Variables panel, with the s variable exposed
Note that this panel can be used to inspect the value currently in any properties at the time of the pausing of the movie. Also note that while the movie is paused you can double click some of the value fields and type in new values. This will only work on primitive values like
Strings andNumbers, but it’s a handy technique to know.Now, move your eyes up to the Debug Console panel. This is where we can control the pausing and execution of our code. At the top of the panel are a series of buttons. Look for this one:
The Step In button
Click it once, and you’ll notice that the yellow arrow advanced from line 5 to line 7. This indicates what has happened; we’ve fully executed line 5, which involves a call to the function declared on line 7. The next step in our program is to call that function. Check our
svariable in the Variables panel. It should still have aSpritevalue.Click the Step In button again. The yellow arrow should point to line 8, where we set
stonull. However, if you inspect the Variables panel again, you’llsstill has a value. This is because we’re paused at line 8, but before line 8 actually runs.Click the Step In button once more, and with the yellow arrow now past line 8, inspect the
sproperty in the Variables panel. Is should now benull. If this example weren’t so simple, we might now have a revelation that the code we just executed is responsible fornull-ing our property, which in turn causes our error.At this point, we’ve satisfied ourselves that this is the cause of the error, so there is no need to keep stepping through code. We can press the green Continue button, which will resume normal execution, and you should then see the error occur.
Wrapping Up
As they said in the 80’s: now you know, and knowing is half the battle. Now you should know some debugging techniques and perhaps learned why some errors show up in different places.
Unfortunately, knowing the facts of debugging is still only half the battle. The other half is much harder to write about in a tutorial. The other half is more about experience and intuition. After you’ve fixed hundreds of bugs, you start to get a sense of what a given error is really about. You also need to know the ins and outs of ActionScript — the rather subtle nuances — in order to make sense of an error that you otherwise would swear shouldn’t be happening.
What I hope we’ve done here is make that first half of the battle easier to get through, so that when you’re facing the real world bugs in your real world projects, you can swashbuckle your way through the second half a little more elegantly.
Finally, be on the look out for a series of debugging Quick Tips. This article provides the generic groundwork that will be referenced by these future Quick Tips. Individual Quick Tips will focus on a very specific, and typically common, type of bug that Flash will throw at you, and how to take care of it when it happens.
We’ll see you there, and thanks for reading.
[Editor's note: Kudos to Yuri Arcurs for his Infuriated Businessman photo, available on PhotoDune.]
It’s time for another quiz! This time, it’s on everybody’s favorite subject: math. The topics covered are incredibly important for game development, and even more so if you know them well enough to answer off the top of your head.
Obligatory Futurama Clip
Let’s Get Quizzy
Having trouble? Check out our You Do The Math session.
Just So You Know…
This quiz was built with the jQuizzy Quiz Engine by Siddharth, ace reviewer for Envato. jQuizzy is available for purchase over on Codecanyon
Thanks also to Orman Clark and MediaLoot for their graphical contributions to the Activetuts+ Coffee Break Quizzes.
Got Something You’d Like To Be Tested On?
If you’ve got an idea for an Activetuts+-related quiz subject, let us know in the comments!
Fans of the Activetuts+ Facebook page can access a new bonus tutorial, this month a sequel to Daniel Ramirez’s Homing Missile tutorial. Check out the preview here!
Introduction
In the previous tutorial we had a homing missile chasing after a single target. This tutorial will show you how to convert your homing missiles into heat-seeking missiles for multiple targets.
Preview the Final Effect
Note how, this time, you can move the cannon with the mouse, and shoot multiple missiles at once.
Download This Fan Bonus Now!
All you have to do is Like us…
Not On Facebook?
Don’t worry, the tutorial will be posted on Activetuts+ in a month’s time!
Good to see you here on Activetuts+. You want to be a “Mathemagician”? All you need is some simple math from your notebook! What? You’re no good at math? Don’t worry. Neither am I. So I looked back into my school days and collected some math tricks we often used for fun. In this article we shall see some of those tricks and how to use them to build interesting fun applications.
First let us have a look at the following fun application I created in Flash. Actually, I was inspired to build this app when I saw a similar app while surfing the net.
This fun application “Sixth Sense” is a good example of “How to use maths tricks in real life applications.”
Sixth Sense: Fun Flash Application
We’ll discuss this math trick used in this fun application later in this session.
Read the instructions before you click Show!
Exploring the Math Trick Behind the Scene
The trick behind this application is so easy that after knowing it you will experience “Brain quake”, of above 8 on Richter scale, for sure.
To understand this trick you just have to revise the nine times table you studied in your school days. This was the easiest table to learn, I thought.
If you concentrate on the final answer in the SWF you will find that the number will always be a multiple of 9.
For e.g. If you choose 85, the final number after doing those tricky maths steps will be 72. Aaha… 72 is multiple of 9 (i.e. 9 x 8 = 72).
Try another one. Consider number 86. So, 8 + 6 = 14. Then, 86 – 14 = 72. Haha… 72 again.
Try another one. Consider number 40. So, 4 + 0 = 4. Then, 40 – 4 = 36. And of course 36 is multiple of 9 (i.e. 9 x 4 = 36).
Now do you have some idea of how things work?. Along with the nine times table you must also consider those math steps which always give a multiple of nine.
So we will take a look at those steps. First, the sum of the digits of the selected number is done (For e.g. 105 will be 1 + 0 + 5 = 6).
Then the resulting number is subtracted from the selected number (i.e. 105 – 6 = 99).
Initially I tried it in a slightly different way (e.g. If 85, then, 8 + 5 = 13. Then, 1 + 3 = 4. Finally, 85 – 4 = 81. Thus we have multiple of 9 i.e. 81). But the previous example is more effective, as it is simpler.
And last but not least, about “Symbols”. Why symbols? There are symbols against each number. So that user can compare it with his final answer.
These symbols here are placed cleverly to create the feel of magic. Want to know how? Observe every number which is a multiple of nine and check their symbols. Surprised? They all are same and will always be same. This is the crux of the whole process. That’s why they are programmed to do so.
Very smart. First you are told to pick up a number. Then doing some tricky maths with this number you are brought to a resulting number which is multiple of nine. As you know for all these multiple of nine numbers same symbol is already set. Other symbols are mixed up into this reserved symbol to hide the trick.
The “Show” button will always show this reserved symbol. Thus the user gets shocked and starts wondering how it worked.
Congrats. Now you know how things can be made magical using the power of maths and programming.
[Editor's Note: So how many of you can explain why this works? I've figured out a proof, honest, but sadly this sidebar is too small to contain it. If you've got an explanation as well, stick a note in the comments.]
More Maths Tricks
This was one application and one math trick. How about some other math tricks and possible fun applications?
I have collected some math tricks we often used in school days. I think these tricks might be useful to build some similar fun applications.
We shall discuss these tricks, how they works and the possibilities of using them for creating fun applications in the rest of this article.
Trick 1: Number Guess
This is a very interesting trick. We used this trick so many times in my school days that I still remember it. Let’s take a look.
The key part of this trick is “your number” and “dividing” it by ,“2″. Thus regardless of the user number the answer is always with you.
So whatever the user thinks, the final result will always be the half of “your number”. For e.g. If you give 100 to add to the total, then the final answer will be 100/2 = 50.
How to use this trick to build an interesting fun application?
Take a look at the following fun application i created in Flash. It uses the above “Number Guess” trick.
Yet another excellent example of putting math tricks in the playground.
Trick 2: Guess the Missing Number
This is yet another trick using nine times table.
Tell the user to get pencil and paper (this is needed since we are going to tell him to cross out any number from final answer). And one more thing; this trick is best suited to a four digit number.
Once the remaining number is with you then guessing the missing number is simply a case of applying some tricky math steps.
Your application will sum up the digits typed by the user (as 6+1+6 = 13). Now with this number 13 all you have to do is tell your application to find out next nearest multiple of nine. In this case, 18 is the next nearest multiple of nine number after 13.
Now you are just one step away to find out missing number, the one that was crossed out. Tell your application to subtract the multiple of nine from the summed digits… so, 18 – 13 = 5 and this 5 is nothing but the crossed out number. Magic…Isn’t it?
Display this number with some nice animation creating the feel of magic.
Trick 3: Guess Birth Date
Not such a great trick, but building a fun application with this trick is still possible.
If the answer is 32089 then the birth date is March 20th, 1989. (3/20/89)
To put this in application form you may collect the final answer as an input from the user in your application. Then program to convert this answer into mm/dd/yy format
Finally display this birth date with nice animation.
You can also guess the age with this data if user’s computer date is correct.
Trick 4: Guess the Exact Number
Unfortunately, this trick requires a four-digit number. Let’s take a look.
I know what you are thinking: ‘How do I apply this trick to a fun game?’. Well let’s see..
Your application could instruct the user to provide results from Steps 6 and 7 as inputs.
With these inputs your program would give the final number. Display this number on the screen to amaze the user.
Trick 5: Guess the Age
And one more trick with the number 9 (this really is a mysterious number). Play with it and you will discover many tricks with it. (Note: this trick is best suited for those aged between 10 to 100.)
To put this in application form get the answer from the second-last step (here, 26) as the input and simply add 9 using the programming logic. Display this final answer as the user’s age.
That’s it for now.
Conclusion.
So friends, feeling inspired enough to create fun applications using the power of math? I am also eager to build some more apps.
Math tricks and fun applications. Possibilities are endless. It’s a matter of picking up a perfect math trick.
Good luck!