Tutorial: Create a Tower Defense Game in AS2 – Part 2

Written By MrSun at 8:02 am - Saturday, April 25th, 2009
Categories: Flash

Step 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. Let’s begin, shall we?

Open up your main flash file and find the code where we set the empty block’s onRollOver() and onRollOut functions. Well, now we’re going to create a onRelease() function, which just means clicking. Add this code to around Line 65, or after you set the onRollOver and onRollOut functions:

_root['block'+i].onRelease = function(){
	//this function will run when the empty block is clicked on
	//change this guy's color back
	var newColor = new Color(this);
	//set all other mouse functions to null in order to keep it from being clicked again
	this.onRollOver = null;
	this.onRollOut = null;
	this.onRelease = null;
	//create an empty turret movieclip that will be on the top root layer

	//drawing the turret, it will have a gray, circular, base with a white gun
	_root['t'+this._name].beginFill(0x999999);//coloring the base light gray
	_root['t'+this._name].moveTo(0, 12.5);//move the entire shape a certain way
	//create 4 curves so that it'll look like a circle
	_root['t'+this._name].endFill();//end the fill so we can make a new one
	//creating the gun
	//setting the gun to be on the center of the turret
	_root['t'+this._name].gun._x = 12.5;
	_root['t'+this._name].gun._y = 12.5;
	//set the turrets coordinates to be the blocks coordinates
	_root['t'+this._name]._x = this._x;
	_root['t'+this._name]._y = this._y;

Well, it’s a lot of code, but it gets the job done.

That’s it for this part of the tutorial. Next time, we’ll create and program some enemies!

Final Product

Source Files (Zipped)



What if you have custom movieclips for terrain and turrets instead of circles and squares?


I think you have to put(for the enemies):

_root[‘t’+this._name].attachMovie(“name_in_the_library”, “new_name”, _root.getNextHighestDepth(), {_x: this._x, _y: this._y});

And for the terrain:

_root[‘block’+i].attachMovie(“name_in_the_library”, “new_name”, _root.getNextHighestDepth(), {_x: (i-row*22)*25, _y: row*25});

I hope this work 😀


DON’T READ THE SENTECE “for the enemies”!!!
I wanted to put “for the turrets”…
Sorry 😛


thanks yours is a gun mine is a greensquare