我知道有很多关于这个错误的帖子,但我在AS3上是新的,我无法弄清楚如何使用这些具体的答案来帮助我。
我在学校的一个项目上工作,我一直在
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at pong_fla::MainTimeline/loop()
我已经尝试过很多东西来尝试解决这个问题,但它仍然存在。 这是带有循环的代码。
var ballSpeedX: int = -6;
var ballSpeedY: int = -6;
var cpuPaddleSpeed: int = 3;
var playerScore: int = 0;
var cpuScore: int = 0;
var wintotal: int = 1;
init();
function init(): void {
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function calculateBallAngle(paddleY: Number, ballY: Number): Number {
var ySpeed: Number = 5 * ((ballY - paddleY) / 25);
return ySpeed;
}
function updateTextFields(): void {
playerScoreText.text = ("Player Score: " + playerScore);
cpuScoreText.text = ("CPU Score: " + cpuScore);
}
function loop(e: Event): void {
if (playerScore == wintotal) {
gotoAndStop(3);
}
if (cpuScore == wintotal) {
gotoAndStop(4);
}
if (playerPaddle.hitTestObject(ball) == true) {
if (ballSpeedX < 0) {
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(playerPaddle.y, ball.y);
}
} else if (cpuPaddle.hitTestObject(ball) == true) {
if (ballSpeedX > 0) {
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(cpuPaddle.y, ball.y);
}
}
if (cpuPaddle.y < ball.y - 10) {
cpuPaddle.y += cpuPaddleSpeed;
} else if (cpuPaddle.y > ball.y + 10) {
cpuPaddle.y -= cpuPaddleSpeed;
}
playerPaddle.y = mouseY;
if (playerPaddle.y - playerPaddle.height / 2 < 0) {
playerPaddle.y = playerPaddle.height / 2;
} else if (playerPaddle.y + playerPaddle.height / 2 > stage.stageHeight) {
playerPaddle.y = stage.stageHeight - playerPaddle.height / 2;
}
ball.x += ballSpeedX;
ball.y += ballSpeedY;
if (ball.x <= ball.width / 2) {
ball.x = ball.width / 2;
ballSpeedX *= -1;
cpuScore++;
updateTextFields();
} else if (ball.x >= stage.stageWidth - ball.width / 2) {
ball.x = stage.stageWidth - ball.width / 2;
ballSpeedX *= -1;
playerScore++;
updateTextFields();
}
if (ball.y <= ball.height / 2) {
ball.y = ball.height / 2;
ballSpeedY *= -1;
} else if (ball.y >= stage.stageHeight - ball.height / 2) {
ball.y = stage.stageHeight - ball.height / 2;
ballSpeedY *= -1;
}
}
我是StackOverflow的新手,如果我能改进我的问题,请告诉我。
以下是完整档案: DropBox Link
答案 0 :(得分:1)
MovieClips
在其他框架中不存在
删除侦听器修复了大多数错误(但不是所有错误)
if (playerScore == wintotal) {
//remove the listener when leaving the frame
stage.removeEventListener(Event.ENTER_FRAME, loop);
gotoAndStop(3);
}
if (cpuScore == wintotal) {
//remove the listener when leaving the frame
stage.removeEventListener(Event.ENTER_FRAME, loop);
gotoAndStop(4);
}
//check if MovieClips exist
if(!playerPaddle || !cpuPaddle){
return;
}
答案 1 :(得分:0)
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at pong_fla::MainTimeline/loop()
实际上这个错误说明该怎么做。 Flash无法在舞台上找到MC或MC没有使用该属性;)只需再次检查您的代码并使用跟踪来检测导致错误的原因。
答案 2 :(得分:0)
当ActionScript无法在当前作用域中找到对象引用时,将引发此错误。我会仔细检查播放器Paddle和球是否存在于舞台上而不是在MovieClips中。记住实例名称区分大小写,因此Ball不会与ball相同。