Tutorials

January 31, 2011

Changing Colors Dynamically with ColorTransform in AS3

More articles by »
Written by: Par
Tags: ,
colorthumbnail

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit

Well, this is the first tutorial in a long time. Mostly because I’m still using CS3 and all CS4 and CS5 users are having a hard time understanding my tutorials. That’s okay, we’ll keep mostly in the code and everyone will be able to understand it (I hope).

Alright so what’s this tutorial about? Well let’s say your game has enemies that on death splat blood all over the place… sounds wonderful. So maybe these enemies are aliens with green blood, but a couple of them need to have blue blood, and well, maybe,  another one should have yellow. What do you do? Copy the same movieclip over and over each time changing the color of the blood? No… there’s a much easier solution for handling color changes in ActionScript. (If you don’t like the blood reference, imagine a cutesy dress up game where you want to change the colors of the outfits)

The beautiful thing about code based colour (for our ‘u’ loving friends) changing is it is incredibly simple in as3. As long as you understand the basics, you’ll have no problem colour changing with your eyes closed.

Step 1: Get the starting FLA and get Ready to Code

Alright, so to get started with this tutorial I ask that you download this zip file. There is a colorme.fla, colorme.swf, and a folder containing a ColorExample.as file in the archive.  You will not need to make any changes to colorme.fla during this tutorial. But feel free to look over the fla as the setup of the file is important to how we write our code. You’ll notice in the library that there are two objects.  There names don’t matter and neither have an linkage attached to them. I have simply placed the sphere movieclip on the middle of the stage. I gave it the instance name of “button”.  Inside of button you’ll notice a few layers that make up the artwork. I locked all the layers but one. This one layer has our movieclip that we wish to color in it. I gave that button the instance name of “colorMe”.

Very simple, so all we will have to do to access our colorMe clip from our code is call button.colorMe in our Document Class. (BTW, if any of this sounds confusing, please go read AS3 Flash Games for Beginners as it should make sense of most everything) Which brings me to the point that I’ve already set the Document Class to be colorMe.ColorExample (our file in the colorMe folder).

Step 2: Understanding some Hexadecimal

Hopefully you understand hexadecimal. But if not let me make it really simple. Instead of counting 0-9, you’re counting 0-F (16 different characters instead of 10). Normally we’d count 1,2,3,4,5,6,7,8,9,10. In hex we’d count 1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,10. Hex 10 is equal to a 16 in decimal. Anyway, we don’t have to fully understand it, we just need to know how to use it.  If you can understand that 0 is low and F is high, then you are good to go.

Second, colors in hex form are six characters long, two for each color. And it’s always in the order Red, Green, and Blue.  So an example hex value would look like this #43A72F. So is this color (#43F72A) mostly red, green, or blue? Green, of course. Why? Because A7 is greater than 43 and 2F both. For some clarity the numbers A7, 43, and 2F in hexadecimal are equal to 167, 67, and 47. The larger the number the more of that color is in the combination. Also, #000000 is black and #ffffff is white and equally important ff is equal to 255.

If you are looking for a specific color, the eye dropper in most all graphics software will tell you the hex value, so really there is no need to worry about it.

Step 3: What is this ColorTransform Awesomeness?

Okay so your code (in ColorExample.as) looks like this:

package colorme
{
	import flash.display.Sprite;
	import flash.display.DisplayObject;
 
	/**
	 * ...
	 * @author AsGamer.com
	 */
	public class ColorExample extends Sprite
	{
 
		public function ColorExample()
		{
 
		}
 
	}
 
}

Alright, First thing I want to do is write our function to change the colors. You are going to need to import an additional class, flash.geom.ColorTransform, so go to your imports at the top and import it now. Great! let’s write a function.

Now let’s write a function that takes two parameters, our movieclip that needs a color change and the color we want to change it to be. I’ll name it colorClip and it will look as follows.

		public function colorClip(mc:DisplayObject, val:Number)
		{
 
		}

Of course, this isn’t the finished code, we need to write the insides that make this thing function. But to break it down, we are accepting a DisplayObject and a number. DisplayObject is pretty much the base class of all things visible in Flash. I’m not absolutely sure that’s true but I know Sprites and MovieClips are definitely extended from our DisplayObject friend. This means we can pass anything thats extended from a DisplayObject through to this function. Then we accept a number which will be our hex color value. Now let’s write all the code for our function… don’t worry it’s only three lines.

		public function colorClip(mc:DisplayObject, val:Number)
		{
				var colorTransform:ColorTransform = new ColorTransform();
				colorTransform.color = val;
				mc.transform.colorTransform = colorTransform;
		}

Alright Breakdown:

  • var colorTransform:ColorTransform = new ColorTransform(); Let’s see, create a variable and an instance of the ColorTransform class. Simple.
  • colorTransform.color = val; So we take our hex number and pass it into the color property of our colorTransform variable.  Just to let you know val will equal a number like this 0x0000FF, 0x00FF00, 0xFF9944, or 0x1A4BB6. (Instead of using # as before we use 0x to establish the number is hex)
  • mc.transform.colorTransform = colorTransform; Transform that DisplayObject. All done.

Step 4: Let’s Make Color Changes.

Okay, we could end this now with one line of code. Go in the constructor and simply add:

colorClip(button.colorMe, 0xFF0000);

Guess what? We just made our button red. Example below.

Step 5: More Color Transformation Fun

Okay, you can quit with the above example and be happy with your life. You made a red button, the Nobel peace prize is definitely right around the corner.  But if you’re one of those learning types, we’ll try something else :D

I simply want to make the color change each time I click the Stage. So erase everything in your constructor and add this:

stage.addEventListener(MouseEvent.MOUSE_UP, changeColor, false, 0, true);

This is an event listener. We ask the stage to watch out for someone releasing a click on the stage so when they do we can call the changeColor function. changeColor function doesn’t exist? Let’s write one.

		private function changeColor(e:MouseEvent) : void
		{
			var red:int = int(Math.random() * 255);
			var green:int = int(Math.random() * 255);
			var blue:int = int(Math.random() * 255);
 
			var hex:Number = Number("0x" + red.toString(16) + green.toString(16) + blue.toString(16));
 
			colorClip(button.colorMe, hex);
		}

Confused? Don’t be. Remember a few steps and paragraphs up when I said FF = 255. Well, I hope that makes sense of what is happening when we define the red, green, and blue variables. If not, let me explain. Math.random() is selecting a random number between 0 and 1. We then times that number by 255. Which means the number is now something between 0 and 255. Then we make it an integer, which will just get rid of any decimals. Excellent, so our red, green, and blue variables should all have a whole number between 0 and 255 stored in them.

I almost LOL at the next line because it’s kinda funny. We’re taking three number… making them strings… concatenating them together… then making them all a number again. Why? Well flash has a nice function we can run on our integers to convert them to hex.  Simply use .toString(value) where value is the base. Since hex is base 16, we used the number sixteen.  Last we need to throw the 0x in front of our string and convert it back into a number. Once done, we are ready to send it off to our color clip function which will do all the magic.

Oh yeah, did I mention we are done? Test it out below. Here’s the final source code.

package colorme
{
	import flash.display.MovieClip;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.ColorTransform;
 
	/**
	 * ...
	 * @author AsGamer.com
	 */
	public class ColorExample extends MovieClip
	{
 
		public function ColorExample()
		{
			//colorClip(button.colorMe, 0xFF0000);
			stage.addEventListener(MouseEvent.MOUSE_UP, changeColor, false, 0, true);
		}
 
		private function changeColor(e:MouseEvent) : void
		{
			var red:int = int(Math.random() * 255);
			var green:int = int(Math.random() * 255);
			var blue:int = int(Math.random() * 255);
 
			var hex:Number = Number("0x" + red.toString(16) + green.toString(16) + blue.toString(16));
 
			colorClip(button.colorMe, hex);
		}
 
		public function colorClip(mc:DisplayObject, val:Number)
		{
				var colorTransform:ColorTransform = new ColorTransform();
				colorTransform.color = val;
				mc.transform.colorTransform = colorTransform;
		}
 
	}
 
}

Similar Posts:


Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit


About the Author

Par
Hey! Don't be surprised, I'm a flash developer. While Flash is definitely one of my favorite languages to develop in, most of all I just like making games. If you want to see the games I've developed so far head over to my website, DigitallyBold, in the link below. If you want to know more about what I'm working on now and in the future be sure to follow me on twitter.




16 Comments


  1. Cinder

    Haven’t used Flash in quite awhile, when suddenly the need for it arose earlier today so I went straight here to give the ol’ memory a good kick-start. Awesome to see ASGamer is still up and about!

    Thanks for another great article!


  2. This is a very helpful tutorial. One thing to consider… It might make it a lot easier for people to follow if your sample color (#43A72F) correlated to your sample comparison (77 is greater than 43 and 29) At the very least, you might want to remove 43 from your sample comparison, because people assume that 43 in the comparison correlates to the 43 in the color, which it does not.

    A base 16 (hex) 43 is 67 in base 10 (decimal)
    A7 is 167 in decimal
    29 is 41 in decimal

    The example still holds up as the color IS more green, because 167 is greater than 67 and 41. I bring this up not to be a know it all. In fact, I didn’t know any of this until I started reading your post and decided I should understand Base 16 counting before I continued. I made the assumption that A7 was 77, because I saw 43 in there along with 29. Eventually I figured out that “77 is greater than 43 and 29″ were arbitrary numbers. So really, this is all MY fault for assuming ;)

    Anyway, it’s a nice article. You might consider revising that portion a bit for people who want to understand how the decimal value conversion allows you to say, “wow, there’s a lot more green in this color than red or blue”. Great site you got here, I always enjoy reading. Anyway, I’m not try to be that guy, this is just a recounting of what confused me as I was trying to understand.


  3. Par

    Thanks Cinder and Sean.

    Sean, I’ve made some changes per your suggestions :) Thanks.


  4. Good stuff, Par. Keep the articles/tutes coming. :)


  5. That was nice ;)
    Can’t wait for the next tutorial :)


  6. Hi and thanks for spending some time to describe the terminlogy for the novices!


  7. The calculation fails if red = 5, green = 5, blue = 5, because it will parse “0×555″ as color, which is not dark gray, but some blue in flash. If you want it do it correctly, you should calculate it bitwise or add a zero before the 5 to make 0×050505.

    A while ago I have created a helper class for this:
    http://code.google.com/p/stroep/wiki/ColorClass


  8. Andrew

    WOAH! 2 posts in one day. I’ve been coming here now and again since this site was born ^^. More frequent posts plzzz! :)


  9. You cannot get full red with this code. While the random color generation works, it doesn’t include the whole spectrum Flash can create. If the number the random value returns is lower than 10, it ends up removing a digit, throwing off the six digit combination when you create your hex.

    e.g.

    red = 0
    green = 255
    blue = 0

    This returns blue, not green. While the random fact works fine because you aren’t asking for a specific color, it doesn’t allow you to accurately select your own color. You would need to add an if statement for when the value of a color is less than ten.

    var redCode:String;
    if (red < 10)
    redCode = (“0″ + red.toString(16));
    else
    redCode = red.toString(16);

    var greenCode:String;
    if (green < 10)
    greenCode = (“0″ + green.toString(16));
    else
    greenCode = green.toString(16);

    var blueCode:String;
    if (blue < 10)
    blueCode = (“0″ + blue.toString(16));
    else
    blueCode = blue.toString(16);

    var formula:String = (“0x” + redCode + greenCode + blueCode);

    var hex:Number = Number(formula);

    That fixes the single digit transfer, and you can still use the math.random() to randomize your colors.


  10. Par

    Good points, Nick & Mark.


  11. Zukero

    Using string concatenation is horrible for managing numbers….

    Somewhat unusual operators for Flash dev come in handy in such cases : bitwise shifts, and bitwise OR.

    This line :
    hex = red << 16 | blue << 8 | green;
    will perform way faster, and without any single-digit values bug.


  12. Easiest way to generate random color:

    var color:uint = Math.random() * 0xFFFFFF;


  13. NoNick

    Thank you!


  14. Rogerio

    very nice tutorial, but where i can get the import display as?


  15. tim

    thanks very much for the tutorial, just wondering how you would include multiple buttons in 1 file?


  16. I hardly leave a response, but i did some searching and wound up here Color changing with ColorTransform in AS3 Actionscript | Flash Game Development Tutorials – As Gamer. And I actually do have a couple of questions for you if it’s allright. Is it just me or does it appear like a few of these responses come across as if they are coming from brain dead visitors? :-P And, if you are writing on other sites, I would like to keep up with anything fresh you have to post. Could you make a list of the complete urls of your communal sites like your linkedin profile, Facebook page or twitter feed?



Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">


Advertisement