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. The first step to take in to create a Turret class. You know the drill, create a new ActionScript File, save it as “Turret.as”, and type in the following code:
package{//creating the basic skeleton imporProxy-Connection: keep-alive Cache-Control: max-age=0 flash.display.MovieClip; import flash.events.*; 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 this.graphics.beginFill(0x999999); this.graphics.drawCircle(0,0,12.5); this.graphics.endFill(); this.graphics.beginFill(0xFFFFFF); this.graphics.drawRect(-2.5, 0, 5, 20); this.graphics.endFill(); } private function eFrameEvents(e:Event):void{ if(_root.gameOver){//destroy this if game is over this.removeEventListener(Event.ENTER_FRAME, eFrameEvents); MovieClip(this.parent).removeChild(this); } } } }
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 “EmptyBlock.as”. 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; this.graphics.beginFill(0x333333); this.graphics.drawRect(0,0,25,25); this.graphics.endFill(); 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!
Final Product
discuss this topic to forum
