Monday, 16 April 2012

AS3 Box2D debug mode in Starling

I have recently been playing with Box2D in Starling and could not get the debug mode to work in Starling. A quick Google search revealed that you had to add the debug mode into a flash sprite so it can be added on top of the starling stage. Here is a quick example of my Main and Game class.

package 
{
 import starling.core.Starling;
 import flash.display.Sprite;
 import flash.display.StageAlign;
 import flash.display.StageScaleMode;
 import flash.events.Event;
 
 public class Main extends Sprite
 {
  public static var starling:Starling;
  public static var debugSprite:Sprite;
  
  public function Main()
  {
   stage.scaleMode = StageScaleMode.NO_SCALE;
   stage.align = StageAlign.TOP_LEFT;
  
   starling = new Starling(Game, stage);
   starling.start();
   
   stage.stage3Ds[0].addEventListener(Event.CONTEXT3D_CREATE, onContextCreated);
  }
  
  private function onContextCreated(e:Event):void
  {
   //debug mode
   debugSprite=new Sprite();
   addChild(debugSprite);
  } 
 }
}
package 
{
 import starling.display.Sprite; 
 import starling.events.Event;
 import Box2D.Dynamics.b2DebugDraw;
 import Box2D.Common.Math.b2Vec2;
 import Box2D.Dynamics.b2World;

 public class Game extends Sprite 
 {
  public var _world:b2World;

  public function Game() {
     addEventListener(Event.ADDED_TO_STAGE, onAdded);
  }
  
  private function onAdded (e:Event):void {
  
      //box 2d world
      var gravity:b2Vec2 = new b2Vec2(0, 10);
      _world = new b2World(gravity, true);
   
      //debug
     (Main.starling.stage.getChildAt(0) as Game).setDebugDraw(Main.debugSprite);
  }
  
  public function setDebugDraw(debugSprite:flash.display.Sprite):void{
      var debugDraw:b2DebugDraw = new b2DebugDraw();
      debugDraw.SetSprite(debugSprite);
      debugDraw.SetDrawScale(Constants.PIXEL_TO_METRE);
      debugDraw.SetLineThickness( 1.0);
      debugDraw.SetAlpha(1);
      debugDraw.SetFillAlpha(0.4);
      debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
      _world.SetDebugDraw(debugDraw);
  }
 }
}

2 comments:

blackwizzard 15 May 2012 at 12:54  

Hi,

This is really useful, but I see that the debug draw is deformed:
http://img207.imageshack.us/img207/209/starlingvsdebug.png

Do you know how to change that?
Apparently it's Starling which is changing something in the way graphics are displayed.

Thanks!

iliketo 15 May 2012 at 13:16  

@blackwizzard

A few things to check -
Is your scale factor correct?
Have you offset your image to compensate for the b2CircleShape's centre registration?

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP