2017-10-28 18 views
0

私はP5 setup()関数でオブジェクトの配列を作成し、問題なく描画できます。しかし、私はP5のdraw()関数で同じオブジェクトを描画しようとすると動作しません。オブジェクトの配列をP5.js描画関数に渡すにはどうすればよいですか?

私は、オブジェクトをdraw()メソッドに渡していないので、P5 draw()の呼び出し方法がわからないため、問題が発生していると推測しています。

class Particle { 
    constructor(x, y, size) { 
    this.x = x; 
    this.y = y; 
    this.size = size; 
    } 

    display() { 
    ellipse(this.x, this.y, this.size, this.size); 
    } 
} 

function setup() { 

    var screenWidth = 720; 
    var screenHeight = 480; 
    var numberOfParticles = 10; 

    var particles = []; 

    for (var idx = 0; idx < numberOfParticles; idx++) { 
    size = Math.floor(Math.random() * 40) + 10; 
    x = Math.floor(Math.random() * (screenWidth - (size * 2))) + size; 
    y = Math.floor(Math.random() * (screenHeight - (size * 2))) + size; 
    var p = new Particle(x, y, size); 
    particles.push(p); 
    } 

    createCanvas(screenWidth,screenHeight); 

    background(100,150,200); 
    fill("yellow"); 

    // This displays the particles 
    for (var idx = 0; idx < particles.length; idx++) { 
    particles[idx].display(); 
    } 

} 

function draw() { 
    fill("green"); 

    // This DOESN'T display the particles 
    for (var idx = 0; idx < particles.length; idx++) { 
    particles[idx].display(); 
    } 

} 

答えて

0

draw()関数に引数を渡さないでください。 draw()関数は引数をとりません。

代わりに、ちょうどは、の両方の機能の外の変数を定義します。次にsetup()の機能でを初期化し、draw()の機能の中で使用できます。このように:

var textToDisplay; 

function setup(){ 
    createCanvas(500, 500); 
    textToDisplay = "hello world"; 
} 

function draw(){ 
    background(64); 
    text(textToDisplay, 100, 100); 
} 
+0

それでした。私がしなければならなかったのは、setup()とdraw()関数の外にある変数を定義することでした。スケッチが正しく機能しました。ありがとうございました!!! – jpummill

関連する問題