19Aug

APE Vectors and Collidable Walls

No comments

So I just added some walls to my little movie here and took out the KEY_UP handler to allow the circle to continuously move around the stage. To activate, simply hit an arrow key.

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 );
		private var walls:Walls = new Walls( stage.stageWidth, stage.stageHeight );

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

			// set up the default diplay container
			APEngine.container = this;
			APEngine.addMasslessForce(new Vector(0,0));

			APEngine.addGroup(cp);
			APEngine.addGroup(walls);

			cp.addCollidable ( walls );

			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
            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));
			}
		}
	}
}

The 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);
		}
	}
}

The Wall class:

package
{
	import org.cove.ape.Group;
	import org.cove.ape.RectangleParticle;  

	public class Walls extends Group
	{

		public function Walls(bw:Number, bh:Number)
		{
			// top
			var t:RectangleParticle = new RectangleParticle(bw/2, 0, bw, 10, 0, true);
			addParticle(t);

			// this is the bottom
			var b:RectangleParticle = new RectangleParticle(bw/2, bh, bw, 100, 0, true);
			addParticle(b);

			// left
			var l:RectangleParticle = new RectangleParticle(0, bh / 2, 10, bh, 0, true);
			addParticle(l);  

			// right
			var r:RectangleParticle = new RectangleParticle(bw, bh / 2, 10, bh, 0, true);
			addParticle(r);
		}
	}
}

Share/Save/Bookmark

Tuesday, August 19th, 2008 at 8:57 am and is filed under APE - Actionscript Physics Engine, Actionscript 3, manewc.com. 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