[英]p5.js 27646: Uncaught TypeError: Cannot read property '0' of undefined
[英]Brackets p5.js “Uncaught TypeError: Cannot read property 'offscreen' of undefined”
我目前正在學習神經網絡(同時學習JS),並希望從Javascript的一個小游戲開始以實現我學到的東西。 所以首先要做的是創建游戲,難道不應該太難了吧? 好吧..看來我太盲目找不到錯誤,所以如果有人可以幫助我,我將非常高興。
我收到以下錯誤消息:“未捕獲的TypeError:無法讀取未定義的屬性'offscreen'”。
它在玩家死亡時發生。 我猜想這與“重置”時清除數組有關,也許for循環然后仍嘗試刪除屏幕外管道,但它不能,因為數組為空或類似的東西。 不知道如何解決這個問題。
https://thumbs.gfycat.com/WanDifficultAnaconda-size_restricted.gif
游戲只是一個簡單的“物體飛向您而您必須跳過它們”。
這是整個代碼,實際上並不多:
sketch.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);
}
player.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;
}
}
barrier.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
錯誤,因為未訪問空索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.