AS3: Managing multiple bullets/moving objects

One of the frequently asked questions is managing multiple similar things like bullets, balls, enemies etc. I did put together a short tutorial here.

Alright, this is what we are going to create:

First, create a new Flash (AS3) file. I named this one ‘BulletTutorial.fla’. Next is a new ActionScript file named ‘BulletTutorial.as’ and ‘BulletTutorial’ is set as the DocumentClass in ‘BulletTutorial.fla’.

Draw something that you like to use as a bullet, select it and convert it to a MovieClip (in the menu ‘Modify – Convert to Symbol’ or by hitting F8) named ‘Bullet’. Check ‘Export for ActionScript’.

Now that is the whole code in ‘BulletTutorial.as’:

package {
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.display.Stage;
	public class BulletTutorial extends MovieClip {
		public var bullet:MovieClip;
		public var bulletHolder:MovieClip;
		public var bulletArray:Array;
		public var autoFireRate:int = 40;
		public function BulletTutorial () {
			bulletHolder = new MovieClip;
			this.addChild(bulletHolder);
			bulletArray = new Array();
			this.addEventListener(Event.ENTER_FRAME, gameLoop, false, 0, true);
			stage.addEventListener(MouseEvent.CLICK, mouseBullet, false, 0, true);
		}
		public function gameLoop (event:Event) {
			for each ( bullet in bulletArray ) {
				bullet.x <= 375 ? bullet.x += 1 : removeBullet ( bullet );
			}
			autoFireRate <= 0 ? addBullet ( 125, 250, 40 ) : autoFireRate--;
		}
		public function mouseBullet (event:MouseEvent) {
			addBullet( 125, 125, 0 );
		}
		public function addBullet (startX, startY, ratePlus) {
			autoFireRate += ratePlus;
			bullet = new Bullet();
			bullet.x = startX;
			bullet.y = startY;
			bulletArray.push(bullet);
			bulletHolder.addChild(bullet);
		}
		public function removeBullet (which) {
			if(bulletHolder.contains(which)){
				bulletHolder.removeChild (which);
				bulletArray.splice(bulletArray.indexOf(which), 1);
			}
		}
	}
}

And that is the same thing as above with extra slides:

I'm done for the moment. Use comments for questions and have fun with the source.

Open fire! Yoho!

This entry was posted in game development and tagged , , , , . Bookmark the permalink.
Be Sociable, Share!

One Response to AS3: Managing multiple bullets/moving objects

  1. raco says:

    man so many thanks for this tutorial. I’ve checked so much different tuts but this si simply brilliant. And awesome explanation!

Leave a Reply

Your email address will not be published.