How to use fullscreen in AS3 | Stage Display State Tutorial

fullscreen_tut png
One of the best features of the flash player if you’re doing video is the fullscreen functionality. It has been a question I’ve heard repeatedly. There are limits to what you can do in fullscreen. Such as minimal keyboard support while in fullscreen. But it is perfect for a video player! Who doesn’t want to see a video expanded to full screen mode?

There are a couple things to consider when coding fullscreen into your flash. Remember the hard coded “Press Esc to exit full screen mode.” that Adobe has placed into the flash player. This is untouchable by developers, and the function returns to normal stage display state. So we call the function to go fullscreen, but the exit fullscreen has already been written for us. This can pose a problem though, when we need the player to do something when we exit fullscreen, that is when we want it to do something more than the generic black box function adobe includes.

Steps

  1. specify stage properties
  2. full screen button and listeners
  3. stage fullscreenEvent listener
  4. (functions for each)
  5. allowfullscreen = true

Example

[kml_flashembed fversion=”9.0.28″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/03/fullscreen_tut.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″ allowfullscreen=”true”]Get Adobe Flash player

[/kml_flashembed]

1. Stage properties exist that allow us to specify what type of fullscreen we want.  We can have the swf scale to fit the fullscreen area (StageScaleMode.SHOW_ALL), not scale at all (StageScaleMode.NO_SCALE), skew to fit fullscreen (StageScaleMode.EXACT_FIT), and scale to fill fullscreen area (Stage.ScaleMode.NO_BORDER).  We may also edit the alignment of the stage in the fullscreen area; in this example I’m using TOP, but refer to documentation for more options

2. Adobe has placed restrictions on when a swf can enter fullscreen, and has deemed that it must result from a user interaction, a mouse click or keystroke. So create your buttons (or keyListeners). I prefer to have one button to enter fullscreen and another to exit, and have them both call the same function to toggle fullscreen. It gives a clearer communication to the user. I then control the visibility of these buttons depending on the current display state of the stage.

3. Another listener to watch the stage dispaly state. stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange); This will fire every time the stage display state changes. We need this because as I mentioned earlier, when entering fullscreen we use our own function, but the ‘hit esc to exit fullscreen’ functionality is built into the flash player, we can’t update our stage layout or button visibility without watching to catch when the display state is changed. Using this method we can update our stage layout any and every time.

4. Of course flesh out the fullscreenToggle function to include anything else you need.

5. Lastly, for a SWF file embedded in an HTML page, the HTML code to embed Flash Player must include a ‘param’ tag and ’embed’ attribute with the name ‘allowFullScreen’ and value ‘true’, like this:

<object>
    ...
    <param name="allowFullScreen" value="true" />
    <embed ... allowfullscreen="true" />
</object>

The allowFullScreen tag enables full-screen mode in the player. If you do everything else right and don’t include this in your embed codes, fullscreen will not work. The default value is false if this attribute is omitted. Note the viewer must at least have Flash Player version 9,0,28,0 installed to use full-screen mode. Also note that  the simple (ctrl + enter) testing your movie in flash will not allow fullscreen either, you must use the debug tester (ctrl + shift + enter) … or go open the published swf in flash player.

Actionscript

[cc lang=”actionscript”]
stage.scaleMode = StageScaleMode.SHOW_ALL;
stage.align = StageAlign.TOP;

var stageDisplayAdjustCounter:uint = 0;

fsb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
ssb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange);

fsb.buttonMode = true;
ssb.buttonMode = true;

//fullscreen buttons need this to adjust the stage display state.
//pressing escape to exit fullscreen bypasses this function
function fullscreenToggle(e:MouseEvent = null):void {
status.appendText(stageDisplayAdjustCounter+”. fullscreenToggle from “+stage.displayState+”\n”);
//normal mode, enter fullscreen mode
if (stage.displayState == StageDisplayState.NORMAL){
//set stage display state
stage.displayState = StageDisplayState.FULL_SCREEN;
}
//fullscreen mode, enter normal mode
else if (stage.displayState == StageDisplayState.FULL_SCREEN){
//set stage display state
stage.displayState = StageDisplayState.NORMAL;
}
//here we subtract 1 from the counter because it has already incremented (in onFullscreenChange) when we set the display state above

status.appendText((stageDisplayAdjustCounter-1)+”. fullscreenToggle to “+stage.displayState+”\n”);
status.scrollV = status.maxScrollV;

}

//this function is called every and anytime the stage display state is adjusted
//either by pressing our buttons or
function onFullscreenChange(e:FullScreenEvent = null):void {
status.appendText(stageDisplayAdjustCounter+”. onFullscreenChange\n”);
status.scrollV = status.maxScrollV;
if (stage.displayState == StageDisplayState.FULL_SCREEN) {
fsb.visible = false;
ssb.visible = true;
}
else {
fsb.visible = true;
ssb.visible = false;
}

stageDisplayAdjustCounter++;
}

onFullscreenChange();

[/cc]

Source

Download fullscreen_tut.fla file

Fullscreen in AS3 Tutorial | Plus Firefox Flash bug when enter fullscreen keyboard events fired

To view the full fullscreen tutorial go here: How to use fullscreen in AS3 | Stage Display State Tutorial

fullscreen_keyboard_bug_thumbnail
Sucks when you seem to have a bug in your code somewhere so you dissect your code over and over and are convinced that according to your code, everything should be fine, so you come back later thinking fresher eyes will see it, and still can’t find the cause, and then resort to debugging with various trace statements…

I’ve been developing a custom flash player in as3. Fullscreen and all those bells and whistles… I could test locally and eveything was beautiful… but then upload and test in the browser and when I would go into fullscreen mode, the video would pause. Pretty annoying bug! So I’d go through my code and examine anywhere a call to pause the video (there are only two): pressing the play/pause button and pressing the spacebar (keyboard shortcut). I couldn’t find any correalation. I was thinking adobe must be doing some crazy security things when going into fullscreen… but no, no other video player I’ve seen does this!
After commenting out my keyboard events, the bug is fixed! But I still can’t use the spacebar to pause/play. I love this functionality for usability. Isn’t that pretty standard for video? space to pause, it’s like second nature to me.

Does entering fullscreen really trigger a keyboard event equivalent to pressing my spacebar!? Sure enough. how much sense does that make, but it gets better! I had a friend test this swf and it worked fine for him. No pause on fullscreen! Wha!? Using good ole IE7… So yes, it’s a browser specific actionscript bug, firefox even! That was one of the things I liked about flash initially, not too much to mess with as far as cross browser issues once you get the swf embedded in the html, or so I thought.

So after playing with booleans to try to control when the keyboard events will be working.

Has anyone experienced this or another issue that just left you baffled, even after you figured out the bug?!

Well, I’ve done the right thing, I’ve posted about it to hopefully help anyone else having this issue. I created a test case file to rule out anything else in my code and make sure I’m not crazy.
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/03/fullscreen_keyboardevent_bug.swf” targetclass=”flashmovie” bgcolor=”#336666″ publishmethod=”dynamic” width=”550″ height=”400″ allowfullscreen=”true”]

Get Adobe Flash player

[/kml_flashembed]

[cc lang=”actionscript”]
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;

fsb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
ssb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange);
fsb.buttonMode = true;
ssb.buttonMode = true;
onFullscreenChange();

function fullscreenToggle(e:MouseEvent = null):void {
//normal mode, enter fullscreen mode
if (stage.displayState == StageDisplayState.NORMAL){
//set stage display state
stage.displayState = StageDisplayState.FULL_SCREEN;
}
//fullscreen mode, enter normal mode
else if (stage.displayState == StageDisplayState.FULL_SCREEN){
//set stage display state
stage.displayState = StageDisplayState.NORMAL;
}
onFullscreenChange();
}
function onFullscreenChange(e:FullScreenEvent = null):void {
if (stage.displayState == StageDisplayState.FULL_SCREEN) {
tracer(“full screen”);
fsb.visible = false;
ssb.visible = true;
}
else {
tracer(“small screen”);
fsb.visible = true;
ssb.visible = false;
}
tracer(“toggle to “+stage.displayState);
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);

function keyDownListener(e:KeyboardEvent) {
tracer(“keyboard: keyCode: “+ e.keyCode.toString());
}
var tracerwindow:TextField;
function tracer( …args){
if (tracerwindow == null){
tracerwindow = new TextField();
tracerwindow.width = stage.stageWidth/2;
tracerwindow.height = stage.stageHeight;
tracerwindow.multiline = true;
addChild(tracerwindow);
}

for (var i:uint = 0; i < args.length; i++) { tracerwindow.appendText(args[i].toString() + " "); } tracerwindow.appendText("\n"); trace(args); } [/cc]other places that I've found this mentioned that helped me understand what was going on: http://dreamweaverforum.info/actionscript-3/123202-keyboard-event-full-screen.html http://bugs.adobe.com/jira/browse/FP-814

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

StomperNet Strikes Again! with FormulaFIVE

StomperNet has been a ‘buzz’.

After Andy’s ‘Mea Culpa‘ why wouldn’t it be…

But this is so much better and bigger, learning many lessons from the last launch – StomperNet strikes again!

Teamed up with Paul Lemberg a new product called FormulaFIVE (F5 for short).

Just launched a video to excite the industry!
So check out stomperf5.com now!

formula five landing page

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)

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.

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.