64x64 icon dark hosting
Choose a hosting plan here and get a free year's subscription to Tuts+ (worth $180).

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


Start a hosting plan from $3.92/mo and get a free year on Tuts+ (normally $180)

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.

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.

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.

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.

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!

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.

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.

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.

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.

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:

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:

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.

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.

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.

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.

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.

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.

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.

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.

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.

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!