# AS3: StageWidth for BOX2D?

I know BOX2D uses meters, and AS3 uses pixels.

I'm trying to create objects which are limited to the stageWidth.

If I do this variable:

for (var i:int = 0; i<(stage.stageWidth); i++){...}


The animation will freeze, and this output appears:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Box2D.Collision.Shapes::b2Shape/CreateProxy()
at Box2D.Dynamics::b2Body/CreateShape()
at com.actionsnippet.qbox.objects::CircleObject/build()
at com.actionsnippet.qbox::QuickObject/init()
at com.actionsnippet.qbox::QuickObject()
at com.actionsnippet.qbox.objects::CircleObject()
at com.actionsnippet.qbox::QuickBox2D/create()
at BOX2D_Test_Tutorial_fla::MainTimeline/frame1()


Does anyone know how to fix this?

Full Code:

    [SWF(width = 350, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
// make a heavy circle
// create a few platforms

// make pins
for (var i:int = 0; i<(stage.stageWidth); i++){
//End

//Mid end

}
sim.start();
sim.mouseDrag();

• You asked this twice on purpose? Nov 27, 2011 at 22:30
• possible duplicate of AS3: limit objects to stage width? Nov 27, 2011 at 22:30
• I updated my answer in the other question. I think your problem is because you're accessing stage at a point of time where it's not initialized, eg. null. Therefore you get this error. Nov 27, 2011 at 22:40
• I had a look at your flash file. The issue isn't the stage. That works fine. I don't know exactly what the problem is, because the error occurs during the creation of the objects. It could be, because you're adding a huge amount of objects. The stageWidth is 350 and you're creating 350 * 9 objects in that loop. Most of these objects will be outside your physics world, because the stage is in pixels, while your physics-world has another unit (meters). That's probably causing the crash. Nov 27, 2011 at 22:54

You are surpassing the limit of bodies in Box2D, at 3150 circles I can't imagine why you would need so many, is there a logic error or will you divide this number by something?

Edit:

If you want to evenly space objects across the stage you can do this:

var meterWidth = stage.stageWidth/meter;// meter can be 30 or whatever your scale is

// Adds the distance between each object to i on each iteration and stops at the width
for (var i = 0; i < meterWidth; i += meterWidth/numberOfObjects)
{