m0j1
m0j1

Reputation: 4267

actionscript3 creating object inside function

I've been trying to write a function to create a simple circle in Box2DFlash . but it keeps telling me that the object is null and I can't access it's properties here's the code:

    public var f1:b2Body;
    public var f2:b2Body;
    public function addACrate(fallingCrate:b2Body, positionX:Number,positionY:Number):void
    {
                var fallingBodyDef:b2BodyDef = new b2BodyDef();
                fallingBodyDef.type = b2Body.b2_dynamicBody;
                fallingBodyDef.position.Set(positionX/ratio,positionY/ratio);

                fallingCrate =_world.CreateBody(fallingBodyDef);

                var fallingCrateShape:b2CircleShape = new b2CircleShape();
                fallingCrateShape.SetRadius(10/ratio);

                var fixtureDef:b2FixtureDef = new b2FixtureDef();
                fixtureDef.shape = fallingCrateShape;
                fixtureDef.density = 0.7;
                fixtureDef.friction = 0.5;
                fixtureDef.restitution = 0.3;//bouncyness

                fallingCrate.CreateFixture(fixtureDef);

    }

    addACrate(f1,270,0);
    trace(f1.GetPosition().y);

and when I try to access the "y" property of my "f1" object it tells me that it's null . I'll be appreciated if someone can tell me what's wrong
thanks

Upvotes: 0

Views: 98

Answers (2)

pho
pho

Reputation: 25489

well, you get a Null reference exception because you presumably haven't set the value of f1 anywhere. Solutions to this are:

In the function, use f1 = fallingCrate; at the end

or

Define the function as

public function addACrate(fallingCrate:b2Body, positionX:Number,positionY:Number):b2Body

and then call it as f1 = addACrate(arguments);

---EDIT---

You are sending a reference to the function, so it should work as intended if it weren't for this line:

fallingCrate =_world.CreateBody(fallingBodyDef);

This reassigns the value of fallingCrate, so fallingCrate no longer refers to the same object as f1.

The solutions mentioned above still apply :)

Upvotes: 0

divillysausages
divillysausages

Reputation: 8033

Either change the addACrate() function to return the b2Body instead of setting it, so your call is

f1 = this.addACrate( 270.0, 0.0 );

or, set f1 directly in the function (instead of using the fallingCrate parameter).

Then it should work. It has to do with the way Flash passes references. When you pass an object to a function, you can change properties inside that object, but you can't make it point to a new object. In your example fallingCrate is essentially a local variable that is set to whatever object you pass in when you make the call to addACrate. In your line

fallingCrate = _world.CreateBody(fallingBodyDef);

fallingCrate is now a local variable pointing to a new object. As fallingCrate is local, it goes out of scope when you exit the function.

Upvotes: 2

Related Questions