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

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!

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

Voters Aide, a Google Analytics Event Tracking Report Example

Overview

Voters Aide – a little flash app I made in some spare time to help prioritize the issues and positions for the 2008 presidential election. The app would let uses assign a weight to each of the big issues (0 – 100), and then read each candidates positions on every issue and record to which candidate they leaned (0 -100). The app did all the math then. Simply multiply the weight by their leaning and total it up. So if on the economy (which was reported the heaviest weighted issue overall) you say it is a weight of 90 and you lean one way +25 then your economy position is calculated 25 x .9 toward that candidate (22.5). To get a better understanding of it even though the election is over, go ahead and run through it yourself. I copied the selection of top issues and each candidate’s position from CNN’s website. I even randomized which side each candidate would show up on and left them unmarked so no one would be prejudiced toward their candidate. I wanted uses actual positions and priorities to speak louder than their preconceived preference or bias. I know this is flawed because the candidates position descriptions often were dead a give away, even sometimes saying the candidates name. Ideally it’d be great to simplify the positions but I wasn’t about to try to summarize it all! =)

Now that the election is decided though, I wanted to share what else I learned with this app. I included my google analytics event tracking methods in the voters aide app. So to everyone that has been using the app, I was watching!

Results

I used event tracking to see what weight was applied to every issue, to see which way users leaned on every issue and of course their final calculations which told them who they support. The reports are interesting because they not only tell you how many people apply a weight to an issue, but also what value. They say not only how many users actually continued through each issue and stated which way they lean, but also how far they lean and who they lean to! Not only how many users actually completed voters aide to the final screen which shows their calculation, but also which candidate they supported in voters aide and even by how much!
The results were very interesting in the weights people used to prioritize the issues. Maybe that is because is is easier to visualize? But the issues were ranked in the following order:

Label Total Events Unique Events Event Value Avg. Value
1.economy70605,25875.11
2.education63554,54872.19
3.iraq46373,22070.00
4.energy67574,57968.34
5.taxes40382,64166.02
6.homeland security50433,26465.28
7.health care59533,78964.22
8.afghanistan64474,06863.56
9.housing50393,12562.50
10.social security33292,00960.88
11.abortion92585,54460.26
12.environment56483,32459.36
13.iran40372,26656.65
14.free trade41362,22454.24
15.israel38362,04853.89
16.guns49422,46150.22
17.russia31251,55050.00
18.stem cell research27261,29648.00
19.LBGT37311,75047.30
20.immigration38331,74946.03
21.cuba57472,15137.74

Here is an example of the report for the most important issue, economy. It stats which candidate had the users support and even how many times and the average value.

Label Total Events Unique EventsEvent Value Avg. Value
1.supportmccain26241,54559.42
2.supportobama23191,43562.39
3.supportno2100.00

I’ll go ahead and say, (although the app was not designed to predict the president or even considered your location, it just counted how many times it reported to users which candidate they leaned towards) according to Voters Aide, John McCain would have won the election.  So more people who used Voters Aide lean McCain in the end, once they get to the end of the issues. I’d have to add that this is a very small sample size and even if it were larger, I never tested the app for usability and user understanding, so the end result doesn’t mean that much in the end. But as you will be curious here is the report for the final page events:

Label Total Events Unique Events Event Value Avg. Value
1.JOHN MCCAIN27212,23982.93
2.BARRACK OBAMA19151,55581.84
3.NO ONE12101,200100

Anyways, great election. I hope all this change will be a change for the better.

Congratulations to everyone who is excited about the future & condolences to everyone lamenting the end of the world.

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)