Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Build a Stage3D Shoot-'Em-Up: Terrain, Enemy AI, and Level Data

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

This post is part of a series called Shoot-'Em-Up.
Quick Tip: A Simple Score Display for Flash Games
Animating Game Menus and Screen Transitions in HTML5: A Guide for Flash Developers

We're creating a high-performance 2D shoot-em-up using Flash's new hardware-accelerated Stage3D rendering engine. In this part of the series we add new enemy movement modes, enemies that shoot back, and hand-crafted levels with background terrain.


Also available in this series:

  1. Build a Stage3D Shoot-’Em-Up: Sprite Test
  2. Build a Stage3D Shoot-’Em-Up: Interaction
  3. Build a Stage3D Shoot-’Em-Up: Explosions, Parallax, and Collisions
  4. Build a Stage3D Shoot-'Em-Up: Terrain, Enemy AI, and Level Data
  5. Build a Stage3D Shoot-’Em-Up: Score, Health, Lives, HUD and Transitions
  6. Build a Stage3D Shoot-’Em-Up: Full-Screen Boss Battles and Polish

Final Result Preview

Let's take a look at the final result we will be working towards: a hardware-accelerated shoot-em-up demo that includes everything from parts one to three of this series, plus new enemy movement modes, enemies that shoot back, and hand-crafted levels that include background terrain.


Introduction: Welcome to Level Four!

Let's continue to make a side-scrolling shooter inspired by retro arcade titles such as R-Type or Gradius in AS3.

In the first part of this series, we implemented a basic 2D sprite engine that achieves great performance through the use of Stage3D hardware rendering and as several optimizations.

In the first part, we implemented a title screen, the main menu, sound and music, and an input system so that the player can control their spaceship using the keyboard.

And in the third part, we added all the eye-candy: a particle system complete with sparks, flying debris, shockwaves, engine fire trails and tons of explosions.

In this part, we are going to upgrade several main components of our game engine. Firstly, we are going to add A.I. (artificial intelligence) to our enemies by creating several different behaviors and movement styles. They are finally going to start shooting back, and will no longer simply move in a straight line. Some won't even move at all, but will point at the the player: perfect for sentry guns.

Secondly, we are going to implement a level data parsing mechanism that will empower you to design vast game worlds using a level editor.

Thirdly, we are going to create a new spritesheet and rendering batch for a non-interactive set of terrain sprites that will be used as part of the background. This way, we will be flying over top of detailed space stations and asteroids rather than just empty space.


Step 1: Open Your Existing Project

We're going to be building on the source code written in the previous tutorials, much of which will not change. If you don't already have it, be sure to download the source code from the previous tutorial. Open the project file in FlashDevelop (info here) and get ready to upgrade your game! This source code will work in any other AS3 compiler, from CS6 to Flash Builder.


Step 2: Upgrade the Entity Class

We are first going to implement some new movement AI to our entity class. For this functionality we're going to require some more state data to be tracked for each entity. In particular we'll need some path information, and various timers that will let us know how often an enemy needs to shoot at the player. Open the existing Entity.as file from last time and add the following new class variables as follows. To avoid confusion, the entire top section of the file is included here but only the AI variables at the top are new.

 
// Stage3D Shoot-em-up Tutorial Part 4 
// by Christer Kaitila - www.mcfunkypants.com 
 
// Entity.as 
// The Entity class will eventually hold all game-specific entity stats 
// for the spaceships, bullets and effects in our game. 
// It stores a reference to a gpu sprite and a few demo properties. 
// This is where you would add hit points, weapons, ability scores, etc. 
// This class handles any AI (artificial intelligence) for enemies as well. 
 
package 
{ 
	import flash.geom.Point; 
	import flash.geom.Rectangle; 
	 
	public class Entity 
	{ 
		// AI VARIABLES BEGIN 
		// if this is set, custom behaviors are run 
		public var aiFunction : Function; 
		// the AI routines might want access to the entity manager 
		public var gfx:EntityManager; 
		// AI needs to have access to time passing (in seconds) 
		public var age:Number = 0; 
		public var fireTime:Number = 0; 
		public var fireDelayMin:Number = 1; 
		public var fireDelayMax:Number = 6; 
		// an array of points defining a movement path for the AI 
		public var aiPathWaypoints:Array; 
		// how fast we travel from one spline node to the next in seconds 
		public var pathNodeTime:Number = 1; 
		// these offsets are added to the sprite location 
		// so that ships move around but eventually scroll offscreen 
		public var aiPathOffsetX:Number = 0; 
		public var aiPathOffsetY:Number = 0; 
		// how much big the path is (max) 
		public var aiPathSize:Number = 128; 
		// how many different nodes in the path 
		public var aiPathWaypointCount:int = 8; 
		// AI VARIABLES END 
		 
		private var _speedX : Number; 
		private var _speedY : Number; 
		private var _sprite : LiteSprite; 
		public var active : Boolean = true; 
 
		// collision detection 
		public var isBullet:Boolean = false; // only these check collisions 
		public var leavesTrail:Boolean = false; // creates particles as it moves 
		public var collidemode:uint = 0; // 0=none, 1=sphere, 2=box, etc. 
		public var collideradius:uint = 32; // used for sphere collision		 
		// box collision is not implemented (yet) 
		public var collidebox:Rectangle = new Rectangle(-16, -16, 32, 32); 
		public var collidepoints:uint = 25; // score earned if destroyed 
		public var touching:Entity; // what entity just hit us? 
 
		public var owner:Entity; // so your own bullets don't hit you 
		public var orbiting:Entity; // entities can orbit (circle) others 
		public var orbitingDistance:Number; // how far in px from the orbit center 
		 
		// used for particle animation (in units per second) 
		public var fadeAnim:Number = 0; 
		public var zoomAnim:Number = 0; 
		public var rotationSpeed:Number = 0; 
 
		// used to mark whether or not this entity was  
		// freshly created or reused from an inactive one 
		public var recycled:Boolean = false;

Step 3: Don't Fire Immediately

We're going to keep track of the elapsed time since an enemy shot at the player so that bad guys don't shoot too often. We also need enemies to remember not to fire instantly right when they are first spawned, so we need to add a small amount of random time before they start shooting.

Continuing with Entity.as, upgrade the class constructor function as follows, and simply take note of the unchanged getter and setter functions as well as the identical collision detection code from last time.

		 
		public function Entity(gs:LiteSprite, myManager:EntityManager) 
		{ 
			_sprite = gs; 
			_speedX = 0.0; 
			_speedY = 0.0; 
			// we need a reference to the entity manager 
			gfx = myManager; 
			// we don't want everyone shooting on the first frame 
			fireTime = (gfx.fastRandom() * (fireDelayMax - fireDelayMin)) + fireDelayMin; 
		} 
		 
		public function die() : void 
		{ 
			// allow this entity to be reused by the entitymanager 
			active = false; 
			// skip all drawing and updating 
			sprite.visible = false; 
			// reset some things that might affect future reuses: 
			leavesTrail = false; 
			isBullet = false; 
			touching = null; 
			owner = null; 
			age = 0; 
			collidemode = 0; 
		} 
		 
		public function get speedX() : Number  
		{ 
			return _speedX; 
		} 
		public function set speedX(sx:Number) : void  
		{ 
			_speedX = sx; 
		} 
		public function get speedY() : Number  
		{ 
			return _speedY; 
		} 
		public function set speedY(sy:Number) : void  
		{ 
			_speedY = sy; 
		} 
		public function get sprite():LiteSprite  
		{	 
			return _sprite; 
		} 
		public function set sprite(gs:LiteSprite):void  
		{ 
			_sprite = gs; 
		} 
 
		// used for collision callback performed in GameActorpool 
		public function colliding(checkme:Entity):Entity 
		{ 
			if (collidemode == 1) // sphere 
			{ 
				if (isCollidingSphere(checkme)) 
					return checkme; 
			} 
			return null; 
		} 
	 
	// simple sphere to sphere collision 
	public function isCollidingSphere(checkme:Entity):Boolean 
	{ 
		// never collide with yourself 
		if (this == checkme) return false; 
		// only check if these shapes are collidable 
		if (!collidemode || !checkme.collidemode) return false; 
		// don't check your own bullets 
		if (checkme.owner == this) return false; 
		// don't check things on the same "team" 
		if (checkme.owner == owner) return false; 
		// don't check if no radius 
		if (collideradius == 0 || checkme.collideradius == 0) return false; 
		 
		// this is the simpler way to do it, but it runs really slow 
		// var dist:Number = Point.distance(sprite.position, checkme.sprite.position); 
		// if (dist <= (collideradius+checkme.collideradius)) 
		 
		// this looks wierd but is 6x faster than the above 
		// see: http://www.emanueleferonato.com/2010/10/13/as3-geom-point-vs-trigonometry/ 
		if (((sprite.position.x - checkme.sprite.position.x) *  
			(sprite.position.x - checkme.sprite.position.x) + 
			(sprite.position.y - checkme.sprite.position.y) * 
			(sprite.position.y - checkme.sprite.position.y)) 
			<=  
			(collideradius+checkme.collideradius)*(collideradius+checkme.collideradius)) 
		{ 
			touching = checkme; // remember who hit us 
			return true; 
		} 
		 
		// default: too far away 
		// trace("No collision. Dist = "+dist); 
		return false; 
		 
	}

Step 4: Spline Curve Movement

One of the new AI modes is going to be a curvy, random movement path. A great algorithm used in many games is the classic Catmull-Rom spline curve, which takes an array of points and interpolates a smooth path between them all. This path will loop around at the ends if need be.

The first new routine we need for our entity class is the spline calculation function. It takes three points and a "percentage" number t that should go from zero to one over time. As t approaches 1 the point returned will be at the very end of the curve segment, and conversely if it is zero the point returned is the spline's starting position.

For our current game demo, we're just going to generate a bunch of random points for each new entity that uses this kind of moment, but you could easily add your own predefined paths for all sorts of interesting enemy movement patterns, from a figure eight to a simple zig-zag pattern.

You can read more about Catmull-Rom splione curves in AS3 by checking out this demo and this tutorial.

 
	// Calculates 2D cubic Catmull-Rom spline. 
	// See http://www.mvps.org/directx/articles/catmull/  
	public function spline (p0:Point, p1:Point, p2:Point, p3:Point, t:Number):Point  
	{ 
		return new Point ( 
			0.5 * ((2 * p1.x) + 
			t * (( -p0.x + p2.x) + 
			t * ((2 * p0.x -5 * p1.x +4 * p2.x -p3.x) + 
			t * ( -p0.x +3 * p1.x -3 * p2.x +p3.x)))), 
			0.5 * ((2 * p1.y) + 
			t * (( -p0.y + p2.y) + 
			t * ((2 * p0.y -5 * p1.y +4 * p2.y -p3.y) + 
			t * (  -p0.y +3 * p1.y -3 * p2.y +p3.y)))) 
		); 
	} 
     
	// generate a random path 
	public function generatePath():void 
	{ 
		trace("Generating AI path"); 
		aiPathWaypoints = [];	 
		var N:int = aiPathWaypointCount; 
		for (var i:int = 0; i < N; i++)  
		{ 
			aiPathWaypoints.push (new Point (aiPathSize * Math.random (), aiPathSize * Math.random ())); 
		} 
	} 
				 
	// find the point on a spline at ratio (0 to 1) 
	public function calculatePathPosition(ratio:Number = 0):Point 
	{ 
		var i:int = int(ratio); 
		var pointratio:Number = ratio - i; 
		//trace(ratio + ' ratio = path point ' + i + ' segment ratio ' + pointratio); 
		var p0:Point = aiPathWaypoints [(i -1 + aiPathWaypoints.length) % aiPathWaypoints.length]; 
		var p1:Point = aiPathWaypoints [i % aiPathWaypoints.length]; 
		var p2:Point = aiPathWaypoints [(i +1 + aiPathWaypoints.length) % aiPathWaypoints.length]; 
		var p3:Point = aiPathWaypoints [(i +2 + aiPathWaypoints.length) % aiPathWaypoints.length]; 
		// figure out current position 
		var q:Point = spline (p0, p1, p2, p3, pointratio); 
		return q; 
	}

Step 5: Decide When to Shoot

Every enemy type needs to shoot at the player (except for non-shooting asteroids that will simply spin and float in space). For now, we are going to simply keep track of the elapsed time since we last fired our weapon and add a random range of a couple seconds between shots.

		 
	// we could optionally implement many different 
	// versions of this routine with different randomness 
	public function maybeShoot(bulletNum:int = 1,  
		delayMin:Number = NaN,  
		delayMax:Number = NaN):void 
	{ 
		// is it time to shoot a bullet? 
		if (fireTime < age) 
		{ 
			// if delay parameters were not set, use class defaults 
			if (isNaN(delayMin)) delayMin = fireDelayMin; 
			if (isNaN(delayMax)) delayMax = fireDelayMax; 
			 
			// shoot one from the current location 
			gfx.shootBullet(bulletNum, this); 
			// randly choose the next time to shoot 
			fireTime = age + (gfx.fastRandom() * (delayMax - delayMin)) + delayMin; 
		} 
	}

You could add more intelligence to this routine by only shooting when the player is within a certain distance, or only shooting once and self destructing if your game requires some sort of "time-bomb" effect.


Step 6: AI #1: Move in a Straight Line

The first AI "brain" function we are going to implement is the most simple: the straightforward movement along a line as seen in last week's tutorial. All we do here is point in the corrent direction and move at whatever trajectory was randomly assigned to us when we were first spawned. Nothing to it!

	 
	// moves forward and points at current destination based on speed 
	public function straightAI(seconds:Number):void 
	{ 
		age += seconds; 
		maybeShoot(1); 
		sprite.rotation = gfx.pointAtRad(speedX, speedY) 
			- (90*gfx.DEGREES_TO_RADIANS); 
	}

Step 7: AI #2: Sinusoidal Wobble

One of the most common movement patterns in any shoot-em-up is a sinusoidal "wave" motion. We're going to use a sine wave that will wobble up and down over time as the enemy moves in a mostly straight line toward the player. This pattern really looks nice and adds some pleasing movement to your enemies without too much chaos, which makes these kinds of enemies easy to aim at and destroy.

 
	// a very simple up/down wobble movement 
	public function wobbleAI(seconds:Number):void 
	{ 
		age += seconds; 
		maybeShoot(1); 
		aiPathOffsetY = (Math.sin(age*2) / Math.PI) * 128;		 
	}

Step 8: AI #3: Sentry Guns

Another really handy and common style of enemy AI that most shoot-em-ups use is a motionless "sentry gun" or turret. This kind of enemy will just sit there and aim at the player. It can be scary for players to see the sentry guns following their every move and is sure to elicit some evasive maneuvers.

	 
	// simply point at the player: good for sentry guns 
	public function sentryAI(seconds:Number):void 
	{ 
		age += seconds; 
		maybeShoot(3,3,6); 
		if (gfx.thePlayer) 
			sprite.rotation = gfx.pointAtRad( 
				gfx.thePlayer.sprite.position.x - sprite.position.x, 
				gfx.thePlayer.sprite.position.y - sprite.position.y)  
				- (90*gfx.DEGREES_TO_RADIANS); 
	}

Since we need access to the player entity's position, we do a quick check to ensure that it exists since AI functions might get run during the "attract mode" main menu before there is a player to aim at.


Step 9: AI #4: Spline Paths

The final style of AI movement is going to use the Catmull-Rom spline curve interpolation routines we programmed above. Enemies of this type will wobble and spin around in a choatic, frustrating fashion. It is best to only include a few enemies of this type in your game, unless you have upgraded the generatePath function to use a manually-entered array of points that isn't so random.

To make things look nicer, once we figure out the new coordinates for our enemy, we orient the sprite to face the direction in which it is moving, so it spins while it loops around.

	 
	// move around on a random spline path 
	// in future versions, you could upgrade this function 
	// to (instead of random) follow a predefined array of points 
	// that were designed by hand in code (or even in the level editor!) 
	public function droneAI(seconds:Number):void 
	{ 
		//trace('droneAI'); 
		 
		age += seconds; 
		maybeShoot(1); 
 
		// movement style inspired by Galaga, R-Type, Centipede 
		// performed by easing through a catmull-rom spline curve 
		// defined by an array of points 
		if (aiPathWaypoints == null) 
			generatePath(); 
			 
		// how many spline nodes have we passed? (loops around to beginning) 
		var pathProgress:Number = age / pathNodeTime; 
			 
		var newPos:Point = calculatePathPosition(pathProgress); 
 
		// point in the correct direction 
		sprite.rotation = gfx.pointAtRad(newPos.x-aiPathOffsetX,newPos.y-aiPathOffsetY)  
			- (90*gfx.DEGREES_TO_RADIANS); 
		 
		// change path offset location 
		// this is added to the sprite scrolling location 
		// so that ships eventually move offscreen 
		// sprite.position.x = newPos.x; 
		// sprite.position.y = newPos.y; 
		 
		aiPathOffsetX = newPos.x; 
		aiPathOffsetY = newPos.x; 
		 
	} 
	 
	} // end class 
} // end package

That's it for our newly upgraded entity class. We've added some fresh new movement code and finally our vast fleets of enemy ships are capable of firing back at the player!


Step 10: The Terrain Spritesheet

Before we move on, we are going to create a new spritesheet for use as the building blocks for our terrain graphics. We are again going to use the wonderful, legal and free "Tyrian" art by Daniel Cook (available at Lostgarden.com). As always, remember to use a square image that is a power-of-two in dimensions (128x128, 256x256, 512x512, etc) when creating your spritesheet. This is the spritesheet I created for this demo:



Step 11: Level Editor Time!

It is finally time to implement a way to parse the data that is generated by a proper level editor. Instead of a simplistic random, never-ending wave of enemies, we want to be able to hand-craft an interesting gameplay experience. To do so, we're going to create a simple class that parses the data output by a popular open source level editor called OGMO. You can read all about OGMO here.

You don't have to use OGMO: you could modify these routines to parse an XML as output by "Tiled" or "DAME", or a .CSV file as output by Excel, or even a .GIF or .PNG as output by Photoshop (by drawing individual pixels and spawning different kinds of enemy depending on what color each pixel is).

The parsing routine for any of kind of level data is trivial compared to our in-game functionality. For sheer simplicity and small download size, CSV (comma-separated values) is a great alternative to bloated and complex XML. More importantly, the linear nature of our shoot-em-up requires a long string of data that is convinient to be able to access column-by-column and row-by-row, as opposed to a "soup" of XML entities that could be in any order. CSV keeps our data flowing from left to right, just like our game. Since OGMO can save data in this format, it's a perfect fit.

Download the installer and optionally the source code. Once you've installed it, create two new projects - one for the terrain and one for the enemy sprites. Ensure that your level data will be saved in the compact and simplistic "trimmed CSV" format.



Be sure to save in CSV format

For the terrain project, we need to create a layer for the terrain that uses our newly photoshopped spritesheet above.


Now, simpy draw the map any way you like. You can click each sprite in your spritesheet in the tile palette and them draw or flood-fill your level as you see fit. Right-click the level to erase that tile, and hold down space while clicking and dragging to scroll around.


Now do the same thing for your enemy sprites. Create a layer that uses the spritesheet we made in previous tutorials as follows:


Finally, fill your level with all sorts of interesting squadrons of enemy ships as you see fit. For the current demo, I started with only a few baddies and literally filled every single space with asteroids towards the end of the level.


The OMGO source files for the levels used in the game demo are included in the /assets/ folder of the source code zip file.


Step 10: Embed the Level Data

We're going to simply embed the levels right into our SWF so that it continues to be a standalone game that doesn't require any external files to be downloaded. You can have the level editor open while programming your game. Any time you tweak your level, just save it and click FlashDevelop's RUN button to see the changes in action. It will notice the new timestamp on your level file and recompile the SWF accordingly.

Depending on which level is requested, we fill a two-dimensional array of integer values based on the level data output by the editor. During gameplay, our entity manager is going to periodically spawn another column of terrain or enemy sprites based on this data. Create a brand new file in your code project called GameLevels.as and embed the level data as follows.

 
// Stage3D Shoot-em-up Tutorial Part 4 
// by Christer Kaitila - www.mcfunkypants.com 
 
// GameLevels.as 
// This class parses .CSV level data strings 
// that define the locations of tiles from a spritesheet 
// Example levels were created using the OGMO editor, 
// but could be designed by hand or any number of other 
// freeware game level editors that can output .csv 
// This can be a .txt, .csv, .oel, .etc file 
// - we will strip all xml/html tags (if any)  
// - we only care about raw csv data 
// Our game can access the current level with: 
// spriteId = myLevel.data[x][y]; 
 
package 
{ 
	import flash.display3D.Context3DProgramType; 
	public class GameLevels 
	{ 
		// the "demo" level seen during the title screen 
		[Embed(source = '../assets/level0.oel', mimeType = 'application/octet-stream')]  
		private static const LEVEL0:Class; 
		private var level0data:String = new LEVEL0; 
		 
		// the "demo" level background TERRAIN 
		[Embed(source = '../assets/terrain0.oel', mimeType = 'application/octet-stream')]  
		private static const LEVEL0TERRAIN:Class; 
		private var level0terrain:String = new LEVEL0TERRAIN; 
 
		// the first level that the player actually experiences 
		[Embed(source = '../assets/level1.oel', mimeType = 'application/octet-stream')]  
		private static const LEVEL1:Class; 
		private var level1data:String = new LEVEL1; 
		 
		// the first level background TERRAIN 
		[Embed(source = '../assets/terrain1.oel', mimeType = 'application/octet-stream')]  
		private static const LEVEL1TERRAIN:Class; 
		private var level1terrain:String = new LEVEL1TERRAIN; 
 
		// the currently loaded level data 
		public var data:Array = []; 
		 
		public function GameLevels() 
		{ 
		}

Step 11: Parse the Level Data

Our new level data parsing class is going to be incredibly simplistic: we simply strip any superfluous XML and gobble up the .CSV data by splitting each line by commas. This is enough for our purposes.

Continue with GameLevels.as and implement the level data parsing function as follows:

		 
		private function stripTags(str:String):String 
		{ 
			var pattern:RegExp = /<\/?[a-zA-Z0-9]+.*?>/gim; 
			return str.replace(pattern, ""); 
		} 
	 
		private function parseLevelData(lvl:String):Array 
		{ 
			var levelString:String; 
			var temps:Array; 
			var nextValue:int; 
			var output:Array = []; 
			var nextrow:int; 
			switch (lvl) 
			{ 
				case "level0" : levelString = stripTags(level0data); break; 
				case "terrain0" : levelString = stripTags(level0terrain); break; 
				case "level1" : levelString = stripTags(level1data); break; 
				case "terrain1" : levelString = stripTags(level1terrain); break; 
				default: 
					return output;  
			} 
			//trace("Level " + num + " data:\n" + levelString); 
			var lines:Array = levelString.split(/\r\n|\n|\r/); 
			for (var row:int = 0; row < lines.length; row++) 
			{ 
				// split the string by comma 
				temps = lines[row].split(","); 
				if (temps.length > 1) 
				{ 
					nextrow = output.push([]) - 1; 
					// turn the string values into integers 
					for (var col:int = 0; col < temps.length; col++) 
					{ 
						if (temps[col] == "") temps[col] = "-1"; 
						nextValue = parseInt(temps[col]); 
						if (nextValue < 0) nextValue = -1; // we still need blanks 
						trace('row '+ nextrow + ' nextValue=' + nextValue); 
						output[nextrow].push(nextValue); 
					} 
					//trace('Level row '+nextrow+':\n' + String(output[nextrow])); 
				} 
			} 
			//trace('Level output data:\n' + String(output)); 
			return output; 
		} 
		 
		public function loadLevel(lvl:String):void 
		{ 
			trace("Loading level " + lvl); 
			data = parseLevelData(lvl); 
		} 
		 
	} // end class 
} // end package

That's it for our level parsing class. Though it is simplistic, it takes up very little space in our SWF, runs quite quickly, and allows us to iterate our level designs with ease by having FlashDevelop and OGMO open at the same time. Two clicks are all it takes to try out a new version of your level, which means that the design-test-repeat cycle is mere seconds.

Just for fun, here are some screenshots of the style of levels we are going to be able to play in our game:






Step 12: Upgrade the Entity Manager

We need to take advantage of these cool new AI movement modes and the awesome new terrain system we just created. This will require some minor tweaks to the EntityManager.as file from last time. To avoid confusion, the entire class is presented here, but only a few lines here and there have changed.

In particular, instead of forcing the entity manager to use a particular spritesheet image, we are going to allow it to be defined by our Main.as so that we can have more than one. This is because we now have an enemy and a terrain entity manager running concurrently.

Other minor tweaks include a larger culling distance (the outside edges of the game world where sprite that go beyond it are recycled for reuse in our sprite pool), plus various new class variables that are needed for our level data parsing routine.

Begin by upgrading all the class variables at the top of the file as follows:

 
// Stage3D Shoot-em-up Tutorial Part 4 
// by Christer Kaitila - www.mcfunkypants.com 
 
// EntityManager.as 
// The entity manager handles a list of all known game entities. 
// This object pool will allow for reuse (respawning) of 
// sprites: for example, when enemy ships are destroyed, 
// they will be re-spawned when needed as an optimization  
// that increases fps and decreases ram use. 
 
package 
{ 
	import flash.display.Bitmap; 
	import flash.display3D.*; 
	import flash.geom.Point; 
	import flash.geom.Rectangle; 
	 
	public class EntityManager 
	{ 
		// the level data parser 
		public var level:GameLevels; 
		// the current level number 
		public var levelNum:int = 0; 
		// where in the level we are in pixels 
		public var levelCurrentScrollX:Number = 0; 
		// the last spawned column of level data 
		public var levelPrevCol:int = -1; 
		// pixels we need to scroll before spawning the next col 
		public var levelTilesize:int = 48; 
		// this is used to ensure all terrain tiles line up exactly 
		public var lastTerrainEntity:Entity; 
		 
		// we need to allow at least enough space for ship movement 
		// entities that move beyond the edges of the screen 
		// plus this amount are recycled (destroyed for reuse) 
		public var cullingDistance:Number = 200; 
		 
		// a particle system class that updates our sprites 
		public var particles:GameParticles; 
		 
		// so that explosions can be played 
		public var sfx:GameSound; 
		 
		// the sprite sheet image 
		public var spriteSheet : LiteSpriteSheet; 
		public var SpritesPerRow:int = 8; 
		public var SpritesPerCol:int = 8; 
		// we no longer force a particular spritesheet here 
		//[Embed(source="../assets/sprites.png")] 
		//private var SourceImage : Class; 
		public var SourceImage : Class; 
 
		// the general size of the player and enemies 
		public var defaultScale:Number = 1; 
		// how fast the default scroll (enemy flying) speed is 
		public var defaultSpeed:Number = 128; 
		// how fast player bullets go per second 
		public var bulletSpeed:Number = 250; 
 
		// for framerate-independent timings 
		public var currentFrameSeconds:Number = 0; 
		 
		// sprite IDs (indexing the spritesheet) 
		public const spritenumFireball:uint = 63; 
		public const spritenumFireburst:uint = 62; 
		public const spritenumShockwave:uint = 61; 
		public const spritenumDebris:uint = 60; 
		public const spritenumSpark:uint = 59; 
		public const spritenumBullet3:uint = 58; 
		public const spritenumBullet2:uint = 57; 
		public const spritenumBullet1:uint = 56; 
		public const spritenumPlayer:uint = 10; 
		public const spritenumOrb:uint = 17; 
 
		// reused for calculation speed 
		public const DEGREES_TO_RADIANS:Number = Math.PI / 180; 
		public const RADIANS_TO_DEGREES:Number = 180 / Math.PI; 
		 
		// the player entity - a special case 
		public var thePlayer:Entity; 
		// a "power orb" that orbits the player 
		public var theOrb:Entity; 
		 
		// a reusable pool of entities 
		// this contains every known Entity 
		// including the contents of the lists below 
		public var entityPool : Vector.<Entity>; 
		// these pools contain only certain types 
		// of entity as an optimization for smaller loops  
		public var allBullets : Vector.<Entity>; 
		public var allEnemies : Vector.<Entity>; 
		 
		// all the polygons that make up the scene 
		public var batch : LiteSpriteBatch; 
		 
		// for statistics 
		public var numCreated : int = 0; 
		public var numReused : int = 0; 
		 
		public var maxX:int; 
		public var minX:int; 
		public var maxY:int; 
		public var minY:int; 
		public var midpoint:int;

Step 13: Upgrade the Inits

We need to upgrade our entity manager's class constructor to create an instance of the game level data parser class we wrote above. Additionally, we want to store the midpoint of the screen for use as the starting playing position and extend the minimum and maximum sprite locations whenever the game is resized. Continuing with EntityManager.as, upgrade the following.

	 
		public function EntityManager(view:Rectangle) 
		{ 
			entityPool = new Vector.<Entity>(); 
			allBullets = new Vector.<Entity>(); 
			allEnemies = new Vector.<Entity>(); 
			particles = new GameParticles(this); 
			setPosition(view);	 
			level = new GameLevels(); 
		} 
		 
		public function setPosition(view:Rectangle):void  
		{ 
			// allow moving fully offscreen before 
			// automatically being culled (and reused) 
			maxX = view.width + cullingDistance; 
			minX = view.x - cullingDistance; 
			maxY = view.height + cullingDistance; 
			minY = view.y - cullingDistance; 
			midpoint = view.height / 2; 
		} 
		 
		// this XOR based fast random number generator runs 4x faster 
		// than Math.random() and also returns a number from 0 to 1 
		// see http://www.calypso88.com/?cat=7 
		private const FASTRANDOMTOFLOAT:Number = 1 / uint.MAX_VALUE; 
		private var fastrandomseed:uint = Math.random() * uint.MAX_VALUE; 
		public function fastRandom():Number 
		{ 
			fastrandomseed ^= (fastrandomseed << 21); 
			fastrandomseed ^= (fastrandomseed >>> 35); 
			fastrandomseed ^= (fastrandomseed << 4); 
			return (fastrandomseed * FASTRANDOMTOFLOAT); 
		}

Step 14: Account for UV Padding

There is one special tweak that is required for our createBatch function. It turns out that the terrain spritesheet, which used tiled sprites that are right next to each other and doesn't include any empty space between tiles, can produce visual glitches on our game if used as-is. This is due to the way your video card's GPU samples each texture in the sprite batch when it renders all the sprites. Here's an example of our terrain being rendered using the routines from last week:


What is happening in example #1 is that the edge pixels of tiles can "bleed through" to adjascent tiles due to bilinear interpolation of the RGB values. To account for this, we need to allow for a small texture coordinate (UV) offset value, which will "zoom in" each tile by just a minuscule amount. Without this change, the game would have artifacts as seen above.

 
		public function createBatch(context3D:Context3D, uvPadding:Number=0) : LiteSpriteBatch  
		{ 
			var sourceBitmap:Bitmap = new SourceImage(); 
 
			// create a spritesheet with 8x8 (64) sprites on it 
			spriteSheet = new LiteSpriteSheet(sourceBitmap.bitmapData, SpritesPerRow, SpritesPerCol, uvPadding); 
			 
			// Create new render batch  
			batch = new LiteSpriteBatch(context3D, spriteSheet); 
			 
			return batch; 
		}

Step 15: Spawning Routines

The following routines are virtually identical to last week's apart from the use of the midpoint value in the player spawning and some size differences. They are included here for completeness.

Finally, the addRandomEntity function as defined below is what in previous versions was the addEntities function. It is not used in this demo and could be deleted, since we are changing our game to no longer use randomly-spawned enemies and are instead switching to hand-crafted levels. This function might come handy in your testing to account for time when there is no remaining level data. You can simply copy and paste this code over top of your original routines and move on without taking a deeper look.

 
		 
		// search the entity pool for unused entities and reuse one 
		// if they are all in use, create a brand new one 
		public function respawn(sprID:uint=0):Entity 
		{ 
			var currentEntityCount:int = entityPool.length; 
			var anEntity:Entity; 
			var i:int = 0; 
			// search for an inactive entity 
			for (i = 0; i < currentEntityCount; i++ )  
			{ 
				anEntity = entityPool[i]; 
				if (!anEntity.active && (anEntity.sprite.spriteId == sprID)) 
				{ 
					//trace('Reusing Entity #' + i); 
					anEntity.active = true; 
					anEntity.sprite.visible = true; 
					anEntity.recycled = true; 
					numReused++; 
					return anEntity; 
				} 
			} 
			// none were found so we need to make a new one 
			//trace('Need to create a new Entity #' + i); 
			var sprite:LiteSprite; 
			sprite = batch.createChild(sprID); 
			anEntity = new Entity(sprite, this); 
			entityPool.push(anEntity); 
			numCreated++; 
			return anEntity; 
		} 
		 
		// this entity is the PLAYER 
		public function addPlayer(playerController:Function):Entity  
		{ 
			trace("Adding Player Entity"); 
			thePlayer = respawn(spritenumPlayer); 
			thePlayer.sprite.position.x = 64; 
			thePlayer.sprite.position.y = midpoint; 
			thePlayer.sprite.rotation = 180 * DEGREES_TO_RADIANS; 
			thePlayer.sprite.scaleX = thePlayer.sprite.scaleY = defaultScale;  
			thePlayer.speedX = 0; 
			thePlayer.speedY = 0; 
			thePlayer.active = true; 
			thePlayer.collidemode = 1; 
			thePlayer.collideradius = 10; 
			thePlayer.owner = thePlayer; // collisions require this 
			thePlayer.aiFunction = playerController; 
			 
			// just for fun, spawn an orbiting "power orb" 
			theOrb = respawn(spritenumOrb); 
			theOrb.rotationSpeed = 720 * DEGREES_TO_RADIANS; 
			theOrb.sprite.scaleX = theOrb.sprite.scaleY = defaultScale / 2; 
			theOrb.leavesTrail = true; 
			theOrb.collidemode = 1; 
			theOrb.collideradius = 12; 
			theOrb.isBullet = true; 
			theOrb.owner = thePlayer; 
			theOrb.orbiting = thePlayer; 
			theOrb.orbitingDistance = 180; 
			 
			return thePlayer; 
		}		 
 
		// shoot a bullet 
		public function shootBullet(powa:uint=1, shooter:Entity = null):Entity  
		{ 
			// just in case the AI is running during the main menu 
			// and we've not yet created the player entity 
			if (thePlayer == null) return null; 
 
			var theBullet:Entity; 
			// assume the player shot it 
			// otherwise maybe an enemy did 
			if (shooter == null)  
				shooter = thePlayer; 
				 
			// three possible bullets, progressively larger 
			if (powa == 1)  
				theBullet = respawn(spritenumBullet1); 
			else if (powa == 2)  
				theBullet = respawn(spritenumBullet2); 
			else  
				theBullet = respawn(spritenumBullet3); 
			theBullet.sprite.position.x = shooter.sprite.position.x + 8; 
			theBullet.sprite.position.y = shooter.sprite.position.y + 2; 
			theBullet.sprite.rotation = 180 * DEGREES_TO_RADIANS; 
			theBullet.sprite.scaleX = theBullet.sprite.scaleY = 1;  
			if (shooter == thePlayer) 
			{ 
				theBullet.speedX = bulletSpeed; 
				theBullet.speedY = 0; 
			} 
			else // enemy bullets move slower and towards the player 
			{ 
				theBullet.sprite.rotation =  
					pointAtRad(theBullet.sprite.position.x - thePlayer.sprite.position.x, 
						theBullet.sprite.position.y-thePlayer.sprite.position.y) - (90*DEGREES_TO_RADIANS); 
				 
				// move in the direction we're facing 
				theBullet.speedX = defaultSpeed*1.5*Math.cos(theBullet.sprite.rotation); 
				theBullet.speedY = defaultSpeed*1.5*Math.sin(theBullet.sprite.rotation); 
    
				// optionally, we could just fire straight ahead in the direction we're heading: 
				// theBullet.speedX = shooter.speedX * 1.5; 
				// theBullet.speedY = shooter.speedY * 1.5; 
				// and we could point where we're going like this: 
				// pointAtRad(theBullet.speedX,theBullet.speedY) - (90*DEGREES_TO_RADIANS); 
			} 
			theBullet.owner = shooter; 
			theBullet.collideradius = 10; 
			theBullet.collidemode = 1; 
			theBullet.isBullet = true; 
			if (!theBullet.recycled) 
				allBullets.push(theBullet); 
			return theBullet; 
		}		 
 
		// Unused: this was "addEntities()" in the previous tutorials. 
		// It spawns random enemies that move in a straight line 
		public function addRandomEntity():void 
		{ 
			var anEntity:Entity; 
			var sprID:int; 
			sprID = Math.floor(fastRandom() * 55); 
			// try to reuse an inactive entity (or create a new one) 
			anEntity = respawn(sprID); 
			// give it a new position and velocity 
			anEntity.sprite.position.x = maxX; 
			anEntity.sprite.position.y = fastRandom() * maxY; 
			anEntity.speedX = 15 * ((-1 * fastRandom() * 10) - 2); 
			anEntity.speedY = 15 * ((fastRandom() * 5) - 2.5); 
			anEntity.sprite.scaleX = defaultScale; 
			anEntity.sprite.scaleY = defaultScale; 
			anEntity.sprite.rotation = pointAtRad(anEntity.speedX,anEntity.speedY) - (90*DEGREES_TO_RADIANS); 
			anEntity.collidemode = 1; 
			anEntity.collideradius = 16; 
			if (!anEntity.recycled) 
				allEnemies.push(anEntity); 
		} 
		 
		// returns the angle in radians of two points 
		public function pointAngle(point1:Point, point2:Point):Number 
		{ 
			var dx:Number = point2.x - point1.x; 
			var dy:Number = point2.y - point1.y; 
			return -Math.atan2(dx,dy); 
		}		 
		 
		// returns the angle in degrees of 0,0 to x,y 
		public function pointAtDeg(x:Number, y:Number):Number 
		{ 
			return -Math.atan2(x,y) * RADIANS_TO_DEGREES; 
		}		 
 
		// returns the angle in radians of 0,0 to x,y 
		public function pointAtRad(x:Number, y:Number):Number 
		{ 
			return -Math.atan2(x,y); 
		}		 
 
		// as an optimization to saver millions of checks, only 
		// the player's bullets check for collisions with all enemy ships 
		// (enemy bullets only check to hit the player) 
		public function checkCollisions(checkMe:Entity):Entity 
		{ 
			var anEntity:Entity; 
			var collided:Boolean = false; 
			if (checkMe.owner != thePlayer) 
			{	// quick check ONLY to see if we have hit the player 
				anEntity = thePlayer; 
				if (checkMe.colliding(anEntity))  
				{ 
					trace("Player was HIT!"); 
					collided = true; 
				} 
			} 
			else // check all active enemies 
			{ 
				for(var i:int=0; i< allEnemies.length;i++) 
				{ 
					anEntity = allEnemies[i]; 
					if (anEntity.active && anEntity.collidemode) 
					{ 
						if (checkMe.colliding(anEntity))  
						{ 
							collided = true; 
							break; 
						} 
					} 
				} 
			} 
			if (collided) 
			{ 
				//trace('Collision!'); 
				if (sfx) sfx.playExplosion(int(fastRandom() * 2 + 1.5)); 
				particles.addExplosion(checkMe.sprite.position); 
				if ((checkMe != theOrb) && (checkMe != thePlayer))  
					checkMe.die(); // the bullet 
				if ((anEntity != theOrb) && ((anEntity != thePlayer)))  
					anEntity.die(); // the victim 
				return anEntity; 
			} 
			return null; 
		}

Step 16: Upgrade the Render Loop

The update() function is run every single frame, just as before. Several modifications have been made to account for out new enemy AI functionality that we added to the entity class above, as well as our new level data parsing functionality.

For example, last week we only ran the entity simulation update step if there wasn't an aiFunction defined. Now, we will be calling this function on almost every game entity that moves, so we run it and then continue with the standard animation by checking the speeds of various entity parameters. We also used to only check for collisions by bullets, but now an enemy ship can collide with the player as well.

Continuing with EntityManager.as, implement these changes as follows.

		 
		 
		// called every frame: used to update the simulation 
		// this is where you would perform AI, physics, etc. 
		// in this version, currentTime is seconds since the previous frame 
		public function update(currentTime:Number) : void 
		{		 
			var anEntity:Entity; 
			var i:int; 
			var max:int; 
			 
			// what portion of a full second has passed since the previous update? 
			currentFrameSeconds = currentTime / 1000; 
			 
			// handle all other entities 
			max = entityPool.length; 
			for (i = 0; i < max; i++) 
			{ 
				anEntity = entityPool[i]; 
				if (anEntity.active) 
				{ 
					// subtract the previous aiPathOffset 
					anEntity.sprite.position.x -= anEntity.aiPathOffsetX; 
					anEntity.sprite.position.y -= anEntity.aiPathOffsetY; 
 
					// calculate location on screen with scrolling 
					anEntity.sprite.position.x += anEntity.speedX * currentFrameSeconds; 
					anEntity.sprite.position.y += anEntity.speedY * currentFrameSeconds; 
										 
					// is a custom AI specified? if so, run it now 
					if (anEntity.aiFunction != null) 
					{ 
						anEntity.aiFunction(currentFrameSeconds); 
					} 
 
					// add the new aiPathOffset 
					anEntity.sprite.position.x += anEntity.aiPathOffsetX; 
					anEntity.sprite.position.y += anEntity.aiPathOffsetY; 
					 
					// collision detection 
					if (anEntity.collidemode)  
					{ 
						checkCollisions(anEntity); 
					} 
					 
					// entities can orbit other entities  
					// (uses their rotation as the position) 
					if (anEntity.orbiting != null) 
					{ 
						anEntity.sprite.position.x = anEntity.orbiting.sprite.position.x +  
							((Math.sin(anEntity.sprite.rotation/4)/Math.PI) * anEntity.orbitingDistance); 
						anEntity.sprite.position.y = anEntity.orbiting.sprite.position.y -  
							((Math.cos(anEntity.sprite.rotation/4)/Math.PI) * anEntity.orbitingDistance); 
					} 
 
					// entities can leave an engine emitter trail 
					if (anEntity.leavesTrail) 
					{ 
						// leave a trail of particles 
						if (anEntity == theOrb) 
							particles.addParticle(63,  
							anEntity.sprite.position.x, anEntity.sprite.position.y,  
							0.25, 0, 0, 0.6, NaN, NaN, -1.5, -1); 
						else // other enemies 
							particles.addParticle(63, anEntity.sprite.position.x + 12,  
							anEntity.sprite.position.y + 2,  
							0.5, 3, 0, 0.6, NaN, NaN, -1.5, -1); 
						 
					} 
					 
					if ((anEntity.sprite.position.x > maxX) || 
						(anEntity.sprite.position.x < minX) || 
						(anEntity.sprite.position.y > maxY) || 
						(anEntity.sprite.position.y < minY))							 
					{ 
						// if we go past any edge, become inactive 
						// so the sprite can be respawned 
						if ((anEntity != thePlayer) && (anEntity != theOrb))  
							anEntity.die(); 
					} 
					 
					if (anEntity.rotationSpeed != 0) 
						anEntity.sprite.rotation += anEntity.rotationSpeed * currentFrameSeconds; 
						 
					if (anEntity.fadeAnim != 0) 
					{ 
						anEntity.sprite.alpha += anEntity.fadeAnim * currentFrameSeconds; 
						if (anEntity.sprite.alpha <= 0.001) 
						{ 
							anEntity.die(); 
						} 
						else if (anEntity.sprite.alpha > 1) 
						{ 
							anEntity.sprite.alpha = 1; 
						} 
					} 
					if (anEntity.zoomAnim != 0) 
					{ 
						anEntity.sprite.scaleX += anEntity.zoomAnim * currentFrameSeconds; 
						anEntity.sprite.scaleY += anEntity.zoomAnim * currentFrameSeconds; 
						if (anEntity.sprite.scaleX < 0 || anEntity.sprite.scaleY < 0) 
							anEntity.die(); 
					} 
				} 
			} 
		}

Step 17: Switching Levels

The remaining functions in EntityManager.as are brand new. We need a mechanism to instantly destroy all known entities in an entire game world. This will happen whenever the player goes to the next level. It also occurs immediately when the game leaves the attract mode "main menu" so that sprites that were there don't pollute the player's actual game world. When the game starts, we will parse the next set of level data as well.

 
		// kill (recycle) all known entities 
		// this is run when we change levels 
		public function killEmAll():void 
		{ 
			//trace('Killing all entities...'); 
			var anEntity:Entity; 
			var i:int; 
			var max:int; 
			max = entityPool.length; 
			for (i = 0; i < max; i++) 
			{ 
				anEntity = entityPool[i]; 
				if ((anEntity != thePlayer) && (anEntity != theOrb)) 
					anEntity.die(); 
			} 
		} 
		 
		// load a new level for entity generation 
		public function changeLevels(lvl:String):void 
		{ 
			killEmAll(); 
			level.loadLevel(lvl); 
			levelCurrentScrollX = 0; 
			levelPrevCol = -1; 
		}

Step 18: Streaming the Level

The final function we need to add to our entity manager is the one that spawns new entities based on the level data. It measures the distance we have travelled, and when the next set of level tiles is requires it spawns another column of entities as specified by the level data. If the entity manager running this routine is in charge of the terrain, nothing more needs to be done, but if we are spawning enemy ships, asteroids, and sentry guns, we need to decide which kind of AI routine to give each entity.

One important consideration relates to the terrain glitches as illustrated in the image above that showed "seams" between tiles.


In the first few versions of this function, we simply measured the distance travelled based on time elapsed each frame and incremented a counter variable, spawning the next row of tiles when needed. The problem with this approach is that floating point numbers (anything with a decimal point) are not 100% accurate. Since we can only store so much information in a Number type, some really small amounts are rounded off.

This is imperceptable in most situations, but over time the slight discrepancies add up until eventually the terrain tiles are off by a pixel. Therefore, we keep track of the previous column's terrain tiles and force the next to be exactly the correct distance from it. We simply can't assume that the terrain has scrolled exactly 48 pixels since the last time we spawned tiles. It may have moved 48.00000000001 pixels.

You can read more about the many problems that floating-point accumulators can produce in games in this very interesting article.

		 
		// check to see if another row from the level data should be spawned  
		public function streamLevelEntities(theseAreEnemies:Boolean = false):void  
		{ 
			var anEntity:Entity; 
			var sprID:int; 
			// time-based with overflow remembering (increment and floor) 
			levelCurrentScrollX += defaultSpeed * currentFrameSeconds; 
			// is it time to spawn the next col from our level data? 
			if (levelCurrentScrollX >= levelTilesize) 
			{ 
				levelCurrentScrollX = 0; 
				levelPrevCol++; 
				 
				// this prevents small "seams" due to floating point inaccuracies over time 
				var currentLevelXCoord:Number; 
				if (lastTerrainEntity && !theseAreEnemies)  
					currentLevelXCoord = lastTerrainEntity.sprite.position.x + levelTilesize; 
				else 
					currentLevelXCoord = maxX; 
				 
				var rows:int = level.data.length; 
				//trace('levelCurrentScrollX = ' + levelCurrentScrollX +  
				//' - spawning next level column ' + levelPrevCol + ' row count: ' + rows); 
								 
				if (level.data && level.data.length) 
				{ 
					for (var row:int = 0; row < rows; row++) 
					{ 
						if (level.data[row].length > levelPrevCol) // data exists? NOP? 
						{ 
							//trace('Next row data: ' + String(level.data[row])); 
							sprID = level.data[row][levelPrevCol]; 
							if (sprID > -1) // zero is a valid number, -1 means blank 
							{ 
								anEntity = respawn(sprID); 
								anEntity.sprite.position.x = currentLevelXCoord; 
								anEntity.sprite.position.y = (row * levelTilesize) + (levelTilesize/2); 
								trace('Spawning a level sprite ID ' + sprID + ' at '  
									+ anEntity.sprite.position.x + ',' + anEntity.sprite.position.y); 
								anEntity.speedX = -defaultSpeed; 
								anEntity.speedY = 0; 
								anEntity.sprite.scaleX = defaultScale; 
								anEntity.sprite.scaleY = defaultScale;

Step 19: Give the Enemies Brains

Continuing with the streamLevelEntities function, we simply need to choose which kind of AI to use for each newly spawned enemy (if any). For reference, this is the spritesheet we are using:


The enemy spritesheet has been split into rows. The first row of sprites simply moves forward in a straight line at a random angle. The second row uses our newly created sinusoidal "wave like" movement which ponting in a straight line. We account for the two sentry gun tiles and three asteroid images as a special case. The next rows move at a random angle with a wobble, and finally, all the remaining sprites will use our random Catmull-Rom spline curve movement.

 
								if (theseAreEnemies) 
								{ 
									// which AI should we give this enemy? 
									switch (sprID) 
									{ 
										case 1: 
										case 2: 
										case 3: 
										case 4: 
										case 5: 
										case 6: 
										case 7: 
											// move forward at a random angle 
											anEntity.speedX = 15 * ((-1 * fastRandom() * 10) - 2); 
											anEntity.speedY = 15 * ((fastRandom() * 5) - 2.5); 
											anEntity.aiFunction = anEntity.straightAI; 
											break; 
										case 8: 
										case 9: 
										case 10: 
										case 11: 
										case 12: 
										case 13: 
										case 14: 
										case 15: 
											// move straight with a wobble 
											anEntity.aiFunction = anEntity.wobbleAI; 
											break 
										case 16: 
										case 24: // sentry guns don't move and always look at the player 
											anEntity.aiFunction = anEntity.sentryAI; 
											anEntity.speedX = -90; // same speed as background 
											break; 
										case 17: 
										case 18: 
										case 19: 
										case 20: 
										case 21: 
										case 22: 
										case 23: 
											// move at a random angle with a wobble 
											anEntity.speedX = 15 * ((-1 * fastRandom() * 10) - 2); 
											anEntity.speedY = 15 * ((fastRandom() * 5) - 2.5); 
											anEntity.aiFunction = anEntity.wobbleAI; 
											break; 
										case 32: 
										case 40: 
										case 48: // asteroids don't move or shoot but they do spin and drift 
											anEntity.aiFunction = null; 
											anEntity.rotationSpeed = fastRandom() * 8 - 4 
											anEntity.speedY = fastRandom() * 64 - 32; 
											break; 
										default: // follow a complex random spline curve path 
											anEntity.aiFunction = anEntity.droneAI; 
											break; 
									} 
									 
									anEntity.sprite.rotation = pointAtRad(anEntity.speedX, anEntity.speedY) 
										- (90*DEGREES_TO_RADIANS); 
									anEntity.collidemode = 1; 
									anEntity.collideradius = 16; 
									if (!anEntity.recycled) 
										allEnemies.push(anEntity); 
								} // end if these were enemies 
							}// end loop for level data rows 
						} 
					} 
				} 
				// remember the last created terrain entity 
				// (might be null if the level data was blank for this column) 
				// to avoid slight seams due to terrain scrolling speed over time 
				if (!theseAreEnemies) lastTerrainEntity = anEntity; 
			} 
		} 
	} // end class 
} // end package

That's it for our newly upgraded entity manager class. It now takes advantage of our "streaming" terrain, gives enemies the appropriate AI, and no longer simply spawns infinite random streams of baddies.


Step 20: Account for UV Padding

In our upgrades above, we avoided small graphical glitches by accounting for two things: floating-point imprecision and texture sampling interpolation, which causes bleeding of edge pixels into adjascent terrain tiles. The latter required that we "zoom in" the terrain tiles just a tiny bit to ensure that the edges look right. We need to upgrade our existing LiteSpriteSheet.as class to account for this small offset when creating all the UV texture coordinates for each sprite.

 
// Stage3D Shoot-em-up Tutorial Part 4 
// by Christer Kaitila - www.mcfunkypants.com 
 
// LiteSpriteSheet.as 
// An optimization used to improve performance, all sprites used 
// in the game are packed onto a single texture so that 
// they can be rendered in a single pass rather than individually. 
// This also avoids the performance penalty of 3d stage changes. 
// Based on example code by Chris Nuuja which is a port 
// of the haXe+NME bunnymark demo by Philippe Elsass 
// which is itself a port of Iain Lobb's original work. 
// Also includes code from the Starling framework. 
// Grateful acknowledgements to all involved. 
 
package 
{ 
    import flash.display.Bitmap; 
    import flash.display.BitmapData; 
    import flash.display.Stage; 
    import flash.display3D.Context3D; 
    import flash.display3D.Context3DTextureFormat; 
    import flash.display3D.IndexBuffer3D; 
    import flash.display3D.textures.Texture; 
    import flash.geom.Point; 
    import flash.geom.Rectangle; 
    import flash.geom.Matrix; 
     
    public class LiteSpriteSheet 
    { 
        internal var _texture : Texture; 
         
        protected var _spriteSheet : BitmapData;     
        protected var _uvCoords : Vector.<Number>; 
        protected var _rects : Vector.<Rectangle>; 
		 
		// because the edge pixels of some sprites are bleeding through, 
		// we zoom in the texture just the slightest bit for terrain tiles 
		public var uvPadding:Number = 0; // 0.01; 
         
        public function LiteSpriteSheet(SpriteSheetBitmapData:BitmapData, numSpritesW:int = 8, numSpritesH:int = 8, uvPad:Number = 0) 
        { 
            _uvCoords = new Vector.<Number>(); 
            _rects = new Vector.<Rectangle>(); 
			_spriteSheet = SpriteSheetBitmapData; 
			uvPadding = uvPad; 
			createUVs(numSpritesW, numSpritesH); 
		} 
 
        // generate a list of uv coordinates for a grid of sprites 
		// on the spritesheet texture for later reference by ID number 
		// sprite ID numbers go from left to right then down 
		public function createUVs(numSpritesW:int, numSpritesH:int) : void 
        { 
			trace('creating a '+_spriteSheet.width+'x'+_spriteSheet.height+ 
				' spritesheet texture with '+numSpritesW+'x'+ numSpritesH+' sprites.'); 
	 
			var destRect : Rectangle; 
	 
			for (var y:int = 0; y < numSpritesH; y++) 
			{ 
				for (var x:int = 0; x < numSpritesW; x++) 
				{ 
					_uvCoords.push( 
						// bl, tl, tr, br	 
						(x / numSpritesW) + uvPadding, ((y+1) / numSpritesH) - uvPadding, 
						(x / numSpritesW) + uvPadding, (y / numSpritesH) + uvPadding, 
						((x+1) / numSpritesW) - uvPadding, (y / numSpritesH) + uvPadding, 
						((x + 1) / numSpritesW) - uvPadding, ((y + 1) / numSpritesH) - uvPadding); 
						 
					    destRect = new Rectangle(); 
						destRect.left = 0; 
						destRect.top = 0; 
						destRect.right = _spriteSheet.width / numSpritesW; 
						destRect.bottom = _spriteSheet.height / numSpritesH; 
						_rects.push(destRect);					 
				} 
			} 
        } 
 
		// when the automated grid isn't what we want 
		// we can define any rectangle and return a new sprite ID 
		public function defineSprite(x:uint, y:uint, w:uint, h:uint) : uint 
		{ 
			var destRect:Rectangle = new Rectangle(); 
			destRect.left = x; 
			destRect.top = y; 
			destRect.right = x + w; 
			destRect.bottom = y + h; 
			_rects.push(destRect); 
				 
			_uvCoords.push( 
                destRect.x/_spriteSheet.width, destRect.y/_spriteSheet.height + destRect.height/_spriteSheet.height, 
                destRect.x/_spriteSheet.width, destRect.y/_spriteSheet.height, 
                destRect.x/_spriteSheet.width + destRect.width/_spriteSheet.width, destRect.y/_spriteSheet.height, 
                destRect.x/_spriteSheet.width + destRect.width/_spriteSheet.width, destRect.y/_spriteSheet.height + destRect.height/_spriteSheet.height);				 
			 
			return _rects.length - 1; 
		} 
		 
        public function removeSprite(spriteId:uint) : void 
        { 
            if ( spriteId < _uvCoords.length ) { 
                _uvCoords = _uvCoords.splice(spriteId * 8, 8); 
                _rects.splice(spriteId, 1); 
            } 
        } 
 
        public function get numSprites() : uint 
        { 
            return _rects.length; 
        } 
 
        public function getRect(spriteId:uint) : Rectangle 
        { 
            return _rects[spriteId]; 
        } 
         
        public function getUVCoords(spriteId:uint) : Vector.<Number> 
        { 
            var startIdx:uint = spriteId * 8; 
            return _uvCoords.slice(startIdx, startIdx + 8); 
        } 
         
        public function uploadTexture(context3D:Context3D) : void 
        { 
            if ( _texture == null ) { 
                _texture = context3D.createTexture(_spriteSheet.width, _spriteSheet.height, Context3DTextureFormat.BGRA, false); 
            } 
  
            _texture.uploadFromBitmapData(_spriteSheet); 
             
            // generate mipmaps 
            var currentWidth:int = _spriteSheet.width >> 1; 
            var currentHeight:int = _spriteSheet.height >> 1; 
            var level:int = 1; 
            var canvas:BitmapData = new BitmapData(currentWidth, currentHeight, true, 0); 
            var transform:Matrix = new Matrix(.5, 0, 0, .5); 
             
            while ( currentWidth >= 1 || currentHeight >= 1 ) { 
                canvas.fillRect(new Rectangle(0, 0, Math.max(currentWidth,1), Math.max(currentHeight,1)), 0); 
                canvas.draw(_spriteSheet, transform, null, null, null, true); 
                _texture.uploadFromBitmapData(canvas, level++); 
                transform.scale(0.5, 0.5); 
                currentWidth = currentWidth >> 1; 
                currentHeight = currentHeight >> 1; 
            } 
        } 
    } // end class 
} // end package

As you can see, the only changes above are related to the uvPadding parameter in the class constructor for each spritesheet.


Step 21: Final Upgrades!

We're nearly done! All we need to do now is upgrade the existing Main.as in our project to account for the various minor changes to the way we create new instances of our entity manager and their spritesheets. The changes to this file are trivial, but it is included here in full to avoid confusion.

The primary differences include the fact that we are now embedding the two main spritesheets here rather than in the entity manager, the addition of a terrain layer, dealing with two different scrolling speeds (since we want the terrain to move slower than the enemies in the foreground, and triggering the new levels to be loaded.

 
// Stage3D Shoot-em-up Tutorial Part 4 
// by Christer Kaitila - www.mcfunkypants.com 
// Created for active.tutsplus.com 
 
package  
{ 
	[SWF(width = "600", height = "400", frameRate = "60", backgroundColor = "#000000")] 
 
	import flash.display3D.*; 
	import flash.display.Sprite; 
	import flash.display.StageAlign; 
	import flash.display.StageQuality; 
	import flash.display.StageScaleMode; 
	import flash.events.Event; 
	import flash.events.ErrorEvent; 
	import flash.events.MouseEvent; 
	import flash.geom.Rectangle; 
	import flash.utils.getTimer; 
		 
	public class Main extends Sprite  
	{ 
		// the entity spritesheet (ships, particles) 
		[Embed(source="../assets/sprites.png")] 
		private var EntitySourceImage : Class; 
 
		// the terrain spritesheet 
		[Embed(source="../assets/terrain.png")] 
		private var TerrainSourceImage : Class; 
		 
		// the keyboard control system 
		private var _controls : GameControls; 
		// don't update the menu too fast 
		private var nothingPressedLastFrame:Boolean = false; 
		// timestamp of the current frame 
		public var currentTime:int; 
		// for framerate independent speeds 
		public var currentFrameMs:int; 
		public var previousFrameTime:int; 
		 
		// player one's entity 
		public var thePlayer:Entity; 
		// movement speed in pixels per second 
		public var playerSpeed:Number = 128; 
		// timestamp when next shot can be fired 
		private var nextFireTime:uint = 0; 
		// how many ms between shots 
		private var fireDelay:uint = 200; 
		 
		// main menu = 0 or current level number 
		private var _state : int = 0; 
		// the title screen batch 
		private var _mainmenu : GameMenu; 
		// the sound system 
		private var _sfx : GameSound;	 
		// the background stars 
		private var _bg : GameBackground;	 
		 
		private var _terrain : EntityManager; 
		private var _entities : EntityManager; 
		private var _spriteStage : LiteSpriteStage; 
		private var _gui : GameGUI; 
		private var _width : Number = 600; 
		private var _height : Number = 400; 
		public var context3D : Context3D; 
		 
		// constructor function for our game 
		public function Main():void  
		{ 
			if (stage) init(); 
			else addEventListener(Event.ADDED_TO_STAGE, init); 
		} 
		 
		// called once flash is ready 
		private function init(e:Event = null):void  
		{ 
			_controls = new GameControls(stage); 
			removeEventListener(Event.ADDED_TO_STAGE, init); 
			stage.quality = StageQuality.LOW; 
			stage.align = StageAlign.TOP_LEFT; 
			stage.scaleMode = StageScaleMode.NO_SCALE; 
			stage.addEventListener(Event.RESIZE, onResizeEvent); 
			trace("Init Stage3D..."); 
			_gui = new GameGUI("Stage3D Shoot-em-up Tutorial Part 3"); 
			addChild(_gui); 
			stage.stage3Ds[0].addEventListener(Event.CONTEXT3D_CREATE, onContext3DCreate); 
			stage.stage3Ds[0].addEventListener(ErrorEvent.ERROR, errorHandler); 
			stage.stage3Ds[0].requestContext3D(Context3DRenderMode.AUTO); 
			trace("Stage3D requested...");		 
			_sfx = new GameSound(); 
		} 
				 
		// this is called when the 3d card has been set up 
		// and is ready for rendering using stage3d 
		private function onContext3DCreate(e:Event):void  
		{ 
			trace("Stage3D context created! Init sprite engine..."); 
			context3D = stage.stage3Ds[0].context3D; 
			initSpriteEngine(); 
		} 
		 
		// this can be called when using an old version of flash 
		// or if the html does not include wmode=direct 
		private function errorHandler(e:ErrorEvent):void  
		{ 
			trace("Error while setting up Stage3D: "+e.errorID+" - " +e.text); 
		} 
 
		protected function onResizeEvent(event:Event) : void 
		{ 
			trace("resize event..."); 
			 
			// Set correct dimensions if we resize 
			_width = stage.stageWidth; 
			_height = stage.stageHeight; 
			 
			// Resize Stage3D to continue to fit screen 
			var view:Rectangle = new Rectangle(0, 0, _width, _height); 
			if ( _spriteStage != null ) { 
				_spriteStage.position = view; 
			} 
			if(_terrain != null) { 
				_terrain.setPosition(view); 
			} 
			if(_entities != null) { 
				_entities.setPosition(view); 
			} 
			if(_mainmenu != null) { 
				_mainmenu.setPosition(view); 
			} 
		} 
		 
		private function initSpriteEngine():void  
		{ 
			// init a gpu sprite system 
			//var view:Rectangle = new Rectangle(0,0,_width,_height) 
			var stageRect:Rectangle = new Rectangle(0, 0, _width, _height);  
			_spriteStage = new LiteSpriteStage(stage.stage3Ds[0], context3D, stageRect); 
			_spriteStage.configureBackBuffer(_width,_height); 
			 
			// create the background stars 
			trace("Init background..."); 
			_bg = new GameBackground(stageRect); 
			_bg.createBatch(context3D); 
			_spriteStage.addBatch(_bg.batch); 
			_bg.initBackground(); 
			 
			// create the terrain spritesheet and batch 
			trace("Init Terrain..."); 
			_terrain = new EntityManager(stageRect); 
			_terrain.SourceImage = TerrainSourceImage; 
			_terrain.SpritesPerRow = 16; 
			_terrain.SpritesPerCol = 16; 
			_terrain.defaultSpeed = 90; 
			_terrain.defaultScale = 1.5; 
			_terrain.levelTilesize = 48;  
			_terrain.createBatch(context3D, 0.001); // a little UV padding required 
			_spriteStage.addBatch(_terrain.batch); 
			_terrain.level.loadLevel('terrain0'); // demo level NOW 
 
			// create a single rendering batch 
			// which will draw all sprites in one pass 
			trace("Init Entities..."); 
			_entities = new EntityManager(stageRect); 
			_entities.SourceImage = EntitySourceImage; 
			_entities.defaultScale = 1.5; // 1 
			_entities.levelTilesize = 48;  
			_entities.createBatch(context3D); 
			_entities.sfx = _sfx; 
			_spriteStage.addBatch(_entities.batch); 
			_entities.level.loadLevel('level0'); // demo level NOW 
			_entities.streamLevelEntities(true); // spawn first row of the level immediately 
			 
			// create the logo/titlescreen main menu 
			_mainmenu = new GameMenu(stageRect); 
			_mainmenu.createBatch(context3D); 
			_spriteStage.addBatch(_mainmenu.batch); 
			 
			// tell the gui where to grab statistics from 
			_gui.statsTarget = _entities;  
			 
			// start the render loop 
			stage.addEventListener(Event.ENTER_FRAME,onEnterFrame); 
 
			// only used for the menu 
			stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);    
			stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);  
		} 
		 
		public function playerLogic(seconds:Number):void 
		{ 
			var me:Entity = _entities.thePlayer; 
			me.speedY = me.speedX = 0; 
			if (_controls.pressing.up) 
				me.speedY = -playerSpeed; 
			if (_controls.pressing.down) 
				me.speedY = playerSpeed; 
			if (_controls.pressing.left) 
				me.speedX = -playerSpeed; 
			if (_controls.pressing.right) 
				me.speedX = playerSpeed; 
				 
			// keep on screen 
			if (me.sprite.position.x < 0) 
				me.sprite.position.x = 0; 
			if (me.sprite.position.x > _width) 
				me.sprite.position.x = _width; 
			if (me.sprite.position.y < 0) 
				me.sprite.position.y = 0; 
			if (me.sprite.position.y > _height) 
				me.sprite.position.y = _height; 
				 
			// 
			// leave a trail of particles 
			_entities.particles.addParticle(63,  
				me.sprite.position.x - 12,  
				me.sprite.position.y + 2,  
				0.75, -200, 0, 0.4, NaN, NaN, -1, -1.5); 
		} 
 
		private function mouseDown(e:MouseEvent):void    
		{    
			trace('mouseDown at '+e.stageX+','+e.stageY); 
			if (_state == 0) // are we at the main menu? 
			{ 
				if (_mainmenu && _mainmenu.activateCurrentMenuItem(getTimer())) 
				{ // if the above returns true we should start the game 
					startGame(); 
				} 
			} 
		} 
 
		private function mouseMove(e:MouseEvent):void    
		{ 
			if (_state == 0) // are we at the main menu? 
			{ 
				// select menu items via mouse 
				if (_mainmenu) _mainmenu.mouseHighlight(e.stageX, e.stageY); 
			} 
		} 
 
		// handle any player input 
		private function processInput():void 
		{ 
			if (_state == 0) // are we at the main menu? 
			{ 
				// select menu items via keyboard 
				if (_controls.pressing.down || _controls.pressing.right) 
				{ 
					if (nothingPressedLastFrame)  
					{ 
						_sfx.playGun(1); 
						_mainmenu.nextMenuItem(); 
						nothingPressedLastFrame = false; 
					} 
				} 
				else if (_controls.pressing.up || _controls.pressing.left) 
				{ 
					if (nothingPressedLastFrame)  
					{ 
						_sfx.playGun(1); 
						_mainmenu.prevMenuItem(); 
						nothingPressedLastFrame = false; 
					} 
				} 
				else if (_controls.pressing.fire) 
				{ 
					if (_mainmenu.activateCurrentMenuItem(getTimer())) 
					{ // if the above returns true we should start the game 
						startGame(); 
					} 
				} 
				else 
				{ 
					// this ensures the menu doesn't change too fast 
					nothingPressedLastFrame = true; 
				} 
			} 
			else  
			{ 
				// we are NOT at the main menu: we are actually playing the game 
				// in future versions we will add projectile 
				// spawning functinality here to fire bullets 
				if (_controls.pressing.fire) 
				{ 
					// is it time to fire again? 
					if (currentTime >= nextFireTime) 
					{ 
						//trace("Fire!"); 
						nextFireTime = currentTime + fireDelay; 
						_sfx.playGun(1); 
						_entities.shootBullet(3); 
					} 
				} 
			} 
		} 
		 
		private function startGame():void 
		{ 
			trace("Starting game!"); 
			_state = 1; 
			_spriteStage.removeBatch(_mainmenu.batch); 
			_sfx.playMusic(); 
			// add the player entity to the game! 
			thePlayer = _entities.addPlayer(playerLogic); 
			// load level one (and clear demo entities) 
			_entities.changeLevels('level1'); 
			_terrain.changeLevels('terrain1'); 
		} 
		 
		// this function draws the scene every frame 
		private function onEnterFrame(e:Event):void  
		{ 
			try  
			{ 
				// grab timestamp of current frame 
				currentTime = getTimer(); 
				currentFrameMs = currentTime - previousFrameTime; 
				previousFrameTime = currentTime; 
				 
				// erase the previous frame 
				context3D.clear(0, 0, 0, 1); 
				 
				// for debugging the input manager, update the gui 
				_gui.titleText = _controls.textDescription(); 
				 
				// process any player input 
				processInput(); 
 
				// scroll the background 
				if (_entities.thePlayer) _bg.yParallax(_entities.thePlayer.sprite.position.y / _height); 
				_bg.update(currentTime); 
				 
				// update the main menu titlescreen 
				if (_state == 0) 
					_mainmenu.update(currentTime); 
				 
				// move/animate all entities 
				_terrain.update(currentFrameMs); 
				_entities.update(currentFrameMs); 
				 
				// keep adding more sprites - IF we need to 
				_terrain.streamLevelEntities(false); 
				_entities.streamLevelEntities(true); 
				 
				// draw all entities 
				_spriteStage.render(); 
 
				// update the screen 
				context3D.present(); 
			} 
			catch (e:Error)  
			{ 
				// this can happen if the computer goes to sleep and 
				// then re-awakens, requiring reinitialization of stage3D 
				// (the onContext3DCreate will fire again) 
			} 
		} 
	} // end class 
} // end package

We're done! Compile your project, fix any typos, and run the game. If you're having trouble with the code you typed in or just want the instant gratification of everything in one place, remember that you can download the full source code here.

Here are a few tips for if you experience problems:

  • If you do use FlashBuilder, be sure to include "-default-frame-rate 60" in your compiler options to ensure you get the best performance.
  • If you are using Linux or a Mac, you can compile this from the command-line (or in a makefile) using something similar to "mxmlc -load-config+=obj\shmup_tutorial_part4Config.xml -swf-version=13", depending on your working environment.
  • Remember that since we're using Flash 11 you will need to be compiling using the latest version of the Flex compiler and playerglobal.swc.
  • Most importantly, remember that your Flash embed HTML has to include "wmode=direct" to enable Stage3D.

This source has only been tested using FlashDevelop on Windows, and the tips above have been kindly submitted by your fellow readers.

Once everything compiles and runs properly you should see something that looks like this: a fast-action Stage3d shoot-em-up game complete with parallax scrolling terrain, tons of enemies to destroy, sounds, music and - last but not least - a silky-smooth 60 frames per second framerate!



Part Four Complete: Prepare for Level Five!

That's it for tutorial number four in this series. We can now boast a detailed game world, enemies with some variety, and the ability to use a level editor. We're well on our way toward the final product!

In the next tutorial, we will upgrade our awesome new shoot-em-up to account for player health and score. We will also add the concept of "lives" so that you can get to a "game over" or "final credits" win condition. We'll add transitions to give the player a break between levels, and we'll allow users to continue where they left off. Instead of an infinite demo in which you cannot die, our project will finally be a fully playable game that actually poses a challenge to the player. We'll try to scale the difficulty just right so that it starts easy and gets harder as you continue.

After next week, the final tutorial, number six, will be all about adding the final polish, plus the creation of an epic BOSS BATTLE! This is going to be fun!

I'd love to hear from you regarding this tutorial. I warmly welcome all readers to get in touch with me via twitter: @McFunkypants, my blog mcfunkypants.com or on google+ any time. In particular, I'd love to see the games you make using this code and I'm always looking for new topics to write future tutorials on. Get in touch with me any time.

If you have enjoyed these tutorials thus far, perhaps you'd like to learn more about Stage3D? If so, why not buy my Stage3d book!

Good luck and HAVE FUN!

Advertisement