我正在学习神经网络(并同时学习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;
}
}
obstacle.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;
}
}
}
}