括号 p5.js "Uncaught TypeError: Cannot read property 'offscreen' of undefined"



我现在正在学习神经网络(同时学习JS(,想从Javascript的小游戏开始,来实现我学到的东西。所以首先要做的是,创建一个游戏,应该不会太难吧?井。。看起来我太盲目了,找不到错误,所以如果有人能帮助我,我会很高兴。

我收到以下错误消息:"未捕获的类型错误:无法读取未定义的属性'屏幕外'"。

它发生在玩家死亡时。我想这与"重置"时清除的数组有关,也许 for 循环仍然尝试删除屏幕外管道,但它不能,因为数组是空的或类似的东西。不知道如何解决这个问题。

https://thumbs.gfycat.com/WanDifficultAnaconda-size_restricted.gif

游戏只是一个简单的"物体飞到你身边,你必须跳过它们"。

这是整个代码,它真的不多:

素描.js

let obstacle;
let player;
let obstacles = [];
let score = 0;
let highscore = 0;
function setup() {
createCanvas(600, 600);
obstacle = new Obstacle();
player = new Player();
}
function draw() {
background(0, 128, 128);
for(let i = obstacles.length-1; i >= 0; i--) {
if(obstacles[i].hits(player)) {
reset();
}
if(obstacles[i].offscreen()) {
obstacles.splice(i, 1);
}
obstacles[i].show();
obstacles[i].update();
}
player.show();
player.update();
score++;
currentScore();
newhighscore();
if(frameCount % 100 == 0) {
obstacles.push(new Obstacle());
}

}

function keyPressed() {
if(keyCode == 87 && player.y + player.h == height) {
player.jump();
}
}
function reset() {
if(score > highscore) {
highscore = score;
}
obstacles = [];
score = 0;
player = new Player();
}
function currentScore() {
strokeWeight(0);
stroke(102,205,170);
fill(14,47,68);
textSize(24);
text(score, 10, 30);
}
function newhighscore() {
strokeWeight(0);
stroke(102,205,170);
fill(14,47,68);
textSize(16);
text(highscore, 11, 48);
}

播放器.js

class Player {
constructor() {
this.x = 100;
this.h = 30;
this.w = this.h;
this.y = height - this.h;
this.gravity = 0.5;  
this.lift = -9; 
this.velocity = 0;
}
show() {
fill(0);
rect(this.x, this.y, this.w, this.h);
}
update() {
this.velocity += this.gravity;
this.y += this.velocity;
if(this.y + this.h > height) {
this.y = height - this.h;
this.velocity = 0;
}
}
jump() {
this.velocity += this.lift;
}
}

障碍.js

class Obstacle {
constructor() {
this.x = width;
this.h = random(30, 50);
this.w = this.h; 
this.y = height-this.h;
this.speed = 5;
}
show() {
noStroke();
fill(255, 115, 115);
rect(this.x, this.y, this.w, this.h); 
}
update() {
this.x -= this.speed;
}
offscreen() {
if(this.x < -width) {
return true;
} else {
false;
}
} 
hits(player) {
if(player.x <= this.x + this.w && player.x + player.w >= this.x) {
if(player.y + player.h >= this.y) {
return true;
} else {
return false;
}
}
}
}

我的解决方案

解释

是的,您的原因是正确的,当调用reset()时,它会更改为obstacles = []但是

for(let i = obstacles.length-1; i >= 0; i--) {
if(obstacles[i].hits(player)) {
reset();
...*Continued*
}

在您的绘图功能中仍然继续。所以你只需要添加休息时间;在重置后的命中条件下。在我上传的链接中看到它完全可以正常工作。

for(let i = obstacles.length-1; i >= 0; i--) {
if(obstacles[i].hits(player)) {
reset();
break;
...*Continued*
}

添加 break 时,for 循环将终止并向下移动到后面的函数。由于obstacles = []为空,因此不会显示undefined错误,因为无法访问空索引。

相关内容

最新更新