-1

运行代码时出现此错误:

TypeError:错误 #1009:无法访问空对象引用的属性或方法。在脚本::Enemy/moveToward()

我假设它与在舞台上注册玩家有关。到目前为止,我有 3 个课程:引擎、玩家和敌人。我目前正在构建一个横向滚动击败 em up 游戏。

package scripts 
{
    import flash.display.*;
    import flash.events.*;
    import flash.events.Event;
    import flash.display.Stage;

    public class Enemy extends MovieClip
    {
        var enemySpeed: Number = 3;
        var xDistance: Number = 50
        var yDistance: Number = 20;

        public var player: Player;

                public function Enemy()
                {
                        this.addEventListener(Event.ADDED_TO_STAGE, addListeners)
                }

        public function addListeners(event: Event):void
        {
            stage.addEventListener(Event.ENTER_FRAME, moveToward);
            trace("handeled");
        }

        function moveToward(event: Event):void
        {
            if(this.x < player.x - xDistance)
            {
                this.x += enemySpeed;
                this.scaleX = -1;
            }
            if(this(root).x > player.x+xDistance)
            {
                this.x -= enemySpeed;
                this. scaleX = 1;
            }

            if(this.y < player.y-yDistance)
            {
                this.y += enemySpeed;
            }
            if(this.y > player.y+yDistance)
            {
                this.y -= enemySpeed;
            }
        }
4

1 回答 1

0

当调用“moveForward”时,“Player”很可能没有被初始化或实例化。这通常发生在影片剪辑的第一帧事件期间。您可以考虑在 moveForward 方法中添加一条语句:

if ( player == null )
{
    return;
}
于 2012-07-10T16:57:09.483 回答