所以我在尝试运行游戏时遇到了这个错误。这是一个简单的小游戏,围绕拾取围绕着杰里罐的同时试图避开轨道上的敌人。所以我点击Ctrl + Shft + Enter,发现问题出现在第26行(if(this.y + ...)在我的船级。
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Ship extends Sprite
{
public function Ship(_x:int,_y:int)
{
this.x = _x;
this.y = _y;
//adds event listener that allows the player to move
addEventListener(Event.ENTER_FRAME, player_move);
}
public function player_move(e:Event)
{
//check if at left or right side of stage
if (this.y - this.height / 2 <= 0)
{
this.y = 50;
}
if (this.y + this.height / 2 >= stage.height - this.height)
{
this.y = 370;
}
if (this.x - this.width / 2 <= 0)
{
this.x = 50;
}
if (this.x + this.width / 2 >= stage.width - this.width)
{
this.x = 500;
}
}
public function left():void
{
//the speed in which the player will move left
this.x -= 10;
}
public function right():void
{
//the speed in which the player will move right
this.x += 10;
}
public function up():void
{
//the speed in which the player will move right
this.y -= 10;
}
public function down():void
{
//the speed in which the player will move right
this.y += 10;
}
}
}
现在该怎么办?我该如何解决?我无法在任何地方找到答案。我知道它与我的Main类有关,我已经说过,如果玩家是他的敌人,他的船将被放回原来的合作伙伴。
非常感谢任何帮助。感谢。
答案 0 :(得分:1)
您的null对象是stage
引用。每个DisplayObject都有一个对舞台的引用,但是,在对象实际上在舞台上之前,它是null。
舞台是您应用程序的主要容器。您应用程序中的所有可视化内容都将以某种方式出现在舞台上。您的主要文档类将在舞台上,所有时间轴对象等。
即使将对象添加到其他容器中,只要该容器以某种方式位于舞台上,您的对象就会被计入舞台。因此,要将其置于最基本的术语中,如果对象位于用户应该能够看到它的位置,则stage不会为null。
要解决此问题,您必须在将对象添加到舞台后添加ENTER_FRAME
事件侦听器。幸运的是,你可以听到发生这种情况时被触发的事件。
在构造函数中:
addEventListener(Event.ADDED_TO_STAGE, init);
然后添加你的处理程序:
private function init(evt:Event){
addEventListener(Event.ENTER_FRAME, player_move);
}
请记住,stage
将为空,直到将一个对象添加到舞台中,这是我们现在正在侦听的事件。然后,只需将您的船只添加到主游戏或其进入的任何容器container.addChild(ship)
,如果该容器是舞台的一部分,您应该很高兴。