This is probably one of the easiest pieces of code that you will learn. Don’t let that deceive you though. Trace is an important bit of actionscript to know. It can be incredibly useful when you are still in the testing process of your game. In this tutorial I am going to teach you about trace, what it does, and how to apply it using actionscript 2 code.

Before I talk about the code you’ll need, I’m going to explain what trace does and how to use it. Trace() will output a string or value in your output panel when you test your flash movie. This output will only be seen when you are in Flash, testing your game. It will not be seen in your .swf that is published when you release your game. There is an extension in Firefox though that will show you what is being traced, so it’s usually a good idea to remove the traces once you’ve tested your code. To use trace(), you just put whatever variable or string you want in there. It will read your variable or string and show you what their value is in the output panel.

Here’s an example of trace() in action. Just type it into your actions frame and hit control+enter to test your flash.  It’s pretty simple, just put whatever text you want to be outputted between the quotation marks.

trace ("Freelance Flash Games is the best! Or just put whatever you like in here.");//output the text that has been put between the two "

Outputting a simple piece of text isn’t the only thing trace can do. It can also track variables and output their value. You can even have them outputting the value of the variable every frame. Here’s an example:

var myVar:Number = 2;//creates the variable named myVar with a value of 2.
onEnterFrame = function(){//every frame, run this function
myVar+=1;//increase the variable myVar's value by 1 each frame
trace(myVar);//ouput the value of myVar. This will be done every frame.
}//end of code

If you are working with multiple variables, as you will in most games, a good idea is to put the name of the variable before the actual value of the variable to keep the output organized. Here is an example of it:

var myVar1:Number=0;
var myVar2:Number=0;
onEnterFrame = function(){//every frame, run this function...
myVar1+=1;//add 1 to myVar1 every frame
myVar2-=3;//subtract 3 from myVar2 every frame
trace("myVar1 =" + myVar1);//output the string 'myVar1=' and output the value of myVar2
trace ("myVar2 =" + myVar2);//output the string 'myVar2 =' and output the value of myVar2

Now are you starting to see why trace can be so useful? You can test multiple variables in the output panel using this to make sure they are working correctly. That’s it for trace. Any questions?

Related posts:

  1. Code Bits: Variables
  2. Code Bits: hitTest
  3. Code Bits: Set Interval