Flash Game Tuts » AS2 http://www.flashgametuts.com Free Flash Game Tutorials in AS2 and AS3 Thu, 30 Jul 2009 15:11:46 +0000 en hourly 1 http://wordpress.org/?v=3.2.1 How to Create a Tower Defense Game in AS2 – Part 7 http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-7/ http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-7/#comments Sat, 25 Jul 2009 12:07:48 +0000 Mr Sun http://www.mrsunstudios.com/?p=1534 Welcome back! This part of the tutorial is where we just add all of the finishing touches to the game! Unlike the other parts of the tutorial, I won’t comment any of the code I give you, as the knowledge you have learned from this tutorial should tell you what’s going on. Luckily for you, there aren’t too many finishing touches for us to make, so your brain won’t hurt too much.

Now, what can we add to our little game? The answer is: it’s up to you to decide what to add. It’s also up to you to use what you’ve learned to do it right. Thank you and good night.

]]>
http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-7/feed/ 0
How to Create a Tower Defense Game in AS2 – Part 6 http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-6/ http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-6/#comments Sat, 25 Jul 2009 12:06:07 +0000 Mr Sun http://www.mrsunstudios.com/?p=1531 Welcome to the 6th part of the tutorial, Expanding on the Game! Well, what do I mean by “Expanding”? Well, by expanding, I mean that we’re going to create more enemies and more levels. Sounds pretty cool, doesn’t it?

Open up “source.fla” and find the makeEnemies function. We’re going to have some major renovations to this functions. Just replace the function with this new code:

function makeEnemies():Void{//this function will add enemies to the field
	if(enemyTime < enemyLimit){//if it isn't time to make them yet
		enemyTime ++;//then keep on waiting
	} else {//otherwise
		var theCode:Number = enemyArray[currentLvl-1][currentEnemy];//get the code from the array
		if(theCode != 0 && theCode != null){//if it's not set at 0
			//then create a new enemy and add it to the enemy holder
			enemyHolder.createEmptyMovieClip('enemy'+currentEnemy,enemyHolder.getNextHighestDepth());
			//now we're going to draw the enemy. It'll just be a tiny red circle
			enemyHolder['enemy'+currentEnemy].beginFill(0xFF0000);//coloring them red gray
			enemyHolder['enemy'+currentEnemy].moveTo(0, 2.5);//move the entire shape a certain way
			//create 4 curves so that it'll look like a circle
			enemyHolder['enemy'+currentEnemy].curveTo(0,10,5,10);
			enemyHolder['enemy'+currentEnemy].curveTo(10,10,10,5);
			enemyHolder['enemy'+currentEnemy].curveTo(10,0,5,0);
			enemyHolder['enemy'+currentEnemy].curveTo(0,0,0,5);
			enemyHolder['enemy'+currentEnemy].endFill();//end the fill
 
			//add a few variables to the enemy
			enemyHolder['enemy'+currentEnemy].enLevel = theCode;//setting its level to be what # it is
			enemyHolder['enemy'+currentEnemy].maxSpeed = 3;//how fast it can possibly go
			enemyHolder['enemy'+currentEnemy].xSpeed = 0;
			enemyHolder['enemy'+currentEnemy].ySpeed = 0;
			enemyHolder['enemy'+currentEnemy].health = 5*theCode;
 
			//checking what the start direction is
			if(_root.startDir == 'UP'){//if it's starting up
				enemyHolder['enemy'+currentEnemy]._y = 300;//set the y value off the field
				enemyHolder['enemy'+currentEnemy]._x = _root.startCoord;//make the x value where it should be
				enemyHolder['enemy'+currentEnemy].xSpeed = 0;//make it not move horizontally
				enemyHolder['enemy'+currentEnemy].ySpeed = -enemyHolder['enemy'+currentEnemy].maxSpeed;//make it move upwards
			} else if(_root.startDir == 'RIGHT'){//and so on for other directions
				enemyHolder['enemy'+currentEnemy]._x = -25;
				enemyHolder['enemy'+currentEnemy]._y = _root.startCoord;
				enemyHolder['enemy'+currentEnemy].xSpeed = enemyHolder['enemy'+currentEnemy].maxSpeed;
				enemyHolder['enemy'+currentEnemy].ySpeed = 0;
			} else if(_root.startDir == 'DOWN'){
				enemyHolder['enemy'+currentEnemy]._y = -25;
				enemyHolder['enemy'+currentEnemy]._x = _root.startCoord;
				enemyHolder['enemy'+currentEnemy].xSpeed = 0;
				enemyHolder['enemy'+currentEnemy].ySpeed = enemyHolder['enemy'+currentEnemy].maxSpeed;
			} else if(_root.startDir == 'LEFT'){
				enemyHolder['enemy'+currentEnemy]._x = 550;
				enemyHolder['enemy'+currentEnemy]._y = _root.startCoord;
				enemyHolder['enemy'+currentEnemy].xSpeed = -enemyHolder['enemy'+currentEnemy].maxSpeed;
				enemyHolder['enemy'+currentEnemy].ySpeed = 0;
			}
 
			enemyHolder['enemy'+currentEnemy]._x += 5;//fixing the x value
			enemyHolder['enemy'+currentEnemy]._y += 5;//fixing up the y value
 
			enemyHolder['enemy'+currentEnemy].onEnterFrame = function(){//give it some functions
				this._x += this.xSpeed;
				this._y += this.ySpeed;
 
				//checking what direction it goes when finishing the path
				if(_root.finDir == 'UP'){//if it finishes at the top
					if(this._y <= -25){//if the y value is too high
						_root.lives --;//take away a life
						_root.money -= 5*this.enLevel;//don't let the player gain any money
						this.removeMovieClip();//take it away from the stage
					}
				} else if(_root.finDir == 'RIGHT'){//and so on for other directions
					if(this._x >= 550){
						_root.lives --;
						_root.money -= 5*this.enLevel;
						this.removeMovieClip();
					}
				} else if(_root.finDir == 'DOWN'){
					if(this._y >= 300){
						_root.lives --;
						_root.money -= 5*this.enLevel;
						this.removeMovieClip();
					}
				} else if(_root.startDir == 'LEFT'){
					if(this._x <= 0){
						_root.lives --;
						_root.money -= 5*this.enLevel;
						this.removeMovieClip();
					}
				}
 
				if(this.health <= 0){
					_root.enemiesLeft --;
					_root.money += 5*this.enLevel;
					this.removeMovieClip();
				}
			}
		}
		currentEnemy ++;//move on to the next enemy
		enemyTime = 0;//and reset the time
	}
}

There aren’t very many renovations that we’ve made, but they will make our code much more flexible. It allows us to create different enemy levels by setting the enLevel to be equal to the code that is placed into the enemy array. The enLevel in turn lets us dynamically change the amount of health the enemy has and the amount of money that it gives you when you kill it. Right now the health and money it gives you is 5 times the enemy level.

Now, we can make more levels with better enemies! You can customize your own levels, or use the ones I created by setting these values in the enemyArray:

enemyArray = [//defining the array
			[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],//1's will just represent an enemy to be created
			[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],//another row means another level
			[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],
			[100],
			[5,6,7,6,5,6,7,6,5,6,7,6,5,6,7,6,5,6,7,6,5,6,7,6,5,6,7,6,5],
			[250,250,250]
			  ];

Of course, I’d suggest creating your own levels, as mine aren’t what you would call the best. Anyways, this wraps up the second to last part of this tutorial. Join us next time when finish up this little game!

]]>
http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-6/feed/ 0
How to Create a Tower Defense Game in AS2 – Part 5 http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-5/ http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-5/#comments Sat, 25 Jul 2009 12:05:40 +0000 Mr Sun http://www.mrsunstudios.com/?p=1519 Welcome back to the 5th installment of this tutorial series. In this lesson, we’ll make some playable levels, along with a winning and losing situation. Let’s dig in, shall we?

Lets start off by opening up the main source file. Find where this code is:

enemyArray = [//defining the array
			[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],//1's will just represent an enemy to be created
			[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],//another row means another level
			[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
			  ];

Let’s review this code for a bit. Each of those arrays within that enemyArray represents a level. So, right now, we’re set up for 3 different levels, with an increasing amount of enemies in each level. Now that we’ve covered this, we can continue on to making it possible to advance levels.

In order to do this, we must first count the number of enemies we actually have on stage. This is actually very easy to do. Find the startGame() function (~line 45) that has no code in it, and add the following:

enemiesLeft = enemyArray[currentLvl-1].length;

Now, we have to decrease this number every time an enemy is destroyed. We can do this by adding one line of code to where we remove the Enemy from the stage in the makeEnemies() function. Add the following code (~line 346):

_root.enemiesLeft --;

Now, find the main _root.onEnterFrame() function (~line 287). There should only be one line of code in there right now. We’re going to add some. Add the following code to the bottom of it:

if(enemiesLeft==0){//if there are no more enemies left
	currentLvl ++;//continue to the next level
	currentEnemy = 0;//reset the amount of enemies there are
	startGame();//restart the game
}

Now, try testing out the game. Functionally, it’s working 100%. Practically, it’s not a great game. In order to make this game better, we’re going to have to show some information to the user while they’re playing, like the current level, the score, etc. This is exactly what we’re going to do now.

Now, try testing out the game. Functionally, it’s working 100%. Practically, it’s not a great game. In order to make this game better, we’re going to have to show some information to the user while they’re playing, like the current level, the score, etc. This is exactly what we’re going to do now.

Create four dynamic text boxes at the bottom left portion of the stage, each at 12 point font. Here’s an example of what yours should look like, with an example of what information we’re going to put into them later:

The Text Fields

Got that? Now, we just have to give each of these dynamic text fields an instance name. Label them accordingly:

  • txtLevel
  • txtMoney
  • txtLives
  • txtEnemiesLeft

Now, let’s dive into some code, shall we?

The first thing we need to do is actually define the money and the lives variables. Just add this code to the top:

var money:Number=100;//how much money the player has to spend on turrets
var lives:Number=20;//how many lives the player has

Okay, good stuff. Let’s first make these two variables mean something before we update the text. We first have to make it so the player loses lives so he/she can lose the game.

In order to do this, we must add the following code to the Enemy’s onEnterFrame() function (~line 353):

//checking what direction it goes when finishing the path
if(_root.finDir == 'UP'){//if it finishes at the top
	if(this._y <= -25){//if the y value is too high
		_root.lives --;//take away a life
		_root.money -= 5;//don't let the player gain any money
		this.removeMovieClip();//take it away from the stage
	}
} else if(_root.finDir == 'RIGHT'){//and so on for other directions
	if(this._x >= 550){
		_root.lives --;
		_root.money -= 5;
		this.removeMovieClip();
	}
} else if(_root.finDir == 'DOWN'){
	if(this._y >= 300){
		_root.lives --;
		_root.money -= 5;
		this.removeMovieClip();
	}
} else if(_root.startDir == 'LEFT'){
	if(this._x <= 0){
		_root.lives --;
		_root.money -= 5;
		this.removeMovieClip();
	}
}
if(this.health <= 0){
	_root.enemiesLeft --;
	_root.money += 5;
	this.removeMovieClip();
}

Note that we also are giving the player money for killing the enemies. Next, we’ll make each of the turrets cost a certain amount of money. I’m thinking $20 is a good price. Find the block’s onRelease function (~line 80). We have to wrap all of its contents with if(_root.money >= 20){money-=20;......}. This way, the final onRelease function will look like this:

_root['block'+i].onRelease = function(){
	if(_root.money >= 20){//if there's enough money
		_root.money -= 20;//spend it and make a turret
		//this function will run when the empty block is clicked on
 
		//change this guy's color back
		var newColor = new Color(this);
		newColor.setRGB(0x333333);
		//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
		_root.createEmptyMovieClip('t'+this._name,_root.getNextHighestDepth());
 
		//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].curveTo(0,25,12.5,25);
		_root['t'+this._name].curveTo(25,25,25,12.5);
		_root['t'+this._name].curveTo(25,0,12.5,0);
		_root['t'+this._name].curveTo(0,0,0,12.5);
		_root['t'+this._name].endFill();//end the fill so we can make a new one
 
		//creating the gun
		_root['t'+this._name].createEmptyMovieClip('gun',_root['t'+this._name].getNextHighestDepth());
		_root['t'+this._name].gun.beginFill(0xFFFFFF);
		_root['t'+this._name].gun.lineTo(-2,-2);
		_root['t'+this._name].gun.lineTo(2,-2);
		_root['t'+this._name].gun.lineTo(2,15);
		_root['t'+this._name].gun.lineTo(-2,15);
		_root['t'+this._name].gun.lineTo(-2,-2);
		_root['t'+this._name].gun.endFill();
		//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;
 
		_root['t'+this._name].angle = 0; //the angle that the turret is currently rotated at
		_root['t'+this._name].radiansToDegrees = 180/Math.PI;//this is needed for the rotation
		_root['t'+this._name].damage = 3;//how much damage this little baby can inflict
		_root['t'+this._name].range = 100;//how far away (in pixels) it can hit a target
		_root['t'+this._name].enTarget = null;//the current target that it's rotating towards
		_root['t'+this._name].cTime = 0;//how much time since a shot was fired by this turret
		_root['t'+this._name].reloadTime = 12;//how long it takes to fire another shot
		_root['t'+this._name].loaded = true;//whether or not this turret can shoot
 
		_root['t'+this._name].onEnterFrame = function(){
			//FINDING THE NEAREST ENEMY WITHIN RANGE
			this.distance = this.range;//let's define a variable which will be how far the nearest enemy is
			this.enTarget = null;//right now, we don't have a target to shoot at
			for(var i=_root.currentEnemy-1;i>=0;i--){//loop through the children in enemyHolder
				var cEnemy = _root.enemyHolder['enemy'+i];//define a movieclip that will hold the current child
				//this simple formula with get us the distance of the current enemy
				if(Math.sqrt(Math.pow(cEnemy._y - this._y, 2) + Math.pow(cEnemy._x - this._x, 2)) < this.distance){
					//if the selected enemy is close enough, then set it as the target
					this.enTarget = cEnemy;
				}
			}
			//ROTATING TOWARDS TARGET
			if(this.enTarget != null){//if we have a defined target
				//turn this baby towards it
				this.gun._rotation = Math.atan2((this.enTarget._y-this._y), this.enTarget._x-this._x)/Math.PI*180-90;
				if(this.loaded){//if the turret is able to shoot
					this.loaded = false;//then make in unable to do it for a bit
					//create a bullet
					_root.createEmptyMovieClip('b'+this._name,_root.getNextHighestDepth());
					//draw the bullet
					_root['b'+this._name].beginFill(0xFFFFFF);
					_root['b'+this._name].lineTo(0,0);
					_root['b'+this._name].lineTo(0,3);
					_root['b'+this._name].lineTo(3,3);
					_root['b'+this._name].lineTo(3,0);
					_root['b'+this._name].endFill();
					//set the bullet's coordinates
					_root['b'+this._name]._x = this._x+12.5;
					_root['b'+this._name]._y = this._y+12.5;
					//set the bullet's target and damage
					_root['b'+this._name].target = this.enTarget;
					_root['b'+this._name].damage = this.damage;
 
					//add some functions to this bullet
					_root['b'+this._name].onEnterFrame = function(){
						this.maxSpeed=8;
						this.yDist=this.target._y+12.5 - this._y;//how far this guy is from the enemy (x)
						this.xDist=this.target._x+12.5 - this._x;//how far it is from the enemy (y)
						this.angle=Math.atan2(this.yDist,this.xDist);//the angle that it must move
						this.ySpeed=Math.sin(this.angle) * this.maxSpeed;//calculate how much it should move the enemy vertically
						this.xSpeed=Math.cos(this.angle) * this.maxSpeed;//calculate how much it should move the enemy horizontally
						//move the bullet towards the enemy
						this._x+= this.xSpeed;
						this._y+= this.ySpeed;
						//check if it is close to the enemy
						if(this._x+this.maxSpeed*2>=this.target._x && this._x-this.maxSpeed*2<=this.target._x
						&& this._y+this.maxSpeed*2>=this.target._y && this._y-this.maxSpeed*2<=this.target._y){
							this.target.health -= this.damage;//make the enemy lose health
							this.removeMovieClip();//remove this sucker
						}
					}
				}
			}
			//LOADING THE TURRET
			if(!this.loaded){//if it isn't loaded
				this.cTime ++;//then continue the time
				if(this.cTime == this.reloadTime){//if time has elapsed for long enough
					this.loaded = true;//load the turret
					this.cTime = 0;//and reset the time
				}
			}
		}
}

Now, we can update these text fields. Once again, find the _root.onEnterFrame() function (~line 300). Add the following code which will update all the text fields with the needed information:

//Updating the text fields
txtLevel.text = 'Level '+currentLvl;
txtMoney.text = '$'+money;
txtLives.text = 'Lives: '+lives;
txtEnemiesLeft.text = 'Enemies Left:  '+enemiesLeft;

Now, let’s create some winning and losing scenarios for the player. When the player has beaten all of the levels, then a win screen should show up. The same thing should happen with a lose screen when the player loses all of his/her lives. Let’s create these two frames, shall we?

Before, we create the frames, we have to add a layer called “labels”. This will just let us easily navigate to the required frames. Next, create a frame labeled “win” and add whatever message you want to inform the player that they’ve won. Do the same with a “lose” frame.

Now, we have to make it possible for the player to restart the game. We’ll let them do it by clicking anywhere on the screen. Copy and paste this code to both the “win” frame and the “lose” frame:

timeElapsed = 0;//how many frames have elapsed since this screen has been shown
 
_root.onEnterFrame = function(){
	timeElapsed ++;//increase the amount of frames that have elapsed
	if(timeElapsed == 120){//if 5 seconds (@24fps) have elapsed
		gotoAndStop(1);//go back to restart the game
	}
}

All right, the next thing we have to do is navigate to the desired frame when the player wins or loses. Go back to frame 1 and find the _root.onEnterFrame() function (~line 293). Add the following code to the very beginning of it:

//if there aren't any levels left
	if(currentLvl > enemyArray.length){
		gameOver=true;//set the game to be over
 
		//reset all the stats
		currentLvl = 1;
		currentEnemy = 0;
		enemyTime = 0;
		enemyLimit = 12;
		enemiesLeft = 0;
 
		roadHolder.removeMovieClip();//remove the pieces of road
		enemyHolder.removeMovieClip();//remove the enemies
		//remove all of the blocks
		for(i=0;i<=0){//if the user runs out of lives
		gameOver=true;//set the game to be over
 
		//reset all the stats
		currentLvl = 1;
		currentEnemy = 0;
		enemyTime = 0;
		enemyLimit = 12;
		enemiesLeft = 0;
 
		roadHolder.removeMovieClip();//remove the pieces of road
		enemyHolder.removeMovieClip();//remove the enemies
		//remove all of the blocks
		for(i=0;i

Sweet. This concludes this installment of the tutorial series. Join us next time when we expand on the game!

]]>
http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-5/feed/ 0
How to Create a Tower Defense Game in AS2 – Part 4 http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-4/ http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-4/#comments Sat, 25 Jul 2009 12:04:22 +0000 Mr Sun http://www.mrsunstudios.com/?p=1509 Well, it’s now time to let the enemies we just created be destroyed. Let’s dig in, shall we?

First, we’ll define a single health variable for the Enemy. Find this code in the makeEnemies() function (~ Line 236):

//add a few variables to the enemy
enemyHolder['enemy'+currentEnemy].maxSpeed = 3;//how fast it can possibly go
enemyHolder['enemy'+currentEnemy].xSpeed = 0;
enemyHolder['enemy'+currentEnemy].ySpeed = 0;

Just add this code:

enemyHolder['enemy'+currentEnemy].health = 5;

Now, we’re going to have to add some variables to the turrets. In the makeRoad() function, find the onRelease function of the Empty Block (~ Line 77). Add this code to the bottom of that function (~ Line 116).

_root['t'+this._name].angle = 0; //the angle that the turret is currently rotated at
_root['t'+this._name].radiansToDegrees = 180/Math.PI;//this is needed for the rotation
_root['t'+this._name].damage = 3;//how much damage this little baby can inflict
_root['t'+this._name].range = 100;//how far away (in pixels) it can hit a target
_root['t'+this._name].enTarget = null;//the current target that it's rotating towards
_root['t'+this._name].cTime = 0;//how much time since a shot was fired by this turret
_root['t'+this._name].reloadTime = 12;//how long it takes to fire another shot
_root['t'+this._name].loaded = true;//whether or not this turret can shoot

Those are a lot of variables, aren’t they? Well, this is a pretty complex task, so we’re going to need all of them. So, brace yourself, for we are now going to jump into some code. Add the following after the code you just added above:

_root['t'+this._name].onEnterFrame = function(){
	//FINDING THE NEAREST ENEMY WITHIN RANGE
	this.distance = this.range;//let's define a variable which will be how far the nearest enemy is
	this.enTarget = null;//right now, we don't have a target to shoot at
	for(var i=_root.currentEnemy-1;i>=0;i--){//loop through the children in enemyHolder
		var cEnemy = _root.enemyHolder['enemy'+i];//define a movieclip that will hold the current child
		//this simple formula with get us the distance of the current enemy
		if(Math.sqrt(Math.pow(cEnemy._y - this._y, 2) + Math.pow(cEnemy._x - this._x, 2)) < this.distance){
			//if the selected enemy is close enough, then set it as the target
			this.enTarget = cEnemy;
		}
	}
	//ROTATING TOWARDS TARGET
	if(this.enTarget != null){//if we have a defined target
		//turn this baby towards it
		this.gun._rotation = Math.atan2((this.enTarget._y-this._y), this.enTarget._x-this._x)/Math.PI*180-90;
		if(this.loaded){//if the turret is able to shoot
			//subtract the enemy's health
			this.enTarget.health -= this.damage;
			this.loaded = false;//then make in unable to do it for a bit
			//create a bullet
			_root.createEmptyMovieClip('b'+this._name,_root.getNextHighestDepth());
			//draw the bullet
			_root['b'+this._name].beginFill(0xFFFFFF);
			_root['b'+this._name].lineTo(0,0);
			_root['b'+this._name].lineTo(0,3);
			_root['b'+this._name].lineTo(3,3);
			_root['b'+this._name].lineTo(3,0);
			_root['b'+this._name].endFill();
			//set the bullet's coordinates
			_root['b'+this._name]._x = this._x+12.5;
			_root['b'+this._name]._y = this._y+12.5;
			//set the bullet's target and damage
			_root['b'+this._name].target = this.enTarget;
 
			//add some functions to this bullet
			_root['b'+this._name].onEnterFrame = function(){
				this.maxSpeed=4;
				this.yDist=this.target._y+12.5 - this._y;//how far this guy is from the enemy (x)
				this.xDist=this.target._x+12.5 - this._x;//how far it is from the enemy (y)
				this.angle=Math.atan2(this.yDist,this.xDist);//the angle that it must move
				this.ySpeed=Math.sin(this.angle) * this.maxSpeed;//calculate how much it should move the enemy vertically
				this.xSpeed=Math.cos(this.angle) * this.maxSpeed;//calculate how much it should move the enemy horizontally
				//move the bullet towards the enemy
				this._x+= this.xSpeed;
				this._y+= this.ySpeed;
				//check if it is close to the enemy
				if(this._x+this.maxSpeed*2>=this.target._x && this._x-this.maxSpeed*2<=this.target._x
				&& this._y+this.maxSpeed*2>=this.target._y && this._y-this.maxSpeed*2<=this.target._y){
					this.target.health -= this.damage;//make the enemy lose health
					this.removeMovieClip();//remove this sucker
				}
			}
		}
	}
	//LOADING THE TURRET
	if(!this.loaded){//if it isn't loaded
		this.cTime ++;//then continue the time
		if(this.cTime == this.reloadTime){//if time has elapsed for long enough
			this.loaded = true;//load the turret
			this.cTime = 0;//and reset the time
		}
	}
}

Now, if you test out the game and create some turrets, they should start shooting at those darn enemies! Next, we have to make it so the enemy dies when shot. This will be pretty easy to do. Find the code where we added the onEnterFrame() code to the enemy and made it move (~line 342). Just add this little tidbit of code:

if(this.health <= 0){
	this.removeMovieClip();
}

Pretty hot stuff, ain’t it? Well, this concludes the fourth installment of this tutorial. Join us next time when we make levels and have winning and losing scenarios!

]]>
http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-4/feed/ 0
How to Create a Tower Defense Game in AS2 – Part 3 http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-3/ http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-3/#comments Sat, 25 Jul 2009 12:03:10 +0000 Mr Sun http://www.mrsunstudios.com/?p=1498 Welcome back. In this part of the tutorial, we are going to add enemies to the field and we’re going to program them to move through the paths.

Let’s begin by adding the enemy to the stage. Like the other symbols, we’re going to do it by creating an empty MovieClip and drawing the shape into it. In order to do this, however, we must first define some variables. Do this at the top of the code:

var currentEnemy:Number = 0;//the current enemy that we're creating from the array
var enemyTime:Number = 0;//how many frames have elapsed since the last enemy was created
var enemyLimit:Number = 12;//how many frames are allowed before another enemy is created
var enemyArray:Array = new Array();//this array will tell the function when to create an enemy
var enemiesLeft:Number;//how many enemies are left on the field
enemyArray = [//defining the array
			[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],//1's will just represent an enemy to be created
			[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],//another row means another level
			[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
			  ];

I’ve extensively commented on what each variable does. Next, we need to create an onEnterFrame() function with a few actions, along with a few other stuff. Program this into the bottom of the code:

createEmptyMovieClip('enemyHolder',_root.getNextHighestDepth());//create a movieclip that will hold the enemy
 
_root.onEnterFrame = function(){
	makeEnemies();//we'll just make some enemies
}
 
function makeEnemies():Void{//this function will add enemies to the field
	if(enemyTime < enemyLimit){//if it isn't time to make them yet
		enemyTime ++;//then keep on waiting
	} else {//otherwise
		var theCode:Number = enemyArray[currentLvl-1][currentEnemy];//get the code from the array
		if(theCode == 1){//if it's set as 1
			//then create a new enemy and add it to the enemy holder
			enemyHolder.createEmptyMovieClip('enemy'+currentEnemy,enemyHolder.getNextHighestDepth());
			//now we're going to draw the enemy. It'll just be a tiny red circle
			enemyHolder['enemy'+currentEnemy].beginFill(0xFF0000);//coloring them red gray
			enemyHolder['enemy'+currentEnemy].moveTo(0, 2.5);//move the entire shape a certain way
			//create 4 curves so that it'll look like a circle
			enemyHolder['enemy'+currentEnemy].curveTo(0,10,5,10);
			enemyHolder['enemy'+currentEnemy].curveTo(10,10,10,5);
			enemyHolder['enemy'+currentEnemy].curveTo(10,0,5,0);
			enemyHolder['enemy'+currentEnemy].curveTo(0,0,0,5);
			enemyHolder['enemy'+currentEnemy].endFill();//end the fill
		}
		currentEnemy ++;//move on to the next enemy
		enemyTime = 0;//and reset the time
	}
}

Now, if you test out the game, a red dot should appear on the top left corner of the screen. But, this isn’t what we want for our game, is it? In order to place the enemy so that it’s right next to the start point, we’re going to have to add some code. Remember the variables startDir and finDir that we created all that time ago? If you don’t here’s what it should look like at around line 11:

var startDir:String;//the direction the enemies go when they enter
var finDir:String;//the direction the enemies go when they exit
var startCoord:Number;//the coordinates of the beginning of the road

Well, we’re going to use these variables. Find in the makeRoad() function where we create add in the SPECIAL DIRECTIONAL ROAD PIECE (around line 129). Add the following code to the bottom of that if statement:

if(lvlArray[i] == 'START'){//if this is a start block
	//then define the startDir and StartCoord based on it's coordinates
	if(roadHolder['block'+i]._x == 0){
		_root.startDir = 'RIGHT';
		_root.startCoord = roadHolder['block'+i]._y;
	} else if (roadHolder['block'+i]._y == 0){
		_root.startDir = 'DOWN';
		_root.startCoord = roadHolder['block'+i]._x;
	} else if (roadHolder['block'+i]._x == 525){
		_root.startDir = 'LEFT';
		_root.startCoord = roadHolder['block'+i]._y;
	} else if (roadHolder['block'+i]._y == 275){
		_root.startDir = 'UP';
		_root.startCoord = roadHolder['block'+i]._x;
	} else {
		//this level won't work if not any of these values
	}
} else if (lvlArray[i] == 'FINISH'){//if this is a finish block
	//then define the finDir based on it's coordinates
	if(roadHolder['block'+i]._x == 0){
		_root.finDir = 'LEFT';
	} else if (roadHolder['block'+i]._y == 0){
		_root.finDir = 'UP';
	} else if (roadHolder['block'+i]._x == 525){
		_root.finDir = 'RIGHT';
	} else if (roadHolder['block'+i]._y == 275){
		_root.finDir = 'DOWN';
	} else {
		//this level won't work if not any of these values
	}
}

Next, we have to take the variables we just defined in this code and make the enemy use them. We also have to make the enemy move along the path. Go back to the makeEnemies() function and add the following code in the if(theCode == 1){ statement:

//add a few variables to the enemy
enemyHolder['enemy'+currentEnemy].maxSpeed = 3;//how fast it can possibly go
enemyHolder['enemy'+currentEnemy].xSpeed = 0;
enemyHolder['enemy'+currentEnemy].ySpeed = 0;
//checking what the start direction is
if(_root.startDir == 'UP'){//if it's starting up
	enemyHolder['enemy'+currentEnemy]._y = 300;//set the y value off the field
	enemyHolder['enemy'+currentEnemy]._x = _root.startCoord;//make the x value where it should be
	enemyHolder['enemy'+currentEnemy].xSpeed = 0;//make it not move horizontally
	enemyHolder['enemy'+currentEnemy].ySpeed = -enemyHolder['enemy'+currentEnemy].maxSpeed;//make it move upwards
} else if(_root.startDir == 'RIGHT'){//and so on for other directions
	enemyHolder['enemy'+currentEnemy]._x = -25;
	enemyHolder['enemy'+currentEnemy]._y = _root.startCoord;
	enemyHolder['enemy'+currentEnemy].xSpeed = enemyHolder['enemy'+currentEnemy].maxSpeed;
	enemyHolder['enemy'+currentEnemy].ySpeed = 0;
} else if(_root.startDir == 'DOWN'){
	enemyHolder['enemy'+currentEnemy]._y = -25;
	enemyHolder['enemy'+currentEnemy]._x = _root.startCoord;
	enemyHolder['enemy'+currentEnemy].xSpeed = 0;
	enemyHolder['enemy'+currentEnemy].ySpeed = enemyHolder['enemy'+currentEnemy].maxSpeed;
} else if(_root.startDir == 'LEFT'){
	enemyHolder['enemy'+currentEnemy]._x = 550;
	enemyHolder['enemy'+currentEnemy]._y = _root.startCoord;
	enemyHolder['enemy'+currentEnemy].xSpeed = -enemyHolder['enemy'+currentEnemy].maxSpeed;
	enemyHolder['enemy'+currentEnemy].ySpeed = 0;
}
 
enemyHolder['enemy'+currentEnemy]._x += 5;//fixing the x value
enemyHolder['enemy'+currentEnemy]._y += 5;//fixing up the y value
 
enemyHolder['enemy'+currentEnemy].onEnterFrame = function(){//give it some functions
	this._x += this.xSpeed;
	this._y += this.ySpeed;
}

The final thing we have to do in this lesson is make the enemy turn when it should turn. To do this, we must go back to the Directional Block. We’re going to use the directional block to access all of the enemies coordinates. If the coordinates are close enough to the block, then it will make the enemy change direction. Find the if(String(lvlArray[i])){ statement in the makeRoad() function. Add this code to the end of it:

roadHolder['block'+i].directType = lvlArray[i];//accessing the type of block it is
roadHolder['block'+i].onEnterFrame = function(){//add some functions to this block
	//then it'll act as a directioning block
	for(i = 0;i<_root.enemyArray[currentLvl-1].length;i++){//create a loop
		//if the enemy's coordinates are too close to this block
		if(this._x >= _root.enemyHolder['enemy'+i]._x - _root.enemyHolder['enemy'+i]._width*.5
		&& this._x +6<= _root.enemyHolder['enemy'+i]._x + _root.enemyHolder['enemy'+i]._width*.5
		&& this._y >= _root.enemyHolder['enemy'+i]._y - _root.enemyHolder['enemy'+i]._height*.5
		&& this._y +6<= _root.enemyHolder['enemy'+i]._y + _root.enemyHolder['enemy'+i]._height*.5){
			//then move the enemy's direction based on what direction this block points to
			if(this.directType == 'UP'){
				_root.enemyHolder['enemy'+i].xSpeed = 0;
				_root.enemyHolder['enemy'+i].ySpeed = -_root.enemyHolder['enemy'+i].maxSpeed;
			} else if(this.directType == 'RIGHT'){
				_root.enemyHolder['enemy'+i].xSpeed = _root.enemyHolder['enemy'+i].maxSpeed;
				_root.enemyHolder['enemy'+i].ySpeed = 0;
			} else if(this.directType == 'DOWN'){
				_root.enemyHolder['enemy'+i].xSpeed = 0;
				_root.enemyHolder['enemy'+i].ySpeed = _root.enemyHolder['enemy'+i].maxSpeed;
			} else if(this.directType == 'LEFT'){
				_root.enemyHolder['enemy'+i].xSpeed = _root.enemyHolder['enemy'+i].maxSpeed;
				_root.enemyHolder['enemy'+i].ySpeed = 0;
			}
		}
	}
}
]]>
http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-3/feed/ 0
How to Create a Tower Defense Game in AS2 – Part 2 http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-2/ http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-2/#comments Sat, 25 Jul 2009 12:02:57 +0000 Mr Sun http://www.mrsunstudios.com/?p=1491 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);
	newColor.setRGB(0x333333);
	//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
	_root.createEmptyMovieClip('t'+this._name,_root.getNextHighestDepth());
 
	//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].curveTo(0,25,12.5,25);
	_root['t'+this._name].curveTo(25,25,25,12.5);
	_root['t'+this._name].curveTo(25,0,12.5,0);
	_root['t'+this._name].curveTo(0,0,0,12.5);
	_root['t'+this._name].endFill();//end the fill so we can make a new one
 
	//creating the gun
	_root['t'+this._name].createEmptyMovieClip('gun',_root['t'+this._name].getNextHighestDepth());
	_root['t'+this._name].gun.beginFill(0xFFFFFF);
	_root['t'+this._name].gun.lineTo(-2,-2);
	_root['t'+this._name].gun.lineTo(2,-2);
	_root['t'+this._name].gun.lineTo(2,15);
	_root['t'+this._name].gun.lineTo(-2,15);
	_root['t'+this._name].gun.lineTo(-2,-2);
	_root['t'+this._name].gun.endFill();
	//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!

]]>
http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-2/feed/ 0
How to Create a Tower Defense Game in AS2 – Part 1 http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-1/ http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-1/#comments Sat, 25 Jul 2009 12:01:32 +0000 Mr Sun http://www.mrsunstudios.com/?p=1481 The tower defense genre is one that has become extremely popular over the years. Although they can become quite complicated to develop, they are almost always very fun to play. I am here to walk you through the creation of one of these games. Let us begin, shall we?

In this section of the tutorial, we’re going to set up the roads and stuff onto the stage. However, the first thing we need to do is create a blank flash document with a black background with the frames per second set at 24.

Now, we can dive into some code. Let’s first create some code that will lay down the track for the enemies to go through. Create a new layer called “actions” and add the following code to it:

stop();
 
//setting vars to step in for turns and special blocks
var S:String = 'START';
var F:String = 'FINISH';
var U:String = 'UP';
var R:String = 'RIGHT';
var D:String = 'DOWN';
var L:String = 'LEFT';
 
var startDir:String;//the direction the enemies go when they enter
var finDir:String;//the direction the enemies go when they exit
var startCoord:Number;//the coordinates of the beginning of the road
var lvlArray:Array = new Array();//this array will hold the formatting of the roads
 
lvlArray = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
			0,0,0,0,R,1,1,D,0,0,R,1,1,D,0,0,R,1,1,D,0,0,
			0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,
			0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,
			S,D,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,R,1,F,
			0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,
			0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,
			0,R,1,1,U,0,0,R,1,1,U,0,0,R,1,1,U,0,0,0,0,0,
			0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
			0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
			];
 
//the names of these variables explain what they do
var currentLvl:Number = 1;
var gameOver:Boolean = false;
 
function startGame():Void{//we'll run this function every time a new level begins
	//right now we don't have any code
}
 
_root.createEmptyMovieClip('roadHolder',_root.getNextHighestDepth());//add a MovieClip to hold the road
function makeRoad():Void{
	var row:Number = 0;//the current row we're working on
	var block;//this will act as the block that we're placing down
	for(i=0;i

That’s a lot of code, ain’t it? Hopefully, I’ve given you enough instructions in the comments. If you test out our game, a nice little path should be shown which the enemies will travel through, along with some blank gray boxes where we’ll be able to place some turrets.

Before I end this part of the tutorial, I want to give these empty boxes some rollOver and rollOut effects. Find where I added the comment saying /////*****EMPTY BLOCK*****///// (lines 44-54). Add this code to the bottom of that section of the if statement:

_root['block'+i].onRollOver = function(){
	//Change the color to green
	var newColor = new Color(this);
	newColor.setRGB(0x006600);
}
_root['block'+i].onRollOut = function(){
	//Change this color back to gray
	var newColor = new Color(this);
	newColor.setRGB(0x333333);
}
]]>
http://www.flashgametuts.com/tutorials/advanced/how-to-create-a-tower-defense-game-in-as2-part-1/feed/ 1
How to Create a Brick Breaker Game in AS2 – Part 6 http://www.flashgametuts.com/tutorials/as2/how-to-create-a-brick-breaker-game-in-as2-part-6/ http://www.flashgametuts.com/tutorials/as2/how-to-create-a-brick-breaker-game-in-as2-part-6/#comments Thu, 23 Jul 2009 12:05:47 +0000 Mr Sun http://www.mrsunstudios.com/?p=1073 Well, we’re almost done with our game, now we just have to add some finishing touches. I won’t make a menu system like you usually should in a game before releasing it. But, this is just a tutorial, and hopefully you’ve learned something. You probably already know how to make a menu anyway. Also, I’m not going to teach you how to do some of the things that we need because hopefully you can do it yourself. If you can’t , there’s always the source file at the bottom.

Now, where were we? Oh yes. I realized that the last lesson, we were supposed to make more levels. I taught a lot of stuff, but I forgot to make more levels for you! I apologize. Anyway, here’s an example of a 5 level game (Put it on the first frame).

//The array code for lvl 1
//All of the later levels add one more row of bricks
var lvl1Code:Array = new Array(1,1,1,1,1,1,1);
var lvl2Code:Array = new Array(1,1,1,1,1,1,1,1,1,1,1,1,1,1);
var lvl3Code:Array = new Array(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);
var lvl4Code:Array = new Array(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);
var lvl5Code:Array = new Array(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);
//The array that contains all of the level codes
var lvlArray:Array = new Array(lvl1Code, lvl2Code, lvl3Code, lvl4Code, lvl5Code);

It’ll be a pretty straightforward game. Next, I think the gamer needs to know that he has to click the screen to start, and not think the the game is frozen or something. So, just add a dynamic textfield to the middle of the stage. Give it an instance game of txtStart, and make sure it isn’t selectable.
Make sure that these properties are what you have

Next, add this code at the end of the frame.

//setting the text's word
txtStart.text = "Click To Begin";

You can make the text different, but don’t be too mean. Next, we have to remove the text, which we can do in the mcBg’s onRelease() function. We aren’t going to remove the text field itself because we need it again for every level.

//removing the "Click to Start" Text
txtStart.text = '';

Now, we have to reset it every level. I’m not going to tell you how to do it. I hope you’ve learned enough to be able to.

Now, we can make the scoring happen. 10 points should be awarded to the player for destroying one brick. I’ll leave it to you to find out how to do this.

The next thing we have to do is display the current level, the score, and how many lives the user has. This will be pretty simple as well, so I won’t really go into details about how to do it. Just create a dynamic text field and update it in the onEnterFrame() function. Pretty easy, eh?

]]>
http://www.flashgametuts.com/tutorials/as2/how-to-create-a-brick-breaker-game-in-as2-part-6/feed/ 0
How to Create a Brick Breaker Game in AS2 – Part 5 http://www.flashgametuts.com/tutorials/as2/how-to-create-a-brick-breaker-game-in-as2-part-5/ http://www.flashgametuts.com/tutorials/as2/how-to-create-a-brick-breaker-game-in-as2-part-5/#comments Thu, 23 Jul 2009 12:04:46 +0000 Mr Sun http://www.mrsunstudios.com/?p=1071 Now that we’ve got the basic gameplay down, we can create some levels. Because we’re making only a simple game, we aren’t going to make that many. But before we even start making multiple levels, we have to make it possible to win or lose a level. This will be pretty easy.

We’re first going make it possible to beat the level. In order for this to happen, we have to track how many bricks are on the stage. Just define the following variable at the top of the code.

var brickAmt:Number = 0;

Now, we have to increment this number every time a brick is placed onto the stage. Type in this code into the makeLvl() function where we actually create the brick:

//incrementing how many bricks are on the stage
_root.brickAmt ++;

Next, we have to decrement the number every time a brick is destroyed. Just type in this code in the hitTest if statement:

//decrementing how many bricks are on the stage
_root.brickAmt --;

That was pretty easy, right? Now, we have to add some code that will check if the value of bricks is 0.
You can do so in the onEnterFrame() function:

//checking if the bricks are all gone
if(brickAmt == 0){
	//reset the level by increasing the level
	currentLvl ++;
	//and re-running makeLvl
	makeLvl();
}

When this code runs, nothing will happen when you break all of the bricks because we haven’t defined more levels. But, there is one thing I want to fix before doing that. The game starts automatically, even if the player isn’t ready. So, we want to start the level only when the user first clicks on the screen. This is actually easier than you might think. The first thing we need to do is create a black rectangle that covers the entire stage. Then, we have to turn it into a MovieClip. Name it mcBg, Export it for ActionScript, and give it an instance name of mcBg. Then, add the following to the bottom of the code:

mcBg.onRelease = function(){ //creating a function that will run when bg is clicked
	//move the bg out of range so it isn't bothersome
	mcBg._x = 800;
}

Now, we have to add the entire onEnterFrame() function to this, so it looks like this:

mcBg.onRelease = function(){ //creating a function that will run when bg is clicked
	//move the bg out of range so it isn't bothersome
	mcBg._x = 800;
	_root.onEnterFrame = function(){ //this function will run during every single frame
		//The paddle follows the mouse
		mcPaddle._x = _xmouse - mcPaddle._width*.5;
 
		//If the mouse goes off too far to the left
		if(_xmouse < mcPaddle._width / 2){
			//Keep the paddle on stage
			mcPaddle._x = 0;
		}
		//If the mouse goes off too far to the right
		if(_xmouse > Stage.width - mcPaddle._width / 2){
			//Keep the paddle on stage
			mcPaddle._x = Stage.width - mcPaddle._width;
		}
 
		//MOVING THE BALL
		mcBall._x += ballXSpeed;
		mcBall._y += ballYSpeed;
		//Bouncing the ball off of the walls
		if(mcBall._x >= Stage.width-mcBall._width){
			//if the ball hits the right side
			//of the screen, then bounce off
			ballXSpeed *= -1;
		}
		if(mcBall._x <= 0){
			//if the ball hits the left side
			//of the screen, then bounce off
			ballXSpeed *= -1;
		}
		if(mcBall._y >= Stage.height-mcBall._height){
			//if the ball hits the bottom
			//then bounce up
			ballYSpeed *= -1;
		}
		if(mcBall._y <= 0){
			//if the ball hits the top
			//then bounce down
			ballYSpeed *= -1;
		}
 
		if(mcBall.hitTest(mcPaddle)){
			//calculate the ball angle if ball hits paddle
			calcBallAngle();
		}
 
		//checking if the bricks are all gone
		if(brickAmt == 0){
			//reset the level by increasing the level
			currentLvl ++;
			//and re-running makeLvl
			makeLvl();
		}
	}
}

This is pretty solid code, but it does have some issues. One problem we have to fix is that the level is immediately made after you break all of the bricks, without resetting the ball’s position or anything (it may not be like that on yours, but trust me, I’ve tested it). Just paste in this code where we level up in the onEnterFrame() function:

//checking if the bricks are all gone
if(brickAmt == 0){
	//reset the level by increasing the level
	currentLvl ++;
	//and re-running makeLvl
	makeLvl();
	//reset the ball's position
	mcBall._x = 175;
	mcBall._y = 250;
	//then move the background back
	mcBg._x = 0;
	//and remove all of these events
	_root.onEnterFrame = null;
}

Now that we can beat a level, we now have to lose a level. We’re going to have to add a lives variable at the top first. We’re also going add a variable that defines if the game is over.

//how many lives you got
var lives:Number = 3;
//if the game is over
var gameOver:Boolean = false;

Then, we have to subtract a life every time the ball hits the floor and do other stuff when the lives are all gone.

if(mcBall._y >= Stage.height-mcBall._height){
	//if the ball hits the bottom
	//then bounce up and lose a life
	ballYSpeed *= -1;
	lives --;
	//if there aren't any lives left
	if(lives <= 0){
		//the game is over now
		gameOver = true;
		//go to a lose frame
		gotoAndStop('lose');
	}
}

Of course, now we have to create a frame called “lose”. I’m just going to make a frame that that has the text, “YOU LOSE”. Make sure to give your frame a label of “lose”, or the code won’t work.

Also, we have to remove the bricks from the stage, because they were added dynamically and won’t go away if you just change a frame. So, type the following code into the brick’s onEnterFrame function.

if(_root.gameOver){//if game's over
	this.removeMovieClip();//then remove this from stage
}

Now, we have to make the player be able to restart the game after losing. This will be easy. Just add the mcBg back to the stage that will reset the game if the stage is clicked. This code should be in the “lose” frame:

mcBg._x = 0; //putting the mcBg back
mcBg.onRelease = function(){
	gotoAndPlay(1);//restart the game
}

Well, that’s all for this lesson. The next one will be the final one, where we add some finishing touches, and fix some bugs.

]]>
http://www.flashgametuts.com/tutorials/as2/how-to-create-a-brick-breaker-game-in-as2-part-5/feed/ 0
How to Create a Brick Breaker Game in AS2 – Part 4 http://www.flashgametuts.com/tutorials/as2/how-to-create-a-brick-breaker-game-in-as2-part-4/ http://www.flashgametuts.com/tutorials/as2/how-to-create-a-brick-breaker-game-in-as2-part-4/#comments Thu, 23 Jul 2009 12:03:45 +0000 Mr Sun http://www.mrsunstudios.com/?p=1069 Now that we’ve actually made the bricks, we can now break them with our ball… Anyway, this will be pretty easy to accomplish. All you have to do is change this code in the makeLvl() function:

		if(lvlArray[currentLvl-1][i] == 1){
			//creating a variable which holds the brick instance
			_root.attachMovie('mcBrick', 'brick'+i,_root.getNextHighestDepth());
			//setting the brick's coordinates via the i variable and brickRow
			_root['brick'+i]._x = 15+(i-brickRow*7)*75;
			_root['brick'+i]._y = 10+brickRow*20;
			//checks if the current brick needs a new row
			for(var c:Number = 1;c<=10;c++){
				if(i == c*7-1){
					brickRow ++;
				}
			}
		}

to this:

		if(lvlArray[currentLvl-1][i] == 1){
			//creating a variable which holds the brick instance
			_root.attachMovie('mcBrick', 'brick'+i,_root.getNextHighestDepth());
			//setting the brick's coordinates via the i variable and brickRow
			_root['brick'+i]._x = 15+(i-brickRow*7)*75;
			_root['brick'+i]._y = 10+brickRow*20;
			//giving this brick some actions
			_root['brick'+i].onEnterFrame = function(){
				if(this.hitTest(_root.mcBall)){//if this touches the ball
					//then destroy this mofugger!
					this.removeMovieClip();
					//and make the ball bounce away
					ballYSpeed *= -1;
				}
			}
			//checks if the current brick needs a new row
			for(var c:Number = 1;c<=10;c++){
				if(i == c*7-1){
					brickRow ++;
				}
			}
		}

That was pretty easy, wasn’t it? Definitely much easier than what had to be done in AS3. Well, since we have time, I’m going to post here what your code should look like at this time:

Frame 1:

//Current level player is on
var currentLvl:Number = 1;
//The array code for lvl 1
var lvl1Code:Array = new Array(1,1,1,1,1,1,1);
//The array that contains all of the level codes
var lvlArray:Array = new Array(lvl1Code);

Frame 2:

stop();
//These variables are needed for moving the ball
var ballXSpeed:Number = 10; //X Speed of the Ball
var ballYSpeed:Number = 10; //Y Speed of the Ball
 
onEnterFrame = function(){ //this function will run during every single frame
	//The paddle follows the mouse
	mcPaddle._x = _xmouse - mcPaddle._width*.5;
 
	//If the mouse goes off too far to the left
	if(_xmouse < mcPaddle._width / 2){
		//Keep the paddle on stage
		mcPaddle._x = 0;
	}
	//If the mouse goes off too far to the right
	if(_xmouse > Stage.width - mcPaddle._width / 2){
		//Keep the paddle on stage
		mcPaddle._x = Stage.width - mcPaddle._width;
	}
 
	//MOVING THE BALL
	mcBall._x += ballXSpeed;
	mcBall._y += ballYSpeed;
	//Bouncing the ball off of the walls
	if(mcBall._x >= Stage.width-mcBall._width){
		//if the ball hits the right side
		//of the screen, then bounce off
		ballXSpeed *= -1;
	}
	if(mcBall._x <= 0){
		//if the ball hits the left side
		//of the screen, then bounce off
		ballXSpeed *= -1;
	}
	if(mcBall._y >= Stage.height-mcBall._height){
		//if the ball hits the bottom
		//then bounce up
		ballYSpeed *= -1;
	}
	if(mcBall._y <= 0){
		//if the ball hits the top
		//then bounce down
		ballYSpeed *= -1;
	}
 
 
 
	if(mcBall.hitTest(mcPaddle)){
		//calculate the ball angle if ball hits paddle
		calcBallAngle();
	}
}
 
function calcBallAngle():Void{
	//ballPosition is the position of the ball is on the paddle
	var ballPosition:Number = mcBall._x - mcPaddle._x;
	//hitPercent converts ballPosition into a percent
	//All the way to the left is -.5
	//All the way to the right is .5
	//The center is 0
	var hitPercent:Number = (ballPosition / (mcPaddle._width - mcBall._width)) - .5;
	//Gets the hitPercent and makes it a larger number so the
	//ball actually bounces
	ballXSpeed = hitPercent * 10;
	//Making the ball bounce back up
	ballYSpeed *= -1;
}
 
function makeLvl():Void{ //Places bricks onto Level
	//finding the array length of the lvl code
	//The index has to be currentLvl-1 because:
	//array indexes start on 0 and our lvl starts at 1
	//our level will always be 1 higher than the actual index of the array
	var arrayLength:Number = _root.lvlArray[currentLvl-1].length;
	//the current row of bricks we are creating
	var brickRow:Number = 0;
	//Now, creating a loop which places the bricks onto the stage
	for(var i:Number = 0;i<arrayLength;i++){
		//checking if it should place a brick there
		if(lvlArray[currentLvl-1][i] == 1){
			//creating a variable which holds the brick instance
			_root.attachMovie('mcBrick', 'brick'+i,_root.getNextHighestDepth());
			//setting the brick's coordinates via the i variable and brickRow
			_root['brick'+i]._x = 15+(i-brickRow*7)*75;
			_root['brick'+i]._y = 10+brickRow*20;
			//giving this brick some actions
			_root['brick'+i].onEnterFrame = function(){
				if(this.hitTest(_root.mcBall)){//if this touches the ball
					//then destroy this mofugger!
					this.removeMovieClip();
					//and make the ball bounce away
					ballYSpeed *= -1;
				}
			}
			//checks if the current brick needs a new row
			for(var c:Number = 1;c<=10;c++){
				if(i == c*7-1){
					brickRow ++;
				}
			}
		}
	}
}
 
makeLvl(); //finally, run the function
]]>
http://www.flashgametuts.com/tutorials/as2/how-to-create-a-brick-breaker-game-in-as2-part-4/feed/ 0