简体   繁体   中英

P5.JS .show() is not a function, why?

Not sure if i'm getting the scope wrong but iv'e tried moving the function around a bit but it just gives me that is not a function error.

 let bubbles = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++){ bubbles[i] = new Bubble(200, 200, 40) } } function draw() { background(0); for (i = 0; i < bubbles.length; i++){ bubbles[i].show(); }} function show() { stroke(20); strokeWeight(2); fill(random(255), 0, random(255)) ellipse(this.x, this.y, this.r * 2) } class Bubble { constuctor(x, y, r){ this.x = x; this.y = y; this.r = r; }}

As said in the comments by Rabbid76, your main problem is that you are calling a function within the Bubble object which doesn't exist. So you should pop that into the Bubble class:

class Bubble {
    constructor(x, y, r){
    this.x = x;
    this.y = y;
    this.r = r;
  }
    
  show() {
    stroke(20);
    strokeWeight(2);
    fill(random(255), 0, random(255))
    ellipse(this.x, this.y, this.r * 2)
  }
}

Also, just so you know you misspelt constructor and if you're using the p5 online editor it doesn't flag it as an error, it thinks you've defined a new function called constuctor it is completely valid syntax.

One more thing, you are passing in the x and y location of each bubble as 200, 200 , which basically means each bubble is going to be on top of each other, I'm assuming you'd want them to be spread out around the screen:

bubbles[i] = new Bubble(random(width), random(height), 20);

Oh and also, you may want to store the r,g,b colours in the Bubble object so it doesn't choose a new colour each frame!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM