How to Create a Tower Defense Game in AS3 – Part 2

Part 2: Adding Turrets

Okay, so in this part of the tutorial, we are going to make it so when the user clicks on any of the empty blocks, a turret is created. The first step to take in to create a Turret class. You know the drill, create a new ActionScript File, save it as “”, and type in the following code:

package{//creating the basic skeleton
	imporProxy-Connection: keep-alive
Cache-Control: max-age=0

	public class Turret extends MovieClip{
		private var _root:MovieClip;

		public function Turret(){
			//adding the required listeners
			this.addEventListener(Event.ADDED, beginClass);
			this.addEventListener(Event.ENTER_FRAME, eFrameEvents);
		private function beginClass(e:Event):void{
			_root = MovieClip(root);

			//drawing the turret, it will have a gray, circular, base with a white gun;,0,12.5);;;, 0, 5, 20);;
		private function eFrameEvents(e:Event):void{

			if(_root.gameOver){//destroy this if game is over
				this.removeEventListener(Event.ENTER_FRAME, eFrameEvents);

This will be only the beginning of what we program into the Turret. Next, we have to define a function in the _root of the document that will create the turrets. Add this code to the bottom in your source .fla file:

function makeTurret(xValue:int,yValue:int):void{//this will need to be told the x and y values
	var turret:Turret = new Turret();//creating a variable to hold the Turret
	//changing the coordinates
	turret.x = xValue+12.5;
	turret.y = yValue+12.5;
	addChild(turret);//add it to the stage

Now, we can finally make it so the turret is created when the user clicks on an empty block. Find the function thisClick() in “”. Add the following code to that:

_root.makeTurret(this.x,this.y);//make the turret
//remove all the listeners so it can't be clicked on again
this.buttonMode = false;;,0,25,25);;
this.removeEventListener(MouseEvent.MOUSE_OVER, thisMouseOver);
this.removeEventListener(MouseEvent.MOUSE_OUT, thisMouseOut);
this.removeEventListener(MouseEvent.CLICK, thisClick);

Now, if you test out the game, a turret should appear whenever you click on any empty block!

Well, that’s it for this tutorial. Next time, we’ll add enemies and program them!


Download Source
(Requires Flash CS3 or above)


Enter your email address:  

Awesome Tutorials