1. Code
  2. Game Development

Quick Tip: Create a Typewriter Text Effect Class

Scroll to top
2 min read

In this Quick Tip, we'll create a static, re-usable ActionScript class that will produce a Typewriter effect with a single line. Read on!


Step 1: Brief Overview

We'll split a user defined string into an array, and then add the resulting letters to a TextField one by one using the Timer class.


Step 2: Typewriter Class

Our class will be static, which means it doesn't need to be instantiated using the new keyword. To access a static class member, use the name of the class instead of the name of an instance.

Create a new ActionScript file and write the following code:

1
2
package 
3
{
4
	import flash.text.TextField;
5
	import flash.utils.Timer;
6
	import flash.events.TimerEvent;
7
	
8
	public final class Typewriter
9
	{
10
		/* Declare the variables and methods as static */
11
12
		private static var chars:Array; //the characters in the string

13
		private static var tf:TextField; //textfield to which the string will be written

14
		private static var timer:Timer; //pauses between writing each character

15
		private static var i:int = 0; //variable used to count the written characters

16
		
17
		public static function write(txt:String, txtField:TextField, time:Number):void
18
		{
19
			chars = txt.split(""); //split the string into an array of characters

20
			tf = txtField; //assign tf to the text field passed to the function

21
			timer = new Timer(time); //set time according to parameter

22
			
23
			timer.addEventListener(TimerEvent.TIMER, writeChar);
24
			timer.start(); //start writing function

25
		}
26
		
27
		private static function writeChar(e:TimerEvent):void
28
		{
29
			if (i < chars.length) 
30
			{
31
				tf.appendText(chars[i]); //writes a char every time the function is called

32
				i++; //next char

33
			}
34
			if (i >= chars.length) //check whether string is complete

35
			{
36
				timer.stop();
37
				timer.removeEventListener(TimerEvent.TIMER, writeChar); //clear timer

38
				timer = null;
39
			}
40
		}
41
	}
42
}

Step 3: Usage

The usage couldn't be easier - just add the Typewriter.as class to your project folder and use the following code:

1
2
import Typewriter;
3
4
Typewriter.write('Text to Write', targetTextfield, 50);

That's it, test your movie and you'll see your TextField using the Typewriter effect.


Step 4: Example

I used the class in on this example swf so you can see the effect:


Conclusion

Use this class to create your own effects!

Thank you for reading. If you'd like a more advanced version of this effect for use in your projects, take a look at Rasmus Wriedt Larsen's Letter By Letter Animation.