无法从方法访问阶段属性?
我的舞台上有一个对象,称为 obj。
我还有一个名为“物理”的课程,其中包含一堆物理方法,例如惯性、重力和墙壁弹跳。为了执行其中一些操作,我需要访问 stage.stageWidth 和 stageHeight 属性。
我的代码如下:
public function wallBounce(obj)
{
this.stageRef = stageRef
if (obj.x > stageRef.stageWidth || obj.x < 0)
{
obj.vX = (obj.vX * -1) * bounceConst
}
}
这应该检查对象的x值是否大于stageWidth或小于0。当我运行这段代码时,它说:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
我是一个半新手程序员,完全自学成才,没有知道是什么原因造成的。我花了一点谷歌搜索它,我认为它与作用域有关,但我不知道如何解决这个问题,甚至几乎不知道作用域的真正作用。
再次,抱歉,如果这是一个非常愚蠢的问题,但我就是不知道我做错了什么。
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 have 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我没有在该函数中看到任何对
stageRef
的引用?另外,因为您是在类中工作 -this.val
和val
是同一件事。您不妨去:或者
问题基本上是
stageRef
is null - 这有帮助吗?看来你的意思是:this.stageRef = <对你在其他地方定义的阶段的一些引用>;
这样做似乎很奇怪 - 只要你想要的对象从 DisplayList 上调用
wallBounce()
,您将能够通过stage
访问舞台。如果您想避免此函数中的错误(也许它在实际添加到 DisplayList 之前运行一次),则只需将其放在顶部即可:因此:
return
基本上会当场结束该函数。根据评论:
可以在保存舞台的文档类中创建一个静态属性。像这样:
然后你可以从其他类访问舞台,像这样:
I don't see any reference to
stageRef
from this function? Also, because you're working from within a class -this.val
andval
are the same thing. You may as well be going:Or
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 viastage
. 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:So:
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:
Then you can access the stage from your other classes like so: