Boxy2D Physics Engine running on iPad, Android

by Gritfish on July 15, 2011

I mentioned in part one that when developing for mobiles with boxy2d, that you should use the “no events” branch of boxy2d. When developing for mobile devices, memory is in short supply, and flash’s event class can become a bit of a memory hog if not managed very strictly. The no event branch handles this for you, so you can have around 50 boxy objects on screen at once, although I’d still recommend techniques like object pooling if you’re going to push things.

Code and videos after the jump

Using the accelerometer to set the stages gravity:

var accel:Accelerometer;
if (Accelerometer.isSupported) {
	accel = new Accelerometer();
	accel.addEventListener(AccelerometerEvent.UPDATE, getAccel);
}
function getAccel(evt:AccelerometerEvent):void {
	boxyStage.gravity.x =- evt.accelerationX/10;
	boxyStage.gravity.y = evt.accelerationY/10;
}

Listening for exiting events (home button, or back button) to close the game and reset it

if(Capabilities.cpuArchitecture=="ARM"){
	NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, stopSleep);
	NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, exitGame);
	NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, backKey);
}
function stopSleep(e:Event){
	NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
}

function exitGame(e:Event){
	NativeApplication.nativeApplication.exit();
}
function backKey(e:KeyboardEvent){
	if(e.keyCode == Keyboard.BACK){
		NativeApplication.nativeApplication.exit();
	}
}

Here’s a video of it in action on my android nexus s (the file has been resized for android – 480×800):

Boxy2d running on Android Nexus S from John Kane on Vimeo.

And on an iPad:

Boxy2D running on an iPad from John Kane on Vimeo.