开发者

Cannot access stage properties from a method?

I have an object on my stage, called obj.

I also have a class called "Physics" which contains a bunch of methods for physics, such as inertia, gravity, and bouncing off walls. In order to do some of these, I need access to the stage.stageWidth and stageHeight properties.

My code is as follows:

        public function wallBounce(obj)
    {
        this.stageRef = stageRef
        if (obj.x > stageRef.stageWidth || obj.x < 0)
        {
            obj.vX = (obj.vX * -1) * bounceConst
        }
    }

This is supposed to check if the object's x value is greater than the stageWidth or less than 0. When I run this code it says:

TypeError: Error #1009: Cannot access a property or method of a null object reference.

I am a semi-newbie programmer who is completely self-taught and hav开发者_运维问答e no clue what is causing this. I spent a bit googling it, and I think it has something to do with scopes, but I don't know how to fix this, and barely even know what scopes really do.

Again, sorry if this a really stupid question, but I just can't figure out what I'm doing wrong.


this.stageRef = stageRef;

I don't see any reference to stageRef from this function? Also, because you're working from within a class - this.val and val are the same thing. You may as well be going:

this.stageRef = this.stageRef;

Or

stageRef = stageRef;

The issue basically is stageRef is null - does this help? It seems you're meaning to say:

this.stageRef = <some reference to stage youve defined somewhere else>;

Seems odd to do it this way - as long as the object you're trying to call wallBounce() from is on the DisplayList, you'll be able to access the stage via stage. If you want to avoid errors in this function (maybe it runs once before it's actually been added to the DisplayList), then just put at the top:

if(!stage) return;

So:

public function wallBounce(obj:Object):void
{
    if(!stage) return;

    //this.stageRef = stageRef
    if (obj.x > stage.stageWidth || obj.x < 0)
    {
        obj.vX = (obj.vX * -1) * bounceConst
    }
}

return will essentially end the function on the spot.

As per comment:

Could make a static property in your Document Class that holds the stage. Like so:

package
{
    import flash.display.MovieClip;
    import flash.display.Stage;

    public class DocumentClass extends MovieClip
    {
        // vars
        public static var stageRef:Stage;

        /**
         * Constructor
         */
        public function DocumentClass()
        {
            stageRef = stage;
        }
    }
}

Then you can access the stage from your other classes like so:

public function wallBounce(obj:Object):void
{
    //this.stageRef = stageRef
    if (obj.x > DocumentClass.stageRef.stageWidth || obj.x < 0)
    {
        obj.vX = (obj.vX * -1) * bounceConst
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜