Reputation: 13
I have been bashing my head on this and I know that it's probably an easy fix but I can't for the life of me figure out what is wrong. I am trying to call a class function within a for loop and I've tried a few methods but i've come up with diddly-squat so far. I'll plug in the relevant snippets below. For reference this is a project to make a web-based simple game and I've chosen a bastardization of galaga and asteroids hence, "ship" and "asteroids." My question is why won't it populate the class function .spawn(); that's been assigned to the items in the "rock" iterative? Any advice would be extremely helpful.
var rock = []; //I know global variables = evil, but I'm still early in development
function setup() {
...
//Asteroids
for(var i = 0; i<5; i++){
var y = random(0,350);
var speed = random(2,5);
rock.push(new asteroid(800,y,speed,10));
}
...
}
function draw() {
...
//Spawn Asteroids
//rock[0].spawn(); //<-------Single instance of object from array(works as intended)
/*for (let c of rock){ //<-------Tried changing variable type to const as well because I was pulling my hair out and that did nothing either.
this.spawn();
}*/
/*for (let c in rock){ //<-------Covering my bases
this.spawn();
}*/
rock.forEach(index => this.spawn()); //<------Last thing I tried
...
}
//////////////////////////////////////////////////////////////////////////////
class asteroid {
...
spawn(){
this.move();
this.display();
this.offScreen();
this.speed = random(2,5);
}
...
}
////////////////////////////////////////////////////////////////////////////////////////////
Note: I tried to create a facsimile of another for loop that I used for
the ship attack but it didn't work either. It's this snippet below.
draw(){
this.bullets.forEach((bullet) => {
if(this.isBulletOffScreen(bullet)){
const index = this.bullets.indexOf(bullet);
this.bullets.splice(index, 1);
}
bullet.draw();
});
}
I don't have the one I tried to adapt because I felt I was way over complicating a simple object so I erased it but this is the working code for the projectile controller class that I was copying from.
P.S. Here is the Error message I keep getting.
*🌸 p5.js says: [sketch.js, line 86] "spawn" could not be called as a function. Verify whether "this" has "spawn" in it and check the spelling, letter-casing (JavaScript is case-sensitive) and its type.
- More info: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Not_a_function#What_went_wrong sketch.js:86*
** Uncaught TypeError: this.spawn is not a function at draw (sketch.js:86:10) at p5._main.default.redraw (p5.js:71990:27) at _draw (p5.js:64140:25) ​**
Upvotes: 0
Views: 294
Reputation: 13
@Teemu had the answer and it took a bit for my thick skull to work it out. By adjusting the forEach to resemble this:
rock.forEach(index => index.spawn());
They spawn and now I can start moving forward again. Thank you again Teemu!
Upvotes: 0