[SWF(width=600, height=400, backgroundColor=0x000000, frameRate=30)]
// make some ships
for (var i:int = 0; i<10; i++) makeShip();
//
function makeShip():void {
// setup vars
var char:Object ={posX:Math.random()*stage.stageWidth, posY:Math.random()*stage.stageHeight, velX:0, velY:0, rad:4, theta:Math.random()*6.28, thetaDest:Math.random()*6.28, mc: MovieClip(addChild(new MovieClip()))}
// draw and position the char
with(char.mc) graphics.lineStyle(0,0xFFFFFF), graphics.moveTo(-15, -5), graphics.lineTo(0, 0), graphics.lineTo(-15, 5), x=char.posX, y=char.posY;
// loop
addEventListener(Event.ENTER_FRAME, function(){
// change position based on velocity, .9 friction
with (char) posX += velX *= .9, posY += velY *= .9;
// randomize radius and theta
if (int(Math.random()*10) == 1) char.thetaDest += Math.random()*2-1;
if (int(Math.random()*90) == 1) char.rad = Math.random()*4 + 4
// apply changes to velocity
char.theta += (char.thetaDest - char.theta) / 12;
char.velX = char.rad * Math.cos(char.theta);
char.velY = char.rad * Math.sin(char.theta);
// screen bounds
if (char.posX > 620) char.posX = -20;
if (char.posX < -20) char.posX = 620;
if (char.posY > 420) char.posY = -20;
if (char.posY < -20) char.posY = 420;
// rotation
char.mc.rotation = (Math.abs(char.mc.y - char.posY)>.7 || Math.abs(char.mc.x - char.posX) > .7) ? Math.atan2(char.posY - char.mc.y,char.posX - char.mc.x) / Math.PI * 180 : char.mc.rotation;
// shoot
if(int(Math.random()*100) < 20) shootBullet(char, 5 * Math.cos(char.mc.rotation * Math.PI / 180)+ char.velX, 5 * Math.sin(char.mc.rotation * Math.PI / 180) + char.velY);
// apply position
with(char) mc.x = posX, mc.y = posY;
});
}
//
function shootBullet(char:Object, vx:Number, vy:Number):void{
var b:MovieClip = MovieClip(addChild(new MovieClip()));
b.life = 0;
with(b) graphics.beginFill(0xFFFFFF), graphics.drawCircle(0,0,2), x = char.mc.x, y = char.mc.y;
b.addEventListener(Event.ENTER_FRAME, function(){
with (b) x += vx, y += vy, life++;
if (b.life > 30) b.removeEventListener(Event.ENTER_FRAME, arguments.callee), removeChild(b);
});
}
An asteroids inspired code snippet. See the swf here.