Hellow Guys, this week will be really simple, nothing really new, this tutorial will be 3 steps, the first one we will add a very simple background moving behind our ship, and it is really simple and without parallax (a theme that we may abort later), the second step we will add some enemies and the third step is make this enemies shoot on our ship, but this week won’t have any kind of collision (a theme for our next week) 😉 Oh, and if you want to read our last tutorial the link is HERE!

I – Adding a Simple Moving Background

The first thing, let’s add our background to our scene, drag the image bellow to your scene, in your document in Spaceship.fla:   starsbg     -So select it, and click in “Modify->Convert to Symbol…”.

Screen Shot 2014-08-08 at 11.43.01 PM

I Named it: “BG” Type: Movie Clip Check the Export for ActionScript Type our Class Name: Background and Base Class: “flash.display.MovieClip”

Screen Shot 2014-08-08 at 11.45.16 PM

– So click “OK” and “OK” again (if you need)   Delete the Background Symbol from the scene and the BG Background will be listed in your library. Time to code: Add 3 new vars to our public class Spaceship:

		private var bgspeed:Number=1;
		private var bg1:Background = new Background();
		private var bg2:Background = new Background(); 

Now heads on to inside of our “init(){“: Set the init for our new vars:

			bg1.x=0;
			bg1.y=0;
			this.addChildAt(bg1,0);
			bg2.x=800;
			bg2.y=0;
			this.addChildAt(bg2,0);
			bg2.visible=false;

Now go to our function “Draw” and let’s make the background begin to move: What happens bellow: We created two Backgrounds the same class background to keep it in infinity looping.

			if(bg1.x<=900 && bg1.x>=-1600 && bg1.visible){
				bg1.x=bg1.x-1;
				if(bg1.x<=-700 && bg2.visible==false){
					bg2.visible=true;
					bg2.x=900-bg1.x-700;
				}
				if(bg1.x<=-1600){
					bg1.visible=false;
				}
			}
			if(bg2.x<=900 && bg2.x>=-1600 && bg2.visible){
				bg2.x=bg2.x-1;
				if(bg2.x<=-700 && bg1.visible==false){
					bg1.visible=true;
					bg1.x=900-bg2.x-700;
					
				}
				if(bg2.x<=-1600){
					bg2.visible=false;
				}
				
			}

And now if you test our project, the background will be moving against our ship.

 

 

II – Preparing Enemy Ship

Now the enemy ship, you will do with enemy ship bellow almost the same you did with the Background, In other words, add this to our Library with the name EnemyShip and class: EnemyShip linked. -Import the image bellow to your flash document.

ship2

This ship also was created by me, so it is not problem to use it for this tutorial. And do the same with the new LaserShoot, convert it (bellow) to a symbol and name it: Lasershoot2 and class: Lasershoot2

lasershoot2

Your library now, should look something like this:

 

Screen Shot 2014-08-11 at 5.23.21 AM

So how it will work here: The enemy ship will spawn randomly coming from some possible ways crossing the screen shooting. Later for the next week: If the enemy ship hit the player he will explode and lose the game and if the player’s spaceship hit the enemy, the enemy explode and X ponts will be added to the player score. 😉 First, let’s edit our Lasershoot2 class; Right click over the Lasershoot2 on the library -Select Edit Class

Screen Shot 2014-08-11 at 6.48.18 PM

We need somehow link the laser to the enemyship’s array (that we will create soon), so let’s create a get and set inside this Lasershoot2 class and the full code of this class shall looks like:  Script.as

package  {
	
	import flash.display.MovieClip;
	
	
	public class Lasershoot2 extends MovieClip {
		private var _enemyshipArray:int=new int();
		
		public function Lasershoot2() {
			// constructor code
		}
		public function get enemyshipArray():int
                {
                     return _enemyshipArray;
                } 
		public function set enemyshipArray(nivelval:int):void
                {
                    _enemyshipArray = nivelval;
                }
	}
	
}

Save it with the name: Lasershoot2.as   Now go to the Spaceship.fla and do the same with the EnemyShip, right-click over the “EnemyShip” in library and select Edit Class and let’s add a bunch of get and setters here. EnemyShip.as:

package  {
	
	import flash.display.MovieClip;
	
	
	public class EnemyShip extends MovieClip {
		private var _directionMov:String=new String();
		private var _hp:Number=20
		private var _cooldownweapon:int=0;
		private var _cooldownweaponmax:int=30;
		private var _shootspeed:int=15;
		
		public function EnemyShip() {
			// constructor code
		}
		public function get directionMov():String
        {
            return _directionMov;
        } 
		public function set directionMov(nivelval:String):void
        {
            _directionMov = nivelval;
        }
		public function get hp():Number
        {
            return _hp;
        }
		public function set hp(nivelval:Number):void
        {
            _hp = nivelval;
        }
		public function get cooldownweapon():int
        {
            return _cooldownweapon;
        }
		public function set cooldownweapon(nivelval:int):void
        {
            _cooldownweapon = nivelval;
        }
		public function get cooldownweaponmax():int
        {
            return _cooldownweaponmax;
        }
		public function set cooldownweaponmax(nivelval:int):void
        {
            _cooldownweaponmax = nivelval;
        }
		public function get shootspeed():int
        {
            return _shootspeed;
        } 
		public function set shootspeed(nivelval:int):void
        {
            _shootspeed = nivelval;
        }
	}
}

Save it with the name EnemyShip.as

Explaining: _directionMov will be a var that will tell with a string the direction that our enemy ship will follow.

_hp is the heath point of the ship, 0=dead/destroyed

_cooldownweapon is what the name say, the actual value of the interval shoots of the enemy.

_cooldownweaponmax is the max interval time, is the full time it will take to “reload” for the next shoot of the enemy.

_shootspeed, is the speed of our enemy laser shoot.

 

Head to your Spaceship.as and let’s add two new Array private var inside the public class Spaceship:

 

private var laserList2:Array=new Array();
private var enemyList:Array=new Array();

 

Now let’s create the function randomRange such as bellow:

Randomizing a Value

 

function randomRange(max:Number, min:Number = 0):Number
{
	 return Math.random() * (max - min +1) + min;
}

That function will random a value between a max and a min number. 😉

Let’s create another function called “addEnemyShip”. Like the name say, this function will add a new enemy on our scene.

 

 
function addEnemyShip(xvalue:int, yvalue:int, directionMov:String):void{
			var enemy:EnemyShip = new EnemyShip();	
			enemy.directionMov=directionMov;
			enemy.x=xvalue;
			enemy.y=yvalue;
			enemy.rotation=270;
			enemy.scaleY=0.4;
			enemy.scaleX=0.3;
			enemyList.push(enemy);
			_mcHolder.addChild(enemy);
			_mcHolder.setChildIndex(enemy,0);
}

 

 

Explaining here; We created a function where it will be called on our function “Draw” and tell the x position, y position and the direction that enemy will follow.

And the last function we will add will be the function enemyShoot:

 

function enemyShoot(hindex:int):void{
			var laser2:Lasershoot2 = new Lasershoot2();		
			laser2.x=enemyList[hindex].x+(laser2.height/2);
			laser2.y=enemyList[hindex].y-(enemyList[hindex].width); 
			laser2.rotation=90;
			laser2.scaleY=0.4;
			laser2.scaleX=0.8;
			laser2.enemyshipArray=hindex;
			laserList2.push(laser2);
			_mcHolder.addChild(laser2);
			_mcHolder.setChildIndex(laser2,0);
			enemyList[hindex].cooldownweapon=enemyList[hindex].cooldownweaponmax;
			pewpewSound.play();
			
}

 

Explaining: This enemyShoot will create the lasershoot2 for the enemy and send it to the player direction. The “hindex” is the enemyship’s position on the array enemyList.

Now go to our function Draw(event:Event):void, first we will add the process of spawn the Enemy Spaceship:

The Spawn will works ramdomly and the movements too. However the movements are limited, if the ship spawn up to half-screen-height, the enemy ship can go straight our coming from up to down in diagonal, ekse the enemy ship can go straight our coming from down to up in diagonal:

 

if (randomRange(130, 1)<3){
 				var randomy:Number=randomRange(stage.stageHeight+100,-100);
 				if(randomy>(stage.stageHeight/2)){
				   if(randomRange(10,1)>5){
					   addEnemyShip(900, randomy,"Straight");
				   }
				   else{
					  addEnemyShip(900, randomy,"UpDownDiagonal");
				   }
				 }
				 else{
					if(randomRange(10,0)>5){
						addEnemyShip(900, randomy,"Straight");
					}
					else{
						addEnemyShip(900, randomy,"DownUpDiagonal");
					}
					 
				 }
}

 

We need to set the enemy movements now, yet inside of “Draw”, let’s make this spaceship start to move and here we must tell the directions:

 

if(enemyList.length>0){
				for(var j:int=0;j<enemylist.length;j++){ if(enemylist[j].x<1000=""  &&="" enemylist[j].hp="">0){
						if(enemyList[j].cooldownweapon>0){
							enemyList[j].cooldownweapon--;
						}
						else{
							enemyShoot(j);
						}
						if (enemyList[j].directionMov=="UpDownDiagonal"){
							enemyList[j].x+=-7.5;
							enemyList[j].y+=-3;
						}
						if (enemyList[j].directionMov=="DownUpDiagonal"){
							enemyList[j].x+=-7.5;
							enemyList[j].y+=+3;
						}
						if (enemyList[j].directionMov=="Straight"){
							enemyList[j].x+=-7.5;
						}
						if (enemyList[j].x<-100 && enemyList[j].hp>0){
							enemyList[j].hp=0;
							_mcHolder.removeChild(enemyList[j]);
						}
					}
				}
}

 

Som if the enemyShip is out of screen with “x”<-100, it will be “deleted” from the scene.

For last, let’s add the Lasershoot2 movements:

 

if(laserList2.length>0){
				for(var h:int=0;h

 

Now, you are ready to test your game, your game shall look like this:

Screen Shot 2014-08-12 at 4.06.07 PM

The full code of the Spaceship.as is bellow:

obs: if something goes wrong with the code, or you have any suggestion, be free to comment! or download the actual project bellow. 😉

package  {
	
	import flash.display.MovieClip;
	import flash.events.*;
	import flash.ui.Keyboard;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLVariables;
	import flash.media.Sound;
	import flash.media.SoundMixer;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform; 

	public class Spaceship extends MovieClip {
		//horizontal values
		private var _horispeedmax:Number=15;
		private var _horispeedaccel:Number=2;
		private var _horispeeddesaccel:Number=0.5;
		private var _horispeednow:Number=0;
		//vertical values
		private var _vertspeedmax:Number=15;
		private var _vertspeedaccel:Number=2;
		private var _vertspeeddesaccel:Number=0.5;
		private var _vertspeednow:Number=0;
		//keys
		private var _pushshoot:Boolean=false;
		private var _pushleft:Boolean=false;
		private var _pushright:Boolean=false;
		private var _pushtop:Boolean=false;
		private var _pushbottom:Boolean=false;
		//Mouse Click
		private var _mouseClicked:Boolean = false;
		//MovieClips
		private var _mcHolder:MovieClip = new MovieClip(); //a Holder of movieclips for our scene
		//Array Lists
		private var laserList:Array=new Array();
		private var laserList2:Array=new Array();
		private var enemyList:Array=new Array(); 
		//Sound Effects:
		private var Pewpew:URLRequest = new URLRequest("lasershot.mp3");
		private var pewpewSound:Sound = new Sound(Pewpew);
		//Backgrounds
		private var bgspeed:Number=1;
		private var bg1:Background = new Background();
		private var bg2:Background = new Background();
		//Others
		private var minimumi:int=0;
		private var _weaponcooldown:int=0;
		private var _weaponcooldownmax:int=10;
		private var _shootSpeed:Number=20;
		private var lastyclicked:Number=0;
		
		public function Spaceship() {
			trace("inited");
			init();
		}
		private function init():void{
			addChild(_mcHolder);//Adding a holder for the scene
			//Background
			bg1.x=0;
			bg1.y=0;
			this.addChildAt(bg1,0);
			bg2.x=800;
			bg2.y=0;
			this.addChildAt(bg2,0);
			bg2.visible=false;
			//Laser
			minimumi=0;
			_weaponcooldown=0; //Everytime the game starts, the weapon cooldown will be set to 0
			
			//myShip posicioning
			myShip.x=140;
			myShip.y=120;
			myShip.rotation=90;
			myShip.scaleY=0.6;
			myShip.scaleX=0.4;
			
			//Keyboard events:
			stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyDown);
			stage.addEventListener(KeyboardEvent.KEY_UP, KeyUp);
			stage.addEventListener(Event.ENTER_FRAME, Draw);
			//Mouse events:
			stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
			stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
		}
		
		function KeyDown(event:KeyboardEvent):void
		{
			if(event.keyCode == Keyboard.SPACE) {
				_pushshoot = true;
			}
			if(event.keyCode == Keyboard.RIGHT) {
				_pushright = true;
				_pushleft =false;
			}
			if(event.keyCode == Keyboard.LEFT) {
				_pushleft = true;
				_pushright = false;
			}
			if(event.keyCode == Keyboard.UP) {
				
				_pushtop = true;
				_pushbottom = false;
			}
			if(event.keyCode == Keyboard.DOWN) {
				_pushbottom = true;
				_pushtop = false;
			}
		}
		
		function KeyUp(event:KeyboardEvent):void
		{
			if(event.keyCode == Keyboard.SPACE) { 
				_pushshoot = false;
			}
			if(event.keyCode == Keyboard.RIGHT) {
				_pushright = false;
			}
			if(event.keyCode == Keyboard.LEFT) {
				_pushleft = false;
			}
			if(event.keyCode == Keyboard.UP) {
				_pushtop = false;
			}
			if(event.keyCode == Keyboard.DOWN) {
				_pushbottom = false;
			}
		}
		
		private function onMouseDownHandler(e:MouseEvent):void {
			 _mouseClicked = true;
			 lastyclicked=stage.mouseY;
		}
		private function onMouseUpHandler(e:MouseEvent):void {
			 _mouseClicked = false;
		}
		
		function randomRange(max:Number, min:Number = 0):Number
		{
			 return Math.random() * (max - min +1) + min;
		}
		
		function addEnemyShip(xvalue:int, yvalue:int, directionMov:String):void{
			var enemy:EnemyShip = new EnemyShip();	
			enemy.directionMov=directionMov;
			enemy.x=xvalue;
			enemy.y=yvalue;
			enemy.rotation=270;
			enemy.scaleY=0.4;
			enemy.scaleX=0.3;
			enemyList.push(enemy);
			_mcHolder.addChild(enemy);
			_mcHolder.setChildIndex(enemy,0);
		}
		
		function enemyShoot(hindex:int):void{
			var laser2:Lasershoot2 = new Lasershoot2();		
			laser2.x=enemyList[hindex].x+(laser2.height/2);
			laser2.y=enemyList[hindex].y-(enemyList[hindex].width); 
			laser2.rotation=90;
			laser2.scaleY=0.4;
			laser2.scaleX=0.8;
			laser2.enemyshipArray=hindex;
			laserList2.push(laser2);
			_mcHolder.addChild(laser2);
			_mcHolder.setChildIndex(laser2,0);
			enemyList[hindex].cooldownweapon=enemyList[hindex].cooldownweaponmax;
			pewpewSound.play();
			
		}
		
		function Draw(event:Event):void
		{
			//Enemy SpaceShip Spawn:
			if (randomRange(130, 1)<3){
 				var randomy:Number=randomRange(stage.stageHeight+100,-100);
 				if(randomy>(stage.stageHeight/2)){
				   if(randomRange(10,1)>5){
					   addEnemyShip(900, randomy,"Straight");
				   }
				   else{
					  addEnemyShip(900, randomy,"UpDownDiagonal");
				   }
				 }
				 else{
					if(randomRange(10,0)>5){
						addEnemyShip(900, randomy,"Straight");
					}
					else{
						addEnemyShip(900, randomy,"DownUpDiagonal");
					}
					 
				 }
			}
			//Background Movement
			if(bg1.x<=900 && bg1.x>=-1600 && bg1.visible){
				bg1.x=bg1.x-1;
				if(bg1.x<=-700 && bg2.visible==false){
					bg2.visible=true;
					bg2.x=900-bg1.x-700;
				}
				if(bg1.x<=-1600){
					bg1.visible=false;
				}
			}
			if(bg2.x<=900 && bg2.x>=-1600 && bg2.visible){
				bg2.x=bg2.x-1;
				if(bg2.x<=-700 && bg1.visible==false){
					bg1.visible=true;
					bg1.x=900-bg2.x-700;
					
				}
				if(bg2.x<=-1600){
 					bg2.visible=false;
 				}

 			}
			 			//===================Movements==========
 			//Enemy Ships Movements
 			if(enemyList.length>0){
				for(var j:int=0;j<enemylist.length;j++){ if(enemylist[j].x="" <="" 1000=""  &&="" enemylist[j].hp=""> 0){
						if(enemyList[j].cooldownweapon>0){
							enemyList[j].cooldownweapon--;
						}
						else{
							enemyShoot(j);
						}
						if (enemyList[j].directionMov=="UpDownDiagonal"){
							enemyList[j].x+=-7.5;
							enemyList[j].y+=-3;
						}
						if (enemyList[j].directionMov=="DownUpDiagonal"){
							enemyList[j].x+=-7.5;
							enemyList[j].y+=+3;
						}
						if (enemyList[j].directionMov=="Straight"){
							enemyList[j].x+=-7.5;
						}
						if (enemyList[j].x < -100 && enemyList[j].hp > 0){
							enemyList[j].hp=0;
							_mcHolder.removeChild(enemyList[j]);
						}
					}

				}
			}
			//Enemy Laser Movements:
			if(laserList2.length>0){
				for(var h:int=0;h<laserlist2.length;h++){ laserlist2[h].x="laserList2[h].x-enemyList[laserList2[h].enemyshipArray].shootspeed;" if="" (laserlist2[h].x<-100){="" _mcholder.removechild(laserlist2[h]);="" laserlist2.splice(h,="" 1);="" }="" lasers="" movements:="" if(laserlist.length="">0){
				for(var i:int=minimumi;i<laserlist.length;i++){ if(laserlist[i].x<1000){="" laserlist[i].x+="_shootSpeed;" }="" else{="" minimumi="i+1;" _mcholder.removechild(laserlist[i]);="" =="=================Keys=================" if(_weaponcooldown="">0){
				_weaponcooldown--;
			}
			//Keys
			if(_pushshoot && _weaponcooldown==0){
				var laser:Lasershoot = new Lasershoot();		
				laser.x=myShip.x+(laser.height/2);
				laser.y=myShip.y+(myShip.width/1.1);
				laser.rotation=90;
				laser.scaleY=0.4;
				laserList.push(laser);
				_mcHolder.addChild(laser);
				_mcHolder.setChildIndex(laser,0);
				_weaponcooldown=_weaponcooldownmax;
				pewpewSound.play();
			}
			if(_mouseClicked){
				if(stage.mouseY>=(myShip.y+(myShip.width/2)-_vertspeedmax+20) && stage.mouseY<=(myShip.y+(myShip.width/2)+_vertspeedmax+20)){
 					_pushbottom=false;
 					_pushtop=false;
 					_vertspeednow=0;
 				}
 				else{
 					if(stage.mouseY>=(myShip.y+(myShip.width/2))){
						_pushbottom=true;
						_pushtop=false;
					}
					else{
						_pushbottom=false;
						_pushtop=true;
					}
				}
			}
			else{
				if(lastyclicked>=(myShip.y+(myShip.width/2)-_vertspeedmax+20) && lastyclicked<=(myShip.y+(myShip.width/2)+_vertspeedmax+20)){
					_vertspeednow=0;
					_pushbottom=false;
					_pushtop=false;
				}
			}
			if(_pushright && _horispeednow<=_horispeedmax ) {
 				_horispeednow+=_horispeedaccel;
 			}
 			else{
 				if(_horispeednow>0){
					_horispeednow-=_horispeeddesaccel;
				}
				if(_horispeednow<0){
 					_horispeednow+=_horispeeddesaccel;
 				}
 			}
 			if(_pushleft && _horispeednow>=-_horispeedmax) {
				_horispeednow-=_horispeedaccel;
			}
			else{
				if(_horispeednow>0){
					_horispeednow-=_horispeeddesaccel;
				}
				if(_horispeednow<0){
 					_horispeednow+=_horispeeddesaccel;
 				}
 			}
 			if(_pushtop && _vertspeednow>=-_vertspeedmax) {
				_vertspeednow-=_vertspeedaccel;
			}
			else{
				if(_vertspeednow>0){
					_vertspeednow-=_vertspeeddesaccel;
				}
				if(_vertspeednow<0){
					_vertspeednow+=_vertspeeddesaccel;
				}
				if(_vertspeednow-1){
						_vertspeednow=0;
				}
			}
			if(_pushbottom && _vertspeednow<=_vertspeedmax) {
 				_vertspeednow+=_vertspeedaccel;
 			}
 			else{
				if(_vertspeednow>0){
					_vertspeednow-=_vertspeeddesaccel;
					
				}
				if(_vertspeednow<0){
					_vertspeednow+=_vertspeeddesaccel;
				}
				if(_vertspeednow-1){
						_vertspeednow=0;
				}
			}
			myShip.y+=_vertspeednow;
			myShip.x+=_horispeednow;
		}
	}
	
}

 

we don’t have collisions yet, but this theme is coming next week. 😉

Oh and our project till now can be downloaded HERE.

3 thoughts on “Tutorial Actionscript 3 Create Your Simple Spaceship Game for iOS or Android – 4: A Simple Moving Background and Enemy Ship

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s