Asteroids 2.01: Making the Asteroids Move

With a taste of success under my belt, I started remaking the Asteroids game using ActionSctipt 2.0 and class structure.

[Download the source files](http://flashforlearning.com/files/Asteroids_01.zip).

While the Asteroids you see here are movieclips with polygon fills, unlike the completely code-rendered Asteroids in the original game, there is no code in the entire flash movie. All the code takes place in the Asteroid.as class file that each Asteroid movieclip is bound to. I didn’t even have to instantiate these Asteroids for them to behave. I just drag them out of the library and let them do their thing.

Notice any similarities between the [LinearSprite code](http://flashforlearning.com/archives/2005/04/linear_sprites.php) and the following code? [It’s a natural progression from the original code](http://www.macromedia.com/devnet/mx/flash/articles/asteroids03.html). We’ll see in later entries if this has to change…

class Asteroid extends MovieClip
{
	// velocity value for the Asteroid's x- and y- movement
	private var xv:Number;
	private var yv:Number;

	// rotation of the Asteroid, so it looks like it drifts
	// in outer space
	private var r:Number;

	// this is the constructor function, which initializes
	// each Asteroid instance.  It must be a public function
	// or it won't be able to be accessed by the Flash movie.
	private function Asteroid ()
	{
		// shorten up some Math functions
		var mr = Math.random;
		var mf = Math.floor;

		// set the velocity for the Asteroid
		xv = mf( mr() * 6 ) - 3;
		yv = mf( mr() * 6 ) - 3;

		// set the Asteroid's original rotation.
		r = mf( mr() * 360 ) - 180;
		_rotation = r;

	}

	// Each Asteroid will now encapsulates, or
	// determintes its own movement.  This will
	// improve performance over the original
	// game, where one onEnterFrame on the _root
	// controlled everything.
	private function onEnterFrame():Void
	{
		// This series of if statements simply guides the placement
		// of an asteroid as it floats near the borders of the movie.
		if ( _x < = 10 )
		{
			_x += 390;
		}
		if ( _x >= 390 )
		{
			_x -= 390;
		}
		if ( _y < = 10 )
		{
			_y += 140;
		}
		if ( _y >= 140 )
		{
			_y -= 140;
		}

		// Keep the Asteroid moving per its velocity
		_x += xv;
		_y += yv;

		// Keep the Asteroid rotating on its axis, as if it were floating
		// in space.
		_rotation += r / 60;
	}
}

Please use the comments feature here to ask any questions, or make any suggestions to improving the code. I want to build the best asteroids game I can with ActionScript 2.0… and I’m more than willing to incorporate your ideas!