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

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

Preloader Stats File @ FlashDen

A preloader bar that gives full stats, speed, kb, and even remaining download time!

[kml_flashembed fversion=”9.0.0″ movie=”http://activeden.net/files/58667/preview.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”280″]

Get Adobe Flash player

[/kml_flashembed]

Preloader with Stats

Clean slick preloader. Rounded bar with gradient fill and bevel and glow filter. All actionscript driven, no animations to bloat file size. Rounded corners don’t distort as width changes.

Includes loading statistics for download.

Calculates the following:

  • Percent Loaded
  • Loaded kilobytes
  • Total kilobytes
  • Average kilobytes per second download speed
  • Remaining dowload time in seconds
  • Gives kilobytes to 2 decimal places without dropping zero’s

To Use:

Easy to use, just paste in frame 1 of your file. (actionscript code included!)

Customize:

Customize color easily. Edit the fill color of the preloader_bar movie clip in the library.

Customize font easily. Edit the font for the text box named feedback on the text layer of the preloader mc.

Circlecube Flash Items at activeden

21075 24687 45713 45893 22018

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

ColorTransform | RGB, Hex and random colors | Actionscript Color Tutorial

Overview

Color can sometimes make or break your design. I’ve put together this flash to show how to set a movieclip to a certain color, I’ve had to do this at runtime and had to go by different values such as a hex number, rgb values and have even wanted to just set a random color, so this example does them all! It’s even nice for translating a Hexadecimal color into RGB color.

Flash uses a Transform object to control certain properties of movie clips. To set color we need to use a Transform object as well as a ColorTransform object. ColorTransform objets are used to, you guessed it, tell the Transform object what color we want to set our clip to. It was a little unintuitive for me to learn, but now it makes sense, or at least enough sense to use.

I’ve made a function that does all this for you. You just send it the movieClip reference and a color. setColor(myMovieClip, myColor)

There are functions to convert rgb values to a hex value, and from a hex value to red, blue and green values as well.

To make a random hexadecimal number Math.random() * 16777216 (the total number of hexadecimal numbers)

Steps

  1. Imports
    import flash.geom.ColorTransform;
    import flash.geom.Transform;
  2. Make a Transform object
    var myTransform:Transform = new Transform(item);
  3. Make a ColorTransform object
    var myColorTransform:ColorTransform = new ColorTransform();
  4. Set the rgb color of the ColorTransfrorm object
    myColorTransform.rgb = myColor;
  5. Set the colorTransform property of the Transform object to your ColorTransform object
    myTransform.colorTransform = myColorTransform;

Flash Color App

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

Get Adobe Flash player

[/kml_flashembed]

Source Actionscript (as2)

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
//method to set a specified movieClip(item:movidClip) to a specified color(col:hex value number)
function setColor(item, col) {
//make transform object and send the specified movieClip to it
var myTransform:Transform = new Transform(item);
//make colorTransform
var myColorTransform:ColorTransform = new ColorTransform();
//check color bounds
if (col > 16777215) col = 16777215;
else if (col < 0) col = 0; //variable to hold the color value var myColor:Number = col; //set color through color transformation myColorTransform.rgb = myColor; myTransform.colorTransform = myColorTransform;trace("the hex number: 0x" + addZeros(myColorTransform.rgb.toString(16))); var rgbObject = hex2rgb(myColor); trace("the hex number in rgb format: "+rgbObject.r+", "+rgbObject.g+", "+rgbObject.b); trace("the hex number in decimal format: " + myColorTransform.rgb); displayColors(myColorTransform.rgb); }//bitwise conversion of rgb color to a hex value function rgb2hex(r, g, b):Number { return(r<<16 | g<<8 | b); } //bitwise conversion of a hex color into rgb values function hex2rgb (hex):Object{ var red = hex>>16;
var greenBlue = hex-(red<<16) var green = greenBlue>>8;
var blue = greenBlue – (green << 8); //trace("r: " + red + " g: " + green + " b: " + blue); return({r:red, g:green, b:blue}); }//BUTTONS randomColor.onRelease = function() { //make random number (within hex number range) var theColor = Math.floor(Math.random() * 16777215); //set ball color to random color value setColor(colorBall.inner, theColor); } readHexColor.onRelease = function() { //convert 6 character input string into hex color format used by actionscript var theColor = "0x"+hexColorIn.text; //set ball color to hex color value setColor(colorBall.inner, theColor); } readRGBColor.onRelease = function() { //convert rgb values into hex value var theColor = rgb2hex(redColorIn.text, greenColorIn.text, blueColorIn.text); //set ball color to converted hex color value setColor(colorBall.inner, theColor); } readDecColor.onRelease = function() { //convert rgb values into hex value var theColor = decColorIn.text; //set ball color to converted hex color value setColor(colorBall.inner, theColor); } [/cc]

Open Source Download

color.zip (containing color.fla and color.swf)

Event Tracking with Google Analytics | Flash Integration | Tutorial

Many have read my Integrate Google Analytics with Flash Tutorial in which I express enthusiasm for the new event tracking at google analytics! Well, it’s been a while, but I was admitted to the Beta testing group! So I’ve now had the chance to play with event tracking a bit and wanted to publish my findings!

Overview

Almost a year ago Google Analytics announced their new event tracking model and have had help documents published and code samples up. And as with many of Google’s products the beta stamp has lasted a very very long time. Many have seen my earlier tutorial exploring using traditional Google Analytics Tracking from within Flash, and it does wonders to track your flash apps in this manner, but there is a problem with it. We’re using supposed object oriented concepts to track objects as pageviews. One thing is it really isn’t a very intuitive way to represent that data, and another it inflates your pageviews! The solution? the long awaited and announced Event Tracking model. I’ve been itching for this to be released so I could refresh my analytic tactics I use in my flash projects. No, to answer your questions, it has not been released yet, but I contacted Google and explained that I would be a great beta tester for this feature and after a bit of correspondence they invited me to join in the beta testing! This is good news for you too! Because I will tell you all about how to do it and even show you what the reporting looks like and when it is released finally, you will know what you’re in for after this sneak peak!

UPDATE: Here are the reports for this very example: Report from Event Tracking with Flash Tutorial

The very quick summary is this:
_trackEvent(category, action, optional_label, optional_value)
Note that the _trackEvent function is called on the pageTracker object itself. (initially Google had you instantiate a separate event tracker for every object (or category) you wanted tracked)

For example, if we want to track a ball. All the actions that can apply to the ball are: it being created, dragged, dropped, bounced, deleted… You get the idea. We can have direct user actions tracked or even automatic actions. If we have gravity and physics running, the ball may bounce a lot without any direct user interaction. But it will never be dragged or dropped without direct interaction. I’d recommend only tracking user interactions because who cares how often a ball bounces on your page (unless you’re doing an experiment, of course), want we want to know is how and when a user interacts with the ball.

category:string (required)

This is the name of the object you are tracking.

action:string (required)

This is the action that happens to your object you want to track.

optional_label:string (optional)

This can be more information to accompany the action.

optional_value:integer (optional)

A number to provide numerical information to accompany the action.

Steps

  1. First, I’d recommend reading up about Event Tracking at Google
  2. Decide your object oriented structure for tracking events. What objects do you want to track and what useful information do you want to get through tracking user interaction?
  3. Make sure you have the new Google analytics tracking code on your page
  4. Use these functions to communicate Google Analytics from your flash
    1. Call the main function with the specified parameters
    2. It will call the appropriate function and send the data to your pageTracker object through javascript with externalInterface calls
  5. See the reports in your analytics profile! (if your a beta tester, or else, wait until it is released)

Source code

The tracking functions are below, I enhanced the earlier trackGA function I wrote about. Now you call trackGA with 2 required parameters, categoryOrPageTrack and action. categoryOrPageTrack is where you have to pay attention. I wanted to keep the ability to track pageviews as well as have event tracking, so as the first param you either send in the string ‘page’ to explicitly state that you want to track the page view, or you send in another string to state you want to track an event on that specified object. Action remains the same, the action you want tracked (either on the pageview, it is the path that will appear in your reports; or the event tracking will be the action tracked to the category)…
So to track a pageview I call
trackGA("page", "swfLoaded");
and to track an event to an object I call ball:
trackGA("ball", "created");
The trackGA function will rout your call to the appropriate place and send the info to Google through either the trackGAPage function or the trackGAEvent function.
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
//trackGA (categoryOrPageTrack [required], action [required], label [optional], value [optional]
//categoryOrPageTrack – either the category string or a string saying ‘page’
function trackGA(categoryOrPageTrack:String, action:String, optional_label:String, optional_value:Number) {
//call page tracking version of Google analytics
if (categoryOrPageTrack == “page”) {
//trace(“GATC pageTracker call”);
trackGAPage(action);
}
//call event tracking method
else {
//trace(“GATC event tracker call”);
trackGAEvent(categoryOrPageTrack, action, optional_label, optional_value);
}
}

var prefix:String = “flashGA”;
//Google Analytics Calls Page Tracking – for tracking page views
function trackGAPage(action:String) {
//GA call
if (prefix != null && !eventTrack){
var call = “/” + prefix + “/” + action;
//Old Google Analytics Code (urchinTracker)
ExternalInterface.call(“urchinTracker(‘”+call+”‘)”);
//New Google Analytics Code (_trackPageview) pageview
ExternalInterface.call(“pageTracker._trackPageview(‘”+call+”‘)”);
trace(“==GATC==pageTracker._trackPageview(‘”+call+”‘)”);
}
_root.tracer.text = action;
}

//Google Analytics Event Tracking Calls – for tracking events and not pageviews
//category, action, label (optional), value(optional)
function trackGAEvent(category:String, action:String, optional_label:String, optional_value:Number) {
/*
objectTracker_trackEvent(category, action, optional_label, optional_value)
category (required) – The name you supply for the group of objects you want to track.
action (required) – A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object.
label (optional) – An optional string to provide additional dimensions to the event data.
value (optional) – An optional integer that you can use to provide numerical data about the user event.
*/

theCategory = “‘” + category;
theAction = “‘, ‘” + action + “‘”;
theLabel = (optional_label == null) ? “” : “, ‘” + optional_label + “‘”;
theValue = (optional_value == null) ? “” : “, ” + optional_value;
//New Google Analytics Code (_trackEvent) event tracking
theCall = “pageTracker._trackEvent(” + theCategory + theAction + theLabel + theValue + “)”;
ExternalInterface.call(theCall);
trace(“====GATC====”+theCall);
_root.tracer.text = theCategory + theAction + theLabel + theValue;
}
[/cc]

Here’s the actionscript lines where I call the trackGA function:
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
//Tracks that the swf loads, so I pass ‘page’ to let it know I want a pageview tracked…
trackGA(“page”, “swfLoaded”);
//Tracks various objects sending various actions
trackGA(“gravity”, “on”);
trackGA(“gravity”, “off”);
trackGA(“friction”, “on”);
trackGA(“friction”, “off”);
trackGA(“ball”, “deleted”, count);
trackGA(“ball”, “created”, ballCount);
trackGA(“ball”, “drag”, this.ballNum, this.ballNum);
trackGA(“ball”, “drop”, this.ballNum, this.ballNum);
trackGA(“ball”, “bounce”, “right”, this.ballNum);
[/cc]

Example

[kml_flashembed fversion=”9.0.0″ movie=”/wp-content/uploads/2008/10/integrategoogleanalytics/integrategoogleanalytics.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”400″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

View example in it’s own html page, I even added a couple html buttons with javascript hooked in to show javascript event tracking implementation.

Download

Download Source

Concerns

I’ve noticed while putting this together that the calls to google analytics are not completely fullfilled, this example sends out correct calls to javascript, but (in firefox at least) a max of about 1 tracking call is registered with the tracking code every 5 seconds or so. I noticed this as I was monitoring the drag and drop events for each ball, although the drag and drop events are both fired, usually the drag event was received and the drop is not. After verifying that my code was consistent, I noticed that no matter how fast I interacted with the objects, the calls were much slower. I’m guessing this is a limit placed by the google team to keep us from sending pointless data such as is posted at the bottom of the event tracking implementation guide, titled Events Per Session Limit.

Rounded Bar Percentage Preloader for Flash Tutorial

I’ve had a couple inquiries about how to do a simple preloader in Flash. The technique and also the actionscript which implements the technique. So here is a percentage preloader example with source code and a source file to play with.

Overview

So the idea of a preloader is to hold the swf until the file has sufficiently loaded. Once it’s is fully loaded, then the preloader advances to swf to the actual content.

There are different types of preloaders: status preloaders and percentage preloaders. Status preloaders only tell you the status of the loading file. So it will have a simple looping animation like a spinning wheel and you just wait until it is fully loaded. Percentage preloaders will actually tell you how much has been loaded or how much is left and usually will have a bar or something that fills as the file loads or at least tell you in numbers how much has been loaded.

These techniques require the same first few steps. As you can guess, the percentage preloader takes a couple extra steps, but it is much worth the extra few minutes in my opinion. It gives the users valuable information about the program or file they are waiting on. If they are waiting and have no idea how much longer their wait will be, who knows how long they will stick around and watch an hourglass.

In actionscript the only special methods we use for a preloader are getBytesLoaded and getBytesTotal. Once we know the bytes loaded and the total bytes to load, with a little math we calculate what percentage is loaded.

Steps

  • Hold the viewers at frame 1
  • Check if file is loaded yet (percentLoaded)
  • If not loaded, update display (if applicable) and check again
  • If loaded, continue

Example

This is a preview, note that it is not actually a preloader, just what one looks like. You can see this preloader working in my Interactive Image Viewer
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/09/preloader_bar_preview.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”125″]

Get Adobe Flash player

[/kml_flashembed]

Actionscript

I’ve put this code on the preloader movieclip which sits alone on frame one with a simple stop(); actionscript command. Frame 2 contains the beginnings of the actual content. To break down the code, we first see that it is performed every frame: onClipEvent(enterFrame), so every frame we will see how much has loaded. In this case the frame rate is 20 frames per second, so we check the amount loaded every 20th of a second!
First we find the percentLoaded by dividing the total bytes to load by the number of bytes currently loaded. Then we display the percent loaded in a text box named feedback and adjust the xscale of the orange bar according to percentLoaded. Finally we’ll check to see if the percentLoaded has reached 100 yet, and if it has we play the parent clip (which in this case is the root, but it could be used to load numerous objects on the stage). When we play the parent clip, we then go to frame 2 or the actual content of the swf and this preloader is removed from the stage and the code will stop executing. But if percentLoaded is not 100% yet this frame is repeated and the code executes all over again, finding the (hopefully) new number of bytes loaded, and updating the display to inform the user. The code executes so fast that the preloader will actually animate the loading process and inform the user simultaneously.
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
onClipEvent (enterFrame) {
percentLoaded = _parent.getBytesLoaded() / _parent.getBytesTotal() * 100;

this.feedback.text = “%” + Math.ceil(percentLoaded );
this.bar._xscale = percentLoaded ;

if (percentLoaded => 100) {
_parent.play();
}
}
[/cc]

Download

activeden is hosting this preloader file: Round Preloader Bar

Circlecube Flash Items on activeden

21075 24687 45713 45893 22018

Interactive Image Viewer v1 @ FlashDen

I’ve re-purposed an old project of mine, the interactive pog portfolio viewer, to activeden. I call it the pog portfolio because each work is represented by a circle, or pog, and you play ith it in the “bay” with different interactive physics configurations. When you click a pog you can view a close up image of that item and more details. The whole file has been cleaned up (code and graphics) and documented for easy customizations.It is a small file size as well, under 36kb swf!

This is mainly an image viewer, stay tuned for any updates, like video support etc.

INTERACTIVE IMAGE VIEWER WITH PHYSICS AND ANIMATION EXAMPLE!

pog portfolio image

View Details here at activeden

Works and configuration loaded in through a single xml file. Select works from the bay to view title, description image and a link (if applicable). Organize works with the tags or select all and choose the physics of the bay for interactivity control (gravity, spring, grid and friction).

It is fully customizable and fully driven by xml. The xml file contains values for configuring the swf, and also all the information about each work to be included in the portfolio.

Each work is loaded into the ‘bay’ as a round thumbnail or ‘pog’. These pogs are animated with the interaction options (gravity, friction, spring and grid). The pogs are sortable by tags (parsed in from the xml).

The whole color scheme of the image viewer is configurable, or can even be set to random! Have a different color scheme every time your image viewer loads!

Clicking a pog in the interactive bay sends that thumb to the holding area and loads the close up into the focus window for that work. It also loads the details about that work into the detail box (to the right of the focus box). Each works needs a 50×50 thumbnail and a close up (max 375px x 270px) image. Focus images are all loaded in with an informative preloader and fade is once loaded.

Site easily integrates with Google Analytics to track user interactions within this flash portfolio!

All works in the portfolio are passed in through an external xml file, here is a sample work node from xml:
[cc lang=”xml” tab_size=”2″ lines=”40″]


Random Gear

Random gear photograph from activeden assets.

random_gear.jpg


random_gear.jpg

http://activeden.net


Photo|Industrial

[/cc]

Download source at activeden

Enjoy, and let me know what you think!

Circlecube Flash Items on activeden

21075 24687 45713 45893 22018

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