空对象错误;无法访问它 - AS3

时间:2013-10-24 10:06:16

标签: actionscript-3 function flex null

我正在制作一款平台游戏。我试图让玩家在舞台上四处移动,并且能够跳跃,并添加一些重力。但是,当我运行它时,我收到此错误:错误#1009:无法访问空对象引用的属性或方法。

package {

import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.ui.Keyboard;

public class Code1 extends MovieClip {

    var charSpeed:int = 0;
    var velocity:int = 0;
    var gravity:Number = 1;
    var Jump:Boolean = false;
    var leftKey:Boolean;
    var rightKey:Boolean;
    var upKey:Boolean;

    private var platform:Platform;

    public function startGame(){
         stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeyDown);
         stage.addEventListener(KeyboardEvent.KEY_UP, checkKeyUp);
         stage.addEventListener(Event.ENTER_FRAME, loop);
         stage.addEventListener(Event.ENTER_FRAME, update);
    }

    public function Code() {
    }

    public function update(evt:Event){
        moveChar();
    }

    public function moveChar(){
        if (leftKey == true){
            charSpeed -= 10;
        }
        if (rightKey == true){
            charSpeed += 10;
        }
        if (upKey == true){
            if(!Jump){
                velocity -= 14;
                Jump = true;
            }
        }
    }


    function checkKeyDown(evt:KeyboardEvent){
        if (evt.keyCode == Keyboard.UP){
            upKey = true;
        }
        else if (evt.keyCode == Keyboard.RIGHT){
            rightKey = true;
        }
        else if (evt.keyCode == Keyboard.LEFT){
            leftKey = true;
        }
    }

    function checkKeyUp(evt:KeyboardEvent){
        if (evt.keyCode == Keyboard.UP){
            upKey = false;
        }
        else if (evt.keyCode == Keyboard.RIGHT){
            rightKey = false;
        }
        else if (evt.keyCode == Keyboard.LEFT){
            leftKey = false;
        }
    }

    function loop(evt:Event){
        player.x = charSpeed;
        if (player.x < 0){
             player.x = 0;
        }
        if (player.x > 550){
             player.x = 550;
        }

        velocity += gravity;

        if (!platform.hitTestPoint(player.x, player.y, true)){
            player.y += velocity;
        }

        for (var i = 0; i < 10; i++){
            if (platform.hitTestPoint(player.x, player.y, true)){
                player.y--;
                velocity = 0;
                Jump = false;
            }
        }
    }
}

}

我的平台链接是“平台”,但我为它设置了一个变量(或尝试过)。我调试了代码,它提出了这一行:player.x = charSpeed; 我不知道该怎么做,如果有人可以提供帮助,那就太好了。

2 个答案:

答案 0 :(得分:0)

你永远不会宣告或实例化(即玩家=新玩家())你的玩家 或者,如果您的播放器位于.fla时间轴的舞台上,则需要实例名称“播放器”。这可以在对象属性中设置。

答案 1 :(得分:0)

您的玩家对象为空。

我没有将istantiation行看作:

var player:Player = new Player();

在使用播放器的属性

之前添加它