Plugging Starling with Box2D

The fantastic thing about Starling is its display list API, which makes it very easy to plug with existing frameworks. For instance, let’s say we would like to use the Box2D framework for adding some physics to our game?

You can learn more about Box2D here and download the library that we will use in the following example: http://box2dflash.sourceforge.net/

In this code, we make boxes fall on the ground with some simple gravity. Of course, everything is rendered through the GPU:

package
{
    import Box2D.Collision.Shapes.b2CircleShape;
    import Box2D.Collision.Shapes.b2PolygonShape;
    import Box2D.Common.Math.b2Vec2;
    import Box2D.Dynamics.b2Body;
    import Box2D.Dynamics.b2BodyDef;
    import Box2D.Dynamics.b2FixtureDef;
    import Box2D.Dynamics.b2World;

    import starling.display.DisplayObject;
    import starling.display.Quad;
    import starling.display.Sprite;
    import starling.events.Event;

    public class PhysicsTest extends Sprite
    {
        private var mMainMenu:Sprite;
        private var bodyDef:b2BodyDef;
        private var inc:int;

        public var m_world:b2World;
        public var m_velocityIterations:int = 10;
        public var m_positionIterations:int = 10;
        public var m_timeStep:Number = 1.0/30.0;

        public function PhysicsTest()
        {
            addEventListener(Event.ADDED_TO_STAGE, onAdded);
        }

        private function onAdded (e:Event):void
        {
            // Define the gravity vector
            var gravity:b2Vec2 = new b2Vec2(0.0, 10.0);

            // Allow bodies to sleep
            var doSleep:Boolean = true;

            // Construct a world object
            m_world = new b2World( gravity, doSleep); ...

Get Introducing Starling now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.