Friday, April 03, 2009

Managing Multiple Game Objects in AS3

Managing loads of objects in a game can be one of the most challenging aspect of game programming. In sprite heavy games you are constantly making, moving and destroying objects. While much of my code is reused from game to game I always find myself trying to find better/easier ways to manage enemies, bullets and effects.

While I was teaching at AIA I tried teaching the "make an object that holds sprite vars and place it in an array" method. This is a commonly accepted method of managing sprites and their variables. This method was much too complicated for the programming level of the students so I tried to work up and easier way. I found you can simply use the Display List.

Step 1: Object Containers
Create a container for every groups of objects. Enemies, bullets, effects, etc. If you plan on only having sprites use a sprite for your container, if you will be adding movieclips use a mc for your container.


var cBullets:MovieClip;
...
cBullets = new MovieClip();
addChild(cBullets);
...


Step 2: Adding Objects
This is a bit old school but just dump you variables into your sprite/movieclip and add it to the container.

var aBullet:Bullet = new Bullet();
aBullet.speed = mySpeed;
aBullet.angle = myAngle;
aBullet.life = myLife;
cBullets.addChild(aBullet);


Step 3: Loop the container
Now loop through the container and operate on the objects


var i:Number = cBullets.numChildren;
while(i--){
var sp = cBullets.getChildAt(i);
sp.x += Math.cos(sp.myAngle) * mySpeed;
sp.y += Math.sin(sp.myAngle) * mySpeed;
//you can put collision here or whatever else you need
sp.life--;
//if your game sprite is a Sprite
if(sp.life == 0){
cBullets.removeChildAt(i);
sp = null;
// yes, a factory would be ideal
}
//if your game sprite is a MovieClip
if(sp.currentFrame == sp.totalFrames){
cBullets.removeChildAt(i);
sp = null;
}else{
sp.nextFrame();
}
}


I have not tested the efficiency of this method but it makes for very fast prototyping

Labels: , , ,

2 Comments:

Blogger Matt said...

One oddity I've found when using a display object's x and y position as the authoritative game position is that flash somethimes likes to tweak the x and y without telling you. For example sometimes you can set spriteObj.x = 1.123 and the next frame discover it is now 1.124. Sounds harmless, but hell on collision and physics.

9:56 PM  
Blogger Brad Merritt said...

Yeah, that's definitely true. I learned the hard way when collisions would stick to each other sometimes and I could not figure out why.

For example an object penetrates another object, say 1.23, so you move it 1.23 away but it really moves 1.22 and now its still colliding!

12:47 AM  

Post a Comment

<< Home