Actionscript 3 AI Steering Behaviors Library

big-parrot-flock9-799781Big update for you guys! Hey I know I’ve been a bit AWOL on posts lately, but recently I just finished a project which I was on a time crunch to get done. Also I had been having issues with ironing out the last of some bugs with my new big library for you guys. It is an AS3 Artificial Intelligence Steering Behaviors library which works with the game structure code I’ve been writing.

Also I’ve made several adds / changes / fixes to the game structure which I’ll list out below. I wanted to write a big article ( or several ) explaining this big AI library and how each thing works, but I didn’t want to keep everyone waiting any longer so I am going to go ahead and release it now and I’ll write up articles about it as time permits. ( which I have more of now )

For those of you who want to dig in and learn it all on your own go ahead, but for everyone else I promise I’ll get some articles up soon explaining the changes and some tutorials on how steering behaviors work and how I’ve designed mine.

Here is a demo app that I created which shows off everything. You can download the source from the google project page. I highly suggest setting up a repository folder on your PC and keep it updated with the current game library folder, as that is the one which I will be submitting updates to. I won’t be updating the various zips any longer. I recommend tortoise SVN.

Get Adobe Flash player

So anyhow, here is a list of changes to the game structure that I have made so far. Be sure to check back soon for more AI / Game Structure fun!

ENGINE CHANGES:

  • Added more functionality to the Sound Manager class.
  • GameFactory is no longer a singleton.
  • Added creation of gameworld to GameFactory for easy game setup.
  • Fixed dispose function on Entity.
  • MovingEntity now restricts its movements to the max speed variable.
  • MovingEntity has a MaxAcceleration var, which is mainly just for external use.
  • Added a damping variable to MovingEntity.
  • Fixed an incorrect math function on Matrix2D.rotateVector()
  • CreateCallback function added to Root
  • Updated all classes extending EntityParams with the ability to pass variables in the constructor IE:
    new EntityParams( { radius:10, type:”Blob” } );
    NOTE: be sure to call super( a_params:Object ) AFTER you set any of your defaults, or anything passed in will be overwritten ( by the defaults )
  • Added a createCallback function to Root. Quite useful in some cases, check it out.
  • Cleaned up Root by taking out the FPS calculation. Use a custom FPS class for this now, such as the Urbansquall one which I am using in the Main() class.
    - Added astage width/height const to Root for ease of use. Obviously you will have to change it depending on your games size.
  • Fixed the lineIntersecton function of the Geometry Class. ( Thanks to Ryan from Mochimedia for pointing this out )
  • Added a “getRandomPolygon” utility function to the Geometry class which returns an array of points based on some parameters

1 Star2 Stars3 Stars4 Stars5 Stars (13 votes, average: 5.00 out of 5)
Loading ... Loading ...

Added SVN Repository to the Google Project Page

Hey guys, just wanted to say I am still alive. Haven’t been able to finish my latest post yet due to lack of time and some bugs I’m having trouble figuring out.  I decided to go ahead and create an SVN for all of the code here, so that everyone who prefers to stay up to date and use that sort of thing can. It is also MUCH easier than updating .zip files, so that is what I will keep most up to date now.

I’ve also released a little tidbit about constraining rotations to a max amount per second.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Programming Tidbit #3 – Constraining Rotation to a Max Turn Rate Per Second

d_turret

This is the third post in the series “Programming Tidbits.” These articles consist of useful bits of information or code that I would like to share, but are not necesarily full length articles.

Sometimes you may wish to constrain the amount of rotation an entity can rotate per second or tick or whatever, such as the turret on a tank or the turning of the tank itself. This can be done with a bit of math. It could seem a bit complicated without using the math libraries I have already created.

Here it is using my code:

We are going to assume the maxTurnRate will be in degrees per second.

if( maxTurnRate > 0 && currentVelocity.angleTo( newVelocity ) > ( maxTurnRate * MathUtils.DEG_TO_RAD ) * stepSize )
{
 	var mat:Matrix2D = new Matrix2D();
	mat.rotate( ( ( maxTurnRate * MathUtils.DEG_TO_RAD ) * stepSize ) * heading.sign( newVelocity ) );
 	mat.transformVector( currentVelocity);
 	mat.transformVector( heading );
 }
 else
 {
 	velocity.x = _newVel.x;
 	velocity.y = _newVel.y;
 }

The Code Explained

So let’s take a look at what is happening there. First, we are checking to see if maxTurnRate is > 0…because we will assume if it is set as 0 then the entity should be able to turn freely. If it is greater, then we will get the angle from our current velocity and check to see if it is greater than the max turn rate multiplied by the step size. The step size is generally just: tickSize / 1000.

The math to get the angle from one vector to another is:

public function angleTo( vector1:Vector2D, vector2:Vector2D ):Number
{
	return Math.acos( dotProduct( vector1, vector2 ) / ( vector1.length * vector2.length ) );
}
 
public function dotProduct( vector1:Vector2D, vector2:Vector2D ):Number
{
	return ( vector1.x * vector2.x ) + ( vector1.y * vector2.y );
}

Next, if the rotation is greater than the max amount aloud…we will use a matrix to rotate the velocity vector to it’s correct position and transform it and the heading ( the direction the entity is going ). Note: The “sign” function just returns -1 if vector is counterclockwise, else 1 if clockwise. We need this to know which direction to rotate obviously.

The Matrix Code

Here is some of the matrix code, though I definitely don’t plan on explaining matrices in this post. Which is why it’s best to just use the library if you don’t actually understand the math part itself. :D

/**
 * Use to rotate.
 * ( Considers that the Vector object represents a point, not an actual vector )
 * @param rot
 *
 */
public function rotate(rot:Number):void
{
	var sin:Number = Math.sin(rot);
	var cos:Number = Math.cos(rot);
	multiply( new Matrix2D( cos, sin, 0, -sin, cos, 0, 0, 0, 1 ) );
}
 
/**
 * Use to multiply two Matrixes...mainly used internally.
 * @param matrix The Matrix to multiply by.
 *
 */
public function multiply(matrix:Matrix2D):void
{
	var m:Matrix2D = new Matrix2D();
 
	//first row
	m.a1 = (a1 * matrix.a1) + (a2 * matrix.b1) + (a3 * matrix.c1);
	m.a2 = (a1 * matrix.a2) + (a2 * matrix.b2) + (a3 * matrix.c2);
	m.a3 = (a1 * matrix.a3) + (a2 * matrix.b3) + (a3 * matrix.c3);
	//second row
	m.b1 = (b1 * matrix.a1) + (b2 * matrix.b1) + (b3 * matrix.c1);
	m.b2 = (b1 * matrix.a2) + (b2 * matrix.b2) + (b3 * matrix.c2);
	m.b3 = (b1 * matrix.a3) + (b2 * matrix.b3) + (b3 * matrix.c3);
	//third row
	m.c1 = (c1 * matrix.a1) + (c2 * matrix.b1) + (c3 * matrix.c1);
	m.c2 = (c1 * matrix.a2) + (c2 * matrix.b2) + (c3 * matrix.c2);
	m.c3 = (c1 * matrix.a3) + (c2 * matrix.b3) + (c3 * matrix.c3);
 
	Set(m.a1,m.a2,m.a3,m.b1,m.b2,m.b3,m.c1,m.c2,m.c3);
}
 
/**
 * This is used to do the final transformation upon the Vector
 * @param point The Vector to apply this Matrix transformation to.
 *
 */
public function transformVector(point:Vector2D):void
{
	var tempX:Number = (a1*point.x) + (b1*point.y) + (c1);
	var tempY:Number = (a2*point.x) + (b2*point.y) + (c2);
	point.x = tempX;
	point.y = tempY;
}

And that’s all!

So anyways…I’ve shown the internal workings of the math code there for you, though the first code block is all that should really matter to you in the end…since it shows how to actually use the math.

No example today, since I’m pretty sure you can imagine a turret rotating at a max speed…lol. However, it will be used in the next Game Structure post for the entities.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Some Updates: 12/26/2008

I’ve updated my coding conventions slightly.

Also for those of you waiting for the next article…be patient, it is a BIG one! I’ve created many Artificial Intelligence behaviors and a great OOP structure to use them, and I’ll be discussing Boids and many of the behaviors in detail. I’ll try to get it finished as soon as possible.

I hope everyone is enjoying their Christmas break!

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Managing Sounds and Music in Actionscript 3

sound

Dealing with sounds in Actionscript can be kind of wacky. Sound Objects, Channels, Transforms…blah. I don’t like messing with all of that, so I’ve built a sweet, easy to use Sound Manager. I don’t suppose it has any magical powers or anything but that’s only because I couldn’t think of anything magical a Sound Manager should do…other than play sounds and control volume.

The Sound Manager Class

It is a Singleton, and can be used from anywhere in your game / project. Simply register all of your sounds to the manager, and play them using IDs rather than having references to the sounds themselves.

Also, I have made it so that you can play a “sound”, or play “music” which is controlled at a different volume. Also, it is set up so that only one music sound will play at a time.

Here is the interface for the Sound Manager: Read the rest of this entry »

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4.50 out of 5)
Loading ... Loading ...

Game Object Creation – The Factory Method

This is the 4th article in the series: Building a Game Structure. Be sure to read the introduction which also has links to the rest of the articles in the series.

In previous articles we have put together a framework to handle various issues with our game. As of now, it would be quite sufficient for creating many simple games. One problem however, is that the creation of multiple types of entities in various places in our code can get cumbersome and is prone to errors and/or problems if we begin to make changes to the way we want our entities to be created

The Factory Method

The proper way to handle the creation of multiple objects with similar functionality is to Read the rest of this entry »

1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 4.83 out of 5)
Loading ... Loading ...

Managing Game Objects and Rendering a Game World

This is the 3rd article in the series Building a Game Structure. Be sure to read the introduction which also has links to the rest of the articles in the series.

There comes a time when working on a game that you realize the need for an effective way to manage all of your entities and game objects. Also, not all games consist of just one simple non-scrolling screen so you must devise a robust way to deal with the problems of displaying your entities in the correct position based on where in the world you want the view to be centered, not to mention handling the mouse’ world position. Not only that, but it would certainly be nice to have some basic, simple, and reusable classes for rendering your entities so that you don’t ever have to deal with it again.

These are the issues I will be covering in today’s article, and of course I will wrap up by showing the code that I use and handing you the source to play with. I’ve made a few slight changes to some of the classes which I will talk about below. Read the rest of this entry »

1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 4.67 out of 5)
Loading ... Loading ...

Programming Tidbit #2 – Efficient Multiple Object Collision Testing

This is the second post in the series “Programming Tidbits.” These articles consist of useful bits of information or code that I would like to share, but may not be considered a full article.

Sometimes your game may consist of a very large amount of entities that must be checked for collision with each other. In order to increase the speed of your collision tests there are a few methods that you can employ. This is no way an all inclusive article on this subject because there are MANY different methods for improving collision performance, however hopefully this can get you started.

The easiest thing to do is to eliminate as many collision checks as possible, as well as keep the collision checks as simple as you can. I’ll try to explain a few different methods which you can combine to speed up your testing.

The Bad Way

Generally you will be storing multiple entities in some type of array or map. The most common way of checking for collision is to loop through this array and check each entity against one another.

var entity1:Entity;
var entity2:Entity;
 
for ( var i:int = 0; i < entities.length; i++ )
{
 	entity1 = entities[ i ];
 
 	for ( var j:int = 0; j < entities.length; j++ )
 	{
 		entity2 = entities[ j ];
 
 		if( entity1.isOverlapping( entity2 ) )
 		{
 			// Handle Collision
 		}
 	}
}

Reduce Redundancy

Using this method will work, however the more entities you add to the array the slower it will become. The main problem here is that many of your checks are redundant. The more efficient method would be to make sure that you only check each entity once by making a small change to the inner loop:

for ( var j:int = i + 1; j < entities.length; j++ )

Collision Groups

Another way of increasing the speed is to give your entities flags or collision groups. For example, you may flag some entities as “collidable” and you may also decide that some entities cannot collide with each other so you might give them a “group” variable. This eliminates the need for actually running checks against this entity at all.

var entity1:Entity;
var entity2:Entity;
 
for ( var i:int = 0; i < entities.length; i++ )
{
 	entity1 = entities[ i ];	
 
 	if( !entity1.isCollidable )
 	{
 		continue;
 	}
 
 	for ( var j:int = i + 1; j < entities.length; j++ )
 	{
 		entity2 = entities[ j ];
 
 		if( !entity2.isCollidable || entity1.group == entity2.group )
 		{
 			continue;
 		}
 
 		if( entity1.isOverlapping( entity2 ) )
 		{
 			// Handle Collision
 		}
 	}
}

Simplify First

The last trick would apply when you are using complex collision such as pixel perfect / polygon collision. Instead of checking each object with the complex collision algorithm, use a simple bounding circle collision test first, and if that test returns true then proceed with the more detailed collision test.

if( entity1.isOverlapping( entity2 ) )
{
	if( entity1.detailedCollisionTest( entity2 )
	{
		// Handle Collision
	}
}

Final Words

Other methods of increasing collision testing speed would be to implement some sort of “broad phase” algorithm, however that is beyond the scope of this article. The methods discussed here should be sufficient for most flash games.

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading ... Loading ...

Game Entities and Representing Objects in a Game

This is the 2nd article in the series Building a Game Structure. Be sure to read the introduction and article 1 which discusses building a foundation for your games.

I’m going to discuss how different objects should be represented in your games and do my best to explain the idea behind my reasoning. I’ll provide the code I am using for my entities, and explain that a bit as well. So let’s get started. First of all, I feel that it is best to categorize your game objects into two categories: Entities and Game Objects. Let’s talk about Entities first.

What is an Entity?

An entity can represent any physical object in your gameworld. Entities are generally things that can be interacted with in some way, or just anything that holds a position in the world. This could include: A barrel, door, powerup, player, enemy, trigger area, wall, etc.

All entities will use the update/dispose interface. Entities may contain other entities and game objects in a hierarchical structure as well. They contain the basic data to represent themselves in game space such as position, rotation, size, scale. Each has a unique ID associated with it for debug and storage purposes.

Ideally Entities will replace the need for multiple class types for each different enemy by providing somewhat of a “template.” In order to provide more functionality we do things such as extend the basic Entity class with “MovingEntity” which provides movement data, and in a later article I’ll discuss a “Vehicle” class which provides AI to the entity. Each individual game will extend those basic classes further with a general “Unit” class that can provide more specialized data such as health, damage, etc.

To make the Entity classes as reusable as possible we will provide basic hook functions that can be used or overrided by subclasses. We want to make it as easy as possible to centralize the creation of these entities within a factory class, and even create a way that these can be built using external data. Rather than having a long list of constructor parameters, we create an “EntityParameters” class that holds the basic startup variables to be passed through to each entity on creation. This will make it very easy to do the things we just discussed.

Why Use Entities?

One question some may ask is why we create a class to represent our objects rather than simply extending MovieClip. Well, the answer is that it is quite inflexible to extend MovieClip because you may wish to represent your object with several different types of graphical data. This approach I am preaching is more along the Model View Controller design pattern, which allows for the greatest of expandability. Also, there are some things that make using entities extremely faster than dealing with Display Objects directly.

What is a game object?

Now that we are clear on what an Entity is, and the idea behind it…isn’t that what a game object is? Well, yes and no. A game object can be any of the following: A Sprite which graphically represents an entity, an AI routine which must be calculated each frame, any sort of game GUI such as menus etc. A game object’s definition is really quite broad, but we will consider anything to be a game object which needs to be updated and disposed of properly and does not have an actual “Game World” representation. I suppose that leaves the question of…

What is the “Game World”?

The Game World is simply the area in which the entities reside. What would be displayed to the screen can be considered as what is visible in the “camera.” The Game World is in fact an entity itself. I don’t want to go into any more detail on this right now, because it will be discussed in detail with another article.

Let’s build our Entity

Note: This version of the Entity class has a small bit of it’s final functionality taken out. What you see below is the core of it, however we will build upon it slightly in future articles to allow for greater usefulness within our greater game structure.

I’m going to list out the interface of the Entities and Game Objects. I’ve commented the interface here. To see the full code you may download the files from the google project page. Read the rest of this entry »

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 5.00 out of 5)
Loading ... Loading ...

Building a Foundation For Your Games and Handling Screens

This article is part 1 of a series: The Structure of a Game. Read the Introduction here.

Building Foundation

What does a game foundation consist of?

The starting point for any well built structure is a strong foundation. It is important that the foundation of your game is able to handle the basic functionality that will apply across all of your games, and does it simply with little to no extra effort on your part.

Also, what do all games have in common? They consist of various screens (Oh yes they do, or your game would be considered a tech demo my friend). With that in mind, our structure should be able to handle the following:

  • Context Menu Setup
  • Access to the Stage.
  • Tweaking of game speed
  • Frame Rate Tracking
  • Sending updates to your game
  • Custom Game Cursor ( if applicable to your game )
  • Global game pause
  • Ability to step through code 1 update at a time
  • Screen switching

In order to implement all of these in a manner that we can easily and quickly transfer over to each and every project and use without any real need of changing the code at all we will create our structure using the following 3 classes:

  • IScreenItem – Anything that will be considered a screen, such as MenuScreen, GameScreen, etc…
  • AScreen – An Abstract class which handles screen switching.
  • Root – Our meat and potatoes of the foundation. Handles the “Basic” functionality discussed above.

Lets build it!

A few concepts for me to mention now before we start are that almost all of our game objects will use an update and dispose method. Updates will filter down from the Root class so as to keep greater control of the game and eliminate the inconvenience and speed hog of creating multiple frame event listeners to the stage. Also it is good practice to clean up your code on removal such as removing any event listeners and nulling any outside references.

Also we will be using a constant time step to update our code. It is quite simple to interchange actually which I can show you, but in my experience a non-constant time step can cause inconsistencies that are difficult to debug.

When I refer to “Global Game Pause” this means that all updates to the game objects and rendering. You may have seperate pause logic within your game screen that pauses only certain features, still allowing menus or other GUI to run.

The IScreenItem and AScreen Classes

Okay, so let’s begin with the IScreenItem class. This will be the interface for any screen used in the game… Read the rest of this entry »

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 5.00 out of 5)
Loading ... Loading ...