18Aug

Actionscript Physics Engine Vectors

No comments

So I was deconstructing a game the other day that was using the APE Actionscript Engine and wanted to note how movement of an object can be created. By creating a new Vector an object can be moved accordingly. To interact with the movie, simply press the arrow keys on your keyboard.

A simple circle class:

package
{
	import org.cove.ape.Group;
	import org.cove.ape.CircleParticle;
	import org.cove.ape.Vector;

	public class Circle extends Group
	{
		public var cp:CircleParticle;

		public function Circle(x:uint, y:uint)
		{
			cp = new CircleParticle(x, y, 5, false, 3, .8);
			cp.setStyle(0, 0, 0, Math.random() * 0xffffff);
			addParticle(cp);
		}
	}
}

and the Main Document class:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import org.cove.ape.APEngine;
	import org.cove.ape.Vector;
	import org.cove.ape.CircleParticle;
	import org.cove.ape.Group;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import flash.text.TextField;

	public class Main extends Sprite
	{
		private	var cp:Circle = new Circle(stage.stageWidth / 2, stage.stageHeight / 2);

		public function Main()
		{
			APEngine.init(1/4);

			// set up the default diplay container
			APEngine.container = this;
			APEngine.addGroup(cp);

			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
            stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
			addEventListener(Event.ENTER_FRAME, run);
		}

		private function run(e:Event):void
		{
			APEngine.step();
			APEngine.paint();
		}

		private function keyDownHandler(k:KeyboardEvent):void
		{
			if (k.keyCode == Keyboard.UP) {
				cp.cp.velocity = (new Vector(0, -5));
			} else if (k.keyCode == Keyboard.DOWN) {
				cp.cp.velocity = (new Vector(0, 5));
			} else if (k.keyCode == Keyboard.RIGHT) {
				cp.cp.velocity = (new Vector(5, 0));
			} else if (k.keyCode == Keyboard.LEFT) {
				cp.cp.velocity = (new Vector(-5, 0));
			}
		}

		private function keyUpHandler(k:KeyboardEvent):void {
			cp.cp.velocity = (new Vector(0, 0));
		}

	}
}

Share/Save/Bookmark

Monday, August 18th, 2008 at 9:22 am and is filed under APE - Actionscript Physics Engine, Actionscript 3. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a reply