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 (3 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 (5 votes, average: 5.00 out of 5)
Loading ... Loading ...

Programming Tidbit #1 – Eliminate Magic Numbers

This is the first 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.

The Wrong Thing…

When programming, a lot of times you may find yourself throwing together some code which uses “Magic Numbers.” A magic number is basically just any static number sitting in your code such as:

public function moveMyCharacter() : void
{
	myCharacter.x += 5;
	myCharacter.y += 5;
}
 
public function damageEnemy() : void
{
	someEnemy.health -= 20;
}

Why is it bad?

Now obviously that is just a simple example, but let’s say you have code ALL OVER your project using these “magic numbers.” What happens then, if later you want to change these numbers? You have a long and tedious process of finding all times that they are used. Not only that, but you are prone to missing something which will therefore lead to unpredictable code and bugs.

The right thing…

Instead of being mean to yourself, do the right thing and create constants or variables for all of your magic numbers. The usual place to put them is at the top of your class. Even better would be to externalize the data into some sort of settings file ( if the data is worthy of course ). I’ll be discussing externalizing data in a future article if you aren’t quite sure how to go about that…

So here is the code once again, done properly.

// Top of your Class somewhere...
private const MOVE_SPEED:int = 5;
private const HERO_DAMAGE:int = 20;
 
public function moveMyCharacter() : void
{
	myCharacter.x += MOVE_SPEED;
	myCharacter.y += MOVE_SPEED;
}
 
public function damageEnemy() : void
{
	someEnemy.health -= HERO_DAMAGE;
}

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

The Structure of a Game – Introduction

Inspiration

When I first began programming, it seemed like there were a vast amount of tutorials out there which taught you how to do a specific task such as “make a shooting game” or something of that nature. These were great for me at first, as I didn’t know my left toe from my right thumb. Eventually however, I began to get better and I craved more organized and useful information such as how to actually structure games, and how to use proper OOP techniques etc. There simply just isn’t enough of it out there. I found a few articles explaining several ideas and concepts, and I read many different books on OOP and design patterns…then after about a year of working together the different I came up with a great mesh of it all to develop my current game structure.

Purpose

My purpose for this article and those that follow in this series is to teach you piece by piece how to build a reusable game structure for your games as well as explain different game coding techniques and concepts along the way. I’ll be providing code that I’ve written, however for maximum benefit I recommend that you modify or rewrite it to your style and needs. For example, each time I start a new project I simply copy all of my game code over from my latest game and then delete classes which I won’t need, as well as tweak existing code to fit the current project.

Requirements

It is good practice to write down some goals and requirements for what you would like your game engine to incorporate, so let’s consider this now. Our game structure will have consist of the following:

  • The ability to save game state, pause, speed up and slow down
  • We can set a camera position and size to render what is in the game world.
  • The game logic will be separate from the rendering logic.
  • Data driven development. IE: Creatures and levels will be built outside of the core code engine itself, usually from XML or on a higher level in an editor of some sorts.
  • Object creation is centered in one location
  • Control of entities is done through “controller” classes.
  • And of course…it will run incredibly fast.

If any of that sounded complicated, fear not. I will be discussing the reasons for each part as well as explaining how it all works. We will create one piece at a time and build upon the structure as we move along, making improvements along the way.

As I complete each section I will update this article to link to each piece. You may visit the google project page to aquire all of the project files and source code as well.

Additional Articles in this series:

Programming Libraries used in the Series:

Conventions that I follow:

Recommended Reading:

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

Programming on Paper

I want to discuss a technique that I have been using which works very well to get past the initial strain of programming a new part into your game. Yesterday I was trying to figure out how I would program the abilities system for units ( it is a Diablo style game, so there is a possibility for a lot of abilities ).

After staring at the screen for a while, I pulled out the ol’ handy dandy notebook and just began writing things down on paper. Shortly thereafter I had the entire system programmed, and it worked great!

So, the process of programming on paper works like this:

  1. Decide your problem. Write it down.
  2. List out the steps that need to take place from the player’s view in order for the problem to work. IE:
    • Player chooses class ( Wizard for example )
    • Unit is given abilities.
    • Player presses ability 1 key, ability 1 activates.
  3. Now that you see what is required to complete your problem it is much easier to program it. Decide on which classes will be needed, and then write out how it will all work using pseudo code…so for me it was something like this:
    • Ability Class, abilities will extend this…for example: HealAbility, ProjectileAbility, etc.
    • onKeyPress( “A” ) : Unit.useAbility( 1 );
    • Unit.useAbility(): ability1.execute();
    • ability1.execute(): unit.addHealth( 20 ); //or spawnProjectile( “Fireball” ); //or unit.addBuff( … )
  4. Once you have all of it written down in pseudo code like that it really makes it super simple to code everything because you are just basically putting it in Actionscript.

Originally I had thought it would be difficult and take quite some time to design and program all of the things I did yesterday (it was a lot) however since I used this technique I believe it relieved the pressure of creating code that doesn’t work and just let me focus on the concept of HOW it should work. Hopefully you can find a style or programming on paper that works best for you as well.

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

An update and something funny

Last night I was looking on digg and found something hilarious.

Coincidence? Who knows...

Coincidence? Who knows...

Well I haven’t written anything of value in a while due to being super busy ( and gone ) so here is a bit of an update. During half of September and most of October I was in Bridge City, Texas which is a small town that was probably hit the hardest during the hurricane. Only 14 homes in the ENTIRE city were not destroyed by flood. The town has around 4000 homes.

Now that I am back I am working diligently on a new project, which should be done in the latter part of November if I keep on track ( which I am doing ). Also I have some articles planned which you all should look out for.

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

Converted all code to MIT license.

After getting some messages informing me of why the GPL was the wrong license I looked it over and said to myself, “oops!” I didn’t realize that by using them you would have to keep your project GPL as well.

I have converted all of the files to an MIT license so that you can reuse them in any way that you please. Be sure to visit the google code page to download everything.

http://code.google.com/p/cheezeworld

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

Whoops! I’ve been away for a while.

So I haven’t really been on the internet recently…somewhat of a leave of absence for the month of July or so. Sorry for anyone trying to access my website while it has been down, however that shouldn’t happen again.

Anyways. I am back to work on Space Crusade and I should be done shortly. No more demo updates until I am done though sorry! Also I have some plans for new articles and videos after I get some work done. Hope everyone has been having a great Summer. See you around!

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

Adopt Some Coding Conventions for Projects: Sloppy Code SUCKS!

I am writing this article in the hopes that you will learn from mistakes that I have made. Let me just tell you…sloppy code SUCKS! Once you start getting into bigger projects (or even not such a big project) and even worse when you start to work with others and share code things can become a mess. So I am hoping some of you with no coding standard or no idea of how to “properly” structure your code will get something out of this and decide to do the same or at the least come up with your own standard and stick with it.

Occasionally I do tweak or add to my standards but for the most part I really do keep everything the same.

Currently I’ve been improving some habits of mine (mainly things like spacing and brackets etc) a bit so my older code is a little sloppier than my newer stuff which is okay. I also want to first point out this article by GamePoetry which links to the “UrbanSquall” coding standards. Those are basically what I stick to except for the few additions / changes mentioned below.

So let’s get started.

Class properties / Members

Public
The idea here is to always avoid using getter/setter functions whenever possible. Well, atleast for anything that would be called once or more each frame. If it’s an obscure variable that is rarely called or used for something that isn’t speed related you can use them…otherwise NO. Anything that is both gettable/settable will be simply written as it is:

//it probably wouldn't matter too much if you externally modified this variable
public var maxSpeed:Number;

Read-Only
EDIT ( 12/26/2008 ) : I no longer use different naming convention for read alone variables, I simply either use a getter or I keep them public with a code comment that warns against changing the variable externally.

The speed difference of NOT using getters/setters can be very apparent with something like a “Vector” class where the ‘x/y’ variables are public. This adds probably 20-30 FPS to a demo with about 2-3000 sprites all doing world bounds wrap checks etc. Just imagine the speed difference when ALL of your code complies with this.

Sometimes we may want to reduce the “m_bulletsLeft” safely so in that case create a function such as “shootGun()” inside the class that holds “m_bulletsLeft” rather than making it a public variable and implementing some external code to reduce the “m_bulletsLeft” variable. (This is more of a proper Object Oriented design practice: ‘Encapsulate Change’)

Private / Protected
For all properties usable only by the class that created them we will use: m_variableName
For any protected property which can be used only by classes when extend it we will use: _variableName

//this helps avoid naming conflicts...which is good!
private var m_beanCounter:int;
protected static var _nextID:int = 0;

Naming Conventions

Booleans
Any boolean properties and functions will always be structured in question format. They are followed by the words: “is, has, can, does”:

public var isCollidable:Boolean;
public function doesRayIntersectCircle( a_rayOrigin:Vector, a_rayHeading:Vector, a_circleCenter:Vector, a_circleRadius:Number ):Boolean{ //code }
private var m_hasGun:Boolean;
protected var _canComeToTheParty:Boolean; // lol

Constants
All constants will be in caps with phrases separated by underscores:

public static const HEAVY_ARMOR:int = 0x000001;
public static const WOODEN_SHIELD:int = 0x000010;
public static const SLARGH_FIGHTER:String = "slargh_fighter";
private static const ENEMIES_PER_WAVE:int = 15;

Public Functions / Private Functions
Usually I stick to the “Urbansquall” convention on this which is to use a “verbNoun() format. Sometimes my functions will stray slightly from the “verbNoun” format when parameters are available and instead I will try to complete a sentence with the parameters. In other words I use “verbPreposition(noun)” format:

public function addTo( a_vector:Vector ):void;
public function wrapAround( a_topLeft:Vector, a_bottomRight:Vector):void;
public function dotOf( a_vector:Vector ):Number;

Event Handler Functions
I will treat event handlers slightly different when naming them. I always name them as if they are happening because of an event (hmm…) Which means basically all of them have “on” preceding them.

onScriptLoad(e:Event):void{}
onEntityCollision(e:CollisionEvent):void{}

Variable / Function Positioning

The order I use to place variables and functions ( except for specific circumstances ) are as follows:

  1. Static Constants
  2. Getters / Setters
  3. Public variables
  4. Constructor
  5. Public Class Functions
  6. Overriden Public Functions
  7. Protected Functions
  8. Private Functions
  9. Protected Variables
  10. Private Variables

As far as I can think of those + the urbanSquall link from above are the conventions I stick with. Hopefully you decide to do the same! Also be sure to read: Better Debug Tracing for some tracing conventions that should be followed as well.

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