Dynamic 3d space | Floating Sketches Tutorial

parallax_thumbI’ve had quite a few questions about how to make depth in flash. Earlier (like, 2 years ago) I put up an experiment file to give some interactive depth to some sketchbook sketches, see Floating Sketches. I’ve finally gotten around to translating that into as3. It’s still the same basic idea, Create layers of levels, and have each one respond to the mouse a little differently. The ‘closer’ depths will move faster while the farther away depths will be slower. A simple technique called Parallax.

  1. Seperate the scene into layers
  2. Place the layers in the correct depth
  3. Make closer layers react fast and farther layers slower

Example

[kml_flashembed fversion=”8.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/01/depth.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”550″]

Get Adobe Flash player

parallax_thumb
[/kml_flashembed]

Actionscript

[cc lang=”actionscript”]
//define number of layer.
var numLayers:uint = 15;
//number of items in a layer
var numBallsPerLayer:uint = 100;
var defaultBallSize:uint = 25;

var stageWidth3d:uint = 800;
var stageHeight3d:uint = 800;

var layers:Array = new Array();
//init
makeMatrix();
//3d created by layers and placing objects on each layer – the layer has it’s own distance, simulated by movement and alpha

function makeMatrix():void {
//walk through desired number of layers
for (var layerNum:uint=0; layerNumSource

depth.fla

How to as3 resize a movieClip and constrain proportions | Actionscript Tutorial

constrain proportions jpgI’ve had that exact task numerous time while scripting actionscript. I have a source image loaded externally or a mc within the program and I need to fit it into a certain area (width x height) but keep the aspect ratio the same or as photoshop calls it “constrain proportions”. I’ve done this with fancy and not so fancy formulas and equations, but finally I had it and created a simple function that would do it every time. Figured it was worth sharing cause if I’ve googled it before then others most likely will too!

This is more than just setting the width and height of an object, because that way the image is easily skewed and the natural proportions are messed up. If you want to just use scale you need to know the dimensions of the image being resized, and that’s just not scalable (no pun intended).

What we have to do is to do both. Assign the width and height to skew it, and then scale it to correct the proportion. So if we want to resize an image when we don’t know it’s current size to fit into a 300 pixel square we set the width and height of that image to 300 and then a bit of logic that can be summed up in one line:
mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;
That says if the x scale is larger than the y scale set the x to the y scale amount, and vice versa. It's basically setting both scales to the smaller of the two. This works because we don't know the original size of the image, but actionscript does. scaleX and scaleY are ratios of the current width and height to the originals. A little complicated I know, but that's why I've made the function below. I know how to use it and now I don't have to think about skewing and then scaling back to keep my aspect ratio or proportion. You should see how to use it just by looking at it:
resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true)
Pass in the movieClip you want to resize, and the size you want it to fit into. So with the same example above, just do
resizeMe(image, 300);

Example

Here's an interactive example to show what I mean. It loads an external image and you click and drag the mouse around to resize it. To toggle whether you want to constrain proportions use the space bar. Type a url to any image you want to test it with and press load, or hit 'enter'.
[kml_flashembed fversion="9.0.0" movie="https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/01/constrainproportions.swf" publishmethod="dynamic" width="550" height="550"]

Get Adobe Flash player

[/kml_flashembed]

Here's a screenshot of me playing with a photo in here NOT constraining proportions.
constrain proportions jpg

Source (AS3)

The resizing function
[cc lang="actionscript"]
//The resizing function
// parameters
// required: mc = the movieClip to resize
// required: maxW = either the size of the box to resize to, or just the maximum desired width
// optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once)
// optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true.
function resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true):void{
maxH = maxH == 0 ? maxW : maxH;
mc.width = maxW;
mc.height = maxH;
if (constrainProportions) {
mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY; } } [/cc]The full source [cc lang="actionscript"] var defaultUrl:String = "https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/11/circlecubelogo4.png"; var image:MovieClip = new MovieClip(); loadImage(); function loadImage(url:String=""):void { if (url == "" || url == defaultToLoadString) url = defaultUrl; //clear image image.visible = false; image = new MovieClip(); //add image var ldr:Loader = new Loader(); var urlReq:URLRequest = new URLRequest(url); trace("loading image: " + url); ldr.load(urlReq); ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, imageCompleteHandler); image.addChild(ldr); addChild(image); }function imageCompleteHandler(e:Event):void { resizeMe(image, stage.stageWidth) }//The resizing function // parameters // required: mc = the movieClip to resize // required: maxW = either the size of the box to resize to, or just the maximum desired width // optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once) // optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true. function resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true):void{ maxH = maxH == 0 ? maxW : maxH; mc.width = maxW; mc.height = maxH; if (constrainProportions) { mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY; } }var constrainOn:Boolean = true; var isPressed:Boolean = false;stage.addEventListener(MouseEvent.MOUSE_MOVE, moved); stage.addEventListener(MouseEvent.MOUSE_DOWN, pressed); stage.addEventListener(MouseEvent.MOUSE_UP, released); stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);function keyDownListener(e:KeyboardEvent) { if (e.keyCode == 32){//spacebar toggled(e); } if(e.keyCode == 13){//enter loadImagePress(e); } }function moved(e:Event):void{ if (isPressed) resizeMe(image, mouseX, mouseY, constrainOn); } function pressed(e:MouseEvent):void{ isPressed = true; moved(e); } function released(e:MouseEvent):void{ isPressed = false; } function toggled(e:Event):void{ constrainOn = !constrainOn; moved(e); } var defaultToLoadString:String = "type url of image to load"; toLoad.text = defaultToLoadString; toLoad.addEventListener(FocusEvent.FOCUS_IN, toLoadFocus); toLoad.addEventListener(FocusEvent.FOCUS_OUT, toLoadBlur); function toLoadFocus(e:FocusEvent):void{ if (toLoad.text == defaultToLoadString) toLoad.text = ""; } function toLoadBlur(e:FocusEvent):void{ if (toLoad.text == "") toLoad.text = defaultToLoadString; } loadBtn.addEventListener(MouseEvent.CLICK, loadImagePress); function loadImagePress(e:Event):void{ loadImage(toLoad.text); } [/cc]

Download

constrainProportions.fla

And as usual, let me know if you've got any comments questions or suggestions! Thanks,

asfunction (TextEvent.LINK) Tutorial for AS3 | Flash HTML Link to call actionscript function | Tutorial

Overview

Earlier I wrote a tutorial article about asfunction in as2. Now that I’ m into as3, surprise surprise asfunction has been depreciated and now to replace it is the LINK TextEvent. Dispatched when a user clicks a hyperlink in an HTML-enabled text field, where the URL begins with “event:”. The remainder of the URL after “event:” will be placed in the text property of the LINK event.
This differs from the asfunction method in that we must add an event listener (addEventListener) to the textField object, the event listener specifies which function will be called in the event of a link click and there is no way to send arguments along with the event (AFAIK). But it’s easy enought to use one link event function for all your link events and put in a simple switch statement to coordinate the desired results…

Steps

  1. Use event in the href attribute. (href=”event:eventText”)
  2. Listen to the textField (theTextField.addEventListener(TextEvent.LINK, linkHandler);)
  3. Handle the link event (function linkHandler(linkEvent:TextEvent):void {…)

Example

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/12/textlinkevent_as3.swf” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

Actionscript

[cc lang=”actionscript”]
var myHTMLText:String = “Sample text in an html enabled text box.\n”+
“Here’s a normal link to circlecube putting the link into the href attribute like normal!\n”+
Click this circlecube, to see the text event link in action! \n”+
“And some more links that don’t go anywhere, but they do call functions in actionscript. “+
“Click this to move UP, click me move back “+
DOWN.\n”+
“Also, one last example click for a trace test“;

//create and initialize css
var myCSS:StyleSheet = new StyleSheet();
myCSS.setStyle(“a:link”, {color:’#0000CC’,textDecoration:’none’});
myCSS.setStyle(“a:hover”, {color:’#0000FF’,textDecoration:’underline’});
myHTML.styleSheet = myCSS;
myHTML.htmlText = myHTMLText;

myHTML.addEventListener(TextEvent.LINK, linkHandler);

function linkHandler(linkEvent:TextEvent):void {
switch (linkEvent.text) {
case “clickLink”:
clickLink();
break;
case “moveUp”:
moveUp();
break;
case “moveDown”:
moveDown();
break;
default:
giveFeedback(linkEvent.text);
}
}
//function to be called from html text
function clickLink():void {
giveFeedback(“Hyperlink clicked!”);
var myURL:String = “https://circlecube.com/circlecube”;
var myRequest:URLRequest = new URLRequest(myURL);
try {
navigateToURL(myRequest);
}
catch (e:Error) {
// handle error here
giveFeedback(e);
}
}

//another function to be called from html text, recieves one argument
function moveUp():void {
feedback.y -= 10;
giveFeedback(“Up”);
}

//a simple trick to allow passing of multiple arguments
function moveDown():void {
feedback.y += 10;
giveFeedback(“Down”);
}

function giveFeedback(str):void {
trace(str);
feedback.appendText(str +”\n”);
feedback.scrollV = feedback.maxScrollV;
}
[/cc]

Source

Download the fla here: textlinkevent_as3.fla

Learning ActionScript 3.0: A Beginner's Guide | Book Review

Rich Shupe and Zevan Rosser’s Learning ActionScript 3.0: A Beginner’s Guide.

This book is published by O’Reilly and is part of the Adobe Developer Library.

This book was a great way for me to move into as3. I’m coming from a visual design background with little formal programming training, to know more of my background check my about page. Being mostly self taught, I found myself learning about basic programming skills with this book. This book helped me catch up to the as3 world and I began doing some really cool things in flash once I had a base for understanding all the differences and new things in as3.

I really enjoyed the visual aspects of this book as well. Many of the diagrams and illustrations have the hand drawn look. Like so:




I would recommend this book to anyone who wants to better understand actionscript and actionscrip3 more specifically. It’s a great helper at migrating from as2 to as3. On the cover, it claims to teach “everything needed for non-traditional programmers–web designers, GUI-based Flash developers, those new to Actionscript, visual learners–to understand how Actionscript works and how to use it in everyday projects.” I would agree with that whole-heartedly. All I can say is that after reading it and working through some of the samples included, I better understand AS3 and am confident that through the foundation it has helped me lay I will soon become an actionscript ninja.

Thanks Ryan and Zevan!

Detect Flash Player Version | Actionscript based detection method (as3)

See my previous post about how to do this with as2: Detect Flash Player Version | Actionscript based detection method (as2)

Overview

Recently I had a requirement that I had to detect which version of the flash player was currently installed. This is a normal thing, we do it all the time when embedding flash into html, we detect which version of the player is installed and if the user has an old version they are invited to upgrade…

But what about finding the flash version from within flash? An actionscript based detection method? I hadn’t ever thought about doing that…

Actionscript 3 now uses the flash system capabilities class to report all it’s “capabilities”. First we have to import it and then we have access to all the details through the Capabilities object, such as operating system, language, pixel aspect ration and flash player version. There are a ton of others and I’ve included them in the trace statements.

Steps

  1. import the class import flash.system.Capabilities;
  2. read the version from the Capabilities object var flashPlayerVersion:String = Capabilities.version;

This returns a string, 3 letter operating system, a space, and then the version number as four numbers seperated with commas. (just like eval(‘$version’); in as2)
I display the flashPlayerVersion and to split it out I split the string on the space, and then split the version number with the comma delimiter and display them all.

Example

Here’s what mine is (gif):

flash player version detection as3

And here’s what yours is (swf):
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/11/flashversiondetectionactionscriptmethodas3.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”160″ height=”160″]

Get Adobe Flash player

[/kml_flashembed]

Actionscript (as3)

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
import flash.system.Capabilities;

var flashPlayerVersion:String = Capabilities.version;

var osArray:Array = flashPlayerVersion.split(‘ ‘);
var osType:String = osArray[0]; //The operating system: WIN, MAC, LNX
var versionArray:Array = osArray[1].split(‘,’);//The player versions. 9,0,115,0
var majorVersion:Number = parseInt(versionArray[0]);
var majorRevision:Number = parseInt(versionArray[1]);
var minorVersion:Number = parseInt(versionArray[2]);
var minorRevision:Number = parseInt(versionArray[3]);

vers.text = flashPlayerVersion;
feedback.text = “Operating System: “+osType + “\n” +
“Major Version: “+majorVersion + “\n” +
“Major Revision: “+majorRevision + “\n” +
“Minor Version: “+minorVersion + “\n” +
“Minor Revision: “+minorRevision;

trace(“Operating System: “+osType);
trace(“Major Version: “+majorVersion);
trace(“Major Revision: “+majorRevision);
trace(“Minor Version: “+minorVersion);
trace(“Minor Revision: “+minorRevision);
trace(“–other capabilities–“);
trace(“avHardwareDisable: ” + Capabilities.avHardwareDisable);
trace(“hasAccessibility: ” + Capabilities.hasAccessibility);
trace(“hasAudio: ” + Capabilities.hasAudio);
trace(“hasAudioEncoder: ” + Capabilities.hasAudioEncoder);
trace(“hasEmbeddedVideo: ” + Capabilities.hasEmbeddedVideo);
trace(“hasMP3: ” + Capabilities.hasMP3);
trace(“hasPrinting: ” + Capabilities.hasPrinting);
trace(“hasScreenBroadcast: ” + Capabilities.hasScreenBroadcast);
trace(“hasScreenPlayback: ” + Capabilities.hasScreenPlayback);
trace(“hasStreamingAudio: ” + Capabilities.hasStreamingAudio);
trace(“hasVideoEncoder: ” + Capabilities.hasVideoEncoder);
trace(“isDebugger: ” + Capabilities.isDebugger);
trace(“language: ” + Capabilities.language);
trace(“localFileReadDisable: ” + Capabilities.localFileReadDisable);
trace(“manufacturer: ” + Capabilities.manufacturer);
trace(“os: ” + Capabilities.os);
trace(“pixelAspectRatio: ” + Capabilities.pixelAspectRatio);
trace(“playerType: ” + Capabilities.playerType);
trace(“screenColor: ” + Capabilities.screenColor);
trace(“screenDPI: ” + Capabilities.screenDPI);

trace(“screenResolutionX: ” + Capabilities.screenResolutionX);
trace(“screenResolutionY: ” + Capabilities.screenResolutionY);
trace(“serverString: ” + Capabilities.serverString);
[/cc]

Download

Here’s the source fla file: flash version detection actionscript method (as3)

Copy TextField text to System clipboard | Actionscript (AS2 + AS3) Tutorial

Overview

Integrating the clipboard of the operating system with your flash projects is sometimes essential. It’s a very simple and boils down to one basic method… System.setClipboard(). I’ve found a couple other things help the user experience though, such as selecting the text that gets copied and giving the user some sort of feedback to let them know that the text was successfully copied. Here’s a simple way to do it. Have any suggestions to make it better?

I’ve included an as2 version as well as as3. I’ve promised myself to migrate to as3, so I’m not coding anything in 2 that I don’t do in 3 also. This was to discourage me from coding in as2 and to encourage me to code as3, but also let me learn by doing it in both to see the actual differences if I was stuck doing a project in as2. I figured this could help others see the differences between the two versions of actionscript a bit easier and make their own migration as well!

Steps

  1. copy to OS clipboard = System.setClipboard(“Text to COPY”) of System.setClipboard(textBoxToCopy.text)
  2. set selection to text that is copied
  3. give user feedback

Examples and Source

AS2

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/11/clipboard_as2.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
textBox.textBox.text = “Click this text box to copy the text or click the COPY button below. You will see feedback to the user and this text copied to your clipboard!\n\n”+
‘copyButton.onRelease = textBox.onPress = function(){\n\tSelection.setFocus(“textBox”);\n\tSelection.setSelection(0, textBox.text.length);\n\tSystem.setClipboard(textBox.text);\n\ttrace(“copied: “+textBox.text);\n\tfeedback(“Text Copied!”);\n}’;

copyButton.onRelease = textBox.onPress = function(){
Selection.setFocus(“textBox.textBox”);
Selection.setSelection(0, textBox.textBox.text.length);
System.setClipboard(textBox.textBox.text);
trace(“copied: “+textBox.textBox.text);
textFeedback(“Text Copied!”);
}

function textFeedback(theFeedback:String){
feedback.text = theFeedback;
setTimeout(function(){feedback.text=””;}, 1200);
}
[/cc]

AS3

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/11/clipboard_as3.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
textBox.text = “Click this text box to copy the text or click the COPY button below. You will see feedback to the user and this text copied to your clipboard!\n\n”+
‘function copyText(e:MouseEvent):void{\n\ttextBox.setSelection(0, textBox.text.length)\n\tSystem.setClipboard(textBox.text);\n\ttrace(“copied: “+textBox.text);\n\ttextFeedback(“Text Copied!”);\n}’;

//set it so the textBox selection will show even when textBox has no focus
textBox.alwaysShowSelection = true;

textBox.addEventListener(MouseEvent.CLICK, copyText);
copyButton.addEventListener(MouseEvent.CLICK, copyText);

function copyText(e:MouseEvent):void{
textBox.setSelection(0, textBox.text.length)
System.setClipboard(textBox.text);
trace(“copied: “+textBox.text);
textFeedback(“Text Copied!”);
}

function textFeedback(theFeedback:String):void {
feedback.text = theFeedback;
setTimeout(function(){feedback.text=””;}, 1200);
}
[/cc]

Download

Source files: clipboard_as3.fla clipboard_as2+as3.zip

Voters Aide | Prioritize the Issues this Election | Interactive Flash App

To accompany the last presidential debate, I ask a question:

Who to vote for?

It’s not just about what party you’re affiliated with, who you agree with more on an issue or which candidate you understand better… it’s a combination of them all. It’s more important how a candidate can handle the different issues facing us today than how they perform in a debate or advertisement.
There should be somewhere to assign a weight to each issue on the table and then issue by issue see which candidate I agree more with. Then it would calculate and tell me who I really support according to how I prioritize the issues. So if I think the only issue worth voting about is Iraq or the economy and I agree more with Barrack Obama or John McCain on those issues it will be reflect in the results.
It’s pretty hard to explain the whole idea, without building it myself, so that’s just what I did… while I couldn’t stop thinking about it I coded it.

Check it out, and I hope it helps! Cause we’re gonna need all the help we can get on this one! It can help you decide or just test yourself and see if you really support that candidate as much as you think.

Go try it here!

I pulled info from CNN’s election center mostly because all the info was gathered for me already, each of the big issues, descriptions and the candidates position. I have a slider for each issue where users select how imortant it is to them (on a scale of 0 to 100 percent). Then users compare their own position on the issues with each candidate (on a scale of 0 to 100 toward each candidate). This is all considered while your support is calculated. Each issue’s importance as a percentage is multiplied by the amount you agree with each candidates position. These are all added up and totaled to give a final percentage. This is innovative in that it’s not just who you agree with mpre, it’s who you agree with more on the isues that you think are more important! Let me know what you think about this and let the candidates know what you think about their positions.

Voters Aide the flash app to help you decide who you support by letting you prioritize the issues and choose which candidate you lean towards on each issue and see the overall results.

Actionscript Key Listener Tutorial AS3

Overview

Allowing users to use the keyboard as well as the mouse is a great way to incite interaction with your flash. This tutorial will show how to code it and what you can do with some keyboard events. This changed with actionscript 3, note this tutorial is AS3.
altKeY (Boolean) Indicates whether the Alt key is active (true) or inactive (false).
charCode (uint) Contains the character code value of the key pressed or released.
ctrlKey (Boolean) Indicates whether the Control key is active (true) or inactive (false).
keyCode (uint) The key code value of the key pressed or released. KeyboardEvent
keyLocation (uint) Indicates the location of the key on the keyboard. KeyboardEvent
shiftKey (Boolean) Indicates whether the Shift key modifier is active (true) or inactive (false).

Steps

  1. import KeyboardEvent,
    import flash.events.KeyboardEvent;
  2. assign any keycodes
    //keycodes
    var left:uint = 37;
    var up:uint = 38;
    var right:uint = 39;
    var down:uint = 40;
  3. add event listener KeyboardEvent.KEY_DOWN
    stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);
  4. respond to keys
    function keyDownListener(e:KeyboardEvent) {
            trace(e.keyCode.toString());
    }

    or

    function keyDownListener(e:KeyboardEvent) {
            if (e.keyCode==left){
    		ship.x-=10;
    		ship.rotation = 90;
    	}
    	if (e.keyCode==up){
    		ship.y-=10;
    		ship.rotation = 180;
    	}
    	if (e.keyCode==right){
    		ship.x+=10;
    		ship.rotation = 270;
    	}
    	if (e.keyCode==down){
    		ship.y+=10;
    		ship.rotation = 0;
    	}
    }

Example

Here we have a swf with the keyboard event listener on the stage, and feedback boxes to give us all we can know about the event. It will tell us about certain keys (alt, ctrl (cmd), and shift) with a Boolean, it will tell us the keyCode and the charCode. The keyCode is the number that is tied to the actual button pressed or key, and the charCode relates to the character represented by the button(s) pressed. So hitting ‘s’ and then hitting ‘shift + s’ will tell you different charCodes, ‘s’ and ‘S’. but you’ll see that the s key has the same keyCode (you’ll also see the ‘shift’ keyCode as well). If needed you can use the String.fromCharCode function to determine what the charCode for something is. The location on the keyboard is even reported, this helps distinguish between the left shift and the right shift and even the numbers across the qwerty and the numpad on the right of the screen.
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/07/key-listener.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”500″ height=”500″]

Get Adobe Flash player

[/kml_flashembed]

Actionscript

[cc lang=”actionscript” tab_size=”2″ lines=”40″]

import flash.events.KeyboardEvent;

//keycodes
var left:uint = 37;
var up:uint = 38;
var right:uint = 39;
var down:uint = 40;

stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);

function keyDownListener(e:KeyboardEvent) {

feedbackAlt.text = e.altKey.toString();
feedbackCharCode.text = e.charCode.toString();
feedbackChar.text = String.fromCharCode(feedbackCharCode.text);
feedbackCtrl.text = e.ctrlKey.toString();
feedbackKey.text = e.keyCode.toString();
feedbackLoc.text = e.keyLocation.toString();
feedbackShift.text = e.shiftKey.toString();

if (e.keyCode == left){
ship.x-=10;
ship.rotation = 90;
}
if (e.keyCode == up){
ship.y-=10;
ship.rotation = 180;
}
if (e.keyCode == right){
ship.x+=10;
ship.rotation = 270;
}
if (e.keyCode == down){
ship.y+=10;
ship.rotation = 0;
}
}

[/cc]

Download

source file download: key-listener.fla

Google Indexes SWFs and external content | Fleximagically Searchable | Ryan Stewart's Flex SEO Contest

Ryan has announced a contest to investigate how Google is actually crawling swfs. He introduced the term “fleximagically searchable” to be included in external content, which is then loaded into the Flex swf. Hoping that google will read the external source file through the swf. Also testing how this shows up in the search results. Even though I think there a lot more to SEO than just letting Google crawl your site, there’s the pagerank and everything that Google uses in it’s top secret algorithm to determine search result position ranks.

Here’s the official rules:

  • It has to be a Flex application
  • ‘Fleximagically Searchable’ must be dynamically loaded. It can’t be static text inside of your application. – But I don’t care how you load it, in fact that might make a difference in how Google ranks you.
  • The first link must be deep linked directly into where you load ‘Fleximagically Searchable’ into your application. Feel free to use any deep linking methods out there.
  • Nothing in your code can dynamically load the phrase automatically. It has to be the result of a user interaction.
  • You must provide source code and be willing to talk about exactly what you did.
  • Multiple entries are allowed if you want to try different things.

They seem to be a bit vague in places, but we’ll see if Ryan decides to clarify anything.

More information: I’ve found that’s helpful at Peter Elst’s post. And Ryan explains Google and Flash’s relationship development here. Here and here is what Google has officially said. Here is the official press release from Adobe about their new

I’ll have a couple entries I’m sure… and I’ll be sure to post about those as well.

Actionscript to Reference Dynamically created instances Flash Movie Clip | Array notation | Tutorial

Overview:

Often I’ve had some dynamically created movieclip and then wanted to reference it in my code. This is hard to do if it is named dynamically as well, such as with an incrementing variable. If you use one (or more) variable to name an instance in run time, you can’t always know what it will be called.
There are two ways (that I know of) to reference these clips, one is the array operator [] and the other is using the eval() function is as2 (but I’ve noticed that as3 has removed the eval function, so I’d recommend getting used to array notation).

Steps:

  1. Create the object dynamically (or with a variable) (_root.myClip.duplicateMovieClip (“myClip”+i, i);)
  2. Reference it with either array notation or with eval. (thisOne = _root[“myClip”+i];) or (eval(“myClip” + i))

Example:

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/07/reference-dynamically-named-clips.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”500″ height=”500″]

Get Adobe Flash player

[/kml_flashembed]

I create some movie clips dynamically using a for loop and name them all incrementally with a variable (myClip+i). But then i want to refer to some of them later, specifically. I don’t know what they are named though. They are all myClip1 myClip2 myClip3 and so on. I can use array notation to reference these (or eval). I’ve found it’s easiest to create a reference to the name once and then use it to refer to the clip I want. I imagined a scenario that when you click a mc you would want a different one to be moved. So clicking myClip3 moves myClip4 and so on. I’ve made it wrap so that 5 moves 1… They change the _y property of the next to match the one that’s clicked. Clicking the refresh button will loop through all the clips and (this time using eval) randomize the y coordinate.

Actionscript:

[cc lang=”actionscript” tab_size=”2″ lines=”40″]

var myLimit = 5;
//myClip._visible = false;

for(var i=1; i<=myLimit; i++) {
_root.myClip.duplicateMovieClip (“myClip”+i, i);

thisOne = _root[“myClip”+i];
thisOne._y = Math.random() * Stage.height;
thisOne._x = Stage.width/(myLimit+1) * i ;
thisOne.id = i;
thisOne.idDisplay.text = i;

thisOne.onRelease = function() {
nextOne = (this.id == myLimit) ? _root[“myClip”+1]: _root[“myClip”+(this.id+1)];
nextOne._y = this._y;
}
}

myClip.onRelease = function() {
for (var i=1; i<=myLimit; i++) {
eval(“myClip” + i)._y = Math.random() * Stage.height;
}
}

[/cc]

Download:

Source fla file: download

Reference:

Nuno Mira shows a good example:

[cc lang=”actionscript”]
this.createEmptyMovieClip(“outer_mc”, 1); // create a mc called outer_mc
outer_mc.createEmptyMovieClip(“inner_mc”, 1); // create a mc called inner_mc inside outer_mc
// 3 different ways of targeting inner_mc
trace(outer_mc.inner_mc);
trace(outer_mc[“inner_mc”]);
trace(this[“outer_mc”][“inner_mc”]);
// all output _level0.outer_mc.inner_mc
[/cc]

TheCanadian@Kirupa states it nicely:
The Problem
How can I reference objects using a variable? This is commonly a problem with dynamically created buttons:

ActionScript Code:
for(i = 0; i < 3; i++) { button+i.someProp = "Hello World!"; //error }

The Answer
This is probably the question that gets asked the most. Referencing an object with a variable is done using something called associative array referencing or array notation. The fundamental concept behind this is that:

ActionScript Code:
myObject.prop = "value"; //and myObject["prop"] = "value";

Are the same thing. Associative array referencing follows the pattern of scope[“prop”] where scope is the object which contains the property and prop is the name of the property you wish to reference. Save appearance, array notation works in exactly the same way as dot notation.

Going back to the original, problematic, example, the correct code would look like this:

ActionScript Code:
for(i = 0; i < 3; i++) { this["button"+i].someProp = "Hello World!"; }

The button string is concatenated (joined) with the i variable, forming a new reference with each iteration of the loop. First button0, then button1, et cetera.

That’s the quick, but some of you may think that that’s the same notation that is used with instances of the Array class. While that is true, the converse is actually more correct: Array instances use that notation.

Arrays are exactly the same as generic Objects, the only difference is that they have a collection of methods to deal with their properties. And because they require a need for organization, they typically only use numerical properties. Given the array myArray = [“a”, “b”, “c”], you could theoretically reference the indices using myArray.0, myArray.1 and myArray.2. The reason that we must use array notation is because the compiler doesn’t allow the reference of numerical properties with dot notation.