2013-02-16 88 views
0

如何在一段時間後調用我的數組,以便在特定時間間隔內創建對象。我希望我的數組每3秒創建一個球體。如何在處理中使用回調函數?

Ball [] ball; 

void setup() 
{ 
    size(600,600,P3D); 

    ball = new Ball[3]; 
    ball[0] = new Ball(); 
    ball[1] = new Ball(); 
    ball[2] = new Ball(); 
} 

void draw() 
{ 
    background(255); 
    for (int i = 0; i < ball.length; i++) { 
     ball[i].drawBall(); 
    } 
} 

class Ball 
{ 
    float sphereSize = random(30, 90); 
    float sphereX = random(-2200, 2800); 
    float sphereY = 0; 
    float sphereZ = random(-2200, 2800); 

    void drawBall() 
    { 
    translate(sphereX, sphereY, sphereZ); 
    sphere(sphereSize); 
    sphereY +=1; 
    } 
} 

回答

1

最簡單的方法是使用計時功能將時間存儲在變量中,如millis()

的想法很簡單:

  1. 商店以前的時間和延遲的時間不斷
  2. 跟蹤如果當前時間比以前存儲的時間和延遲greather,然後延遲時間間隔已經過去。

這裏有一個簡單的草圖來說明這個想法:

int now,delay = 1000; 
    void setup(){ 
     now = millis(); 
    } 
    void draw(){ 
     if(millis() >= (now+delay)){//if the interval passed 
     //do something cool here 
     println((int)(frameCount/frameRate)%2==1 ? "tick":"tock"); 
     background((int)(frameCount/frameRate)%2==1 ? 0 : 255); 
     //finally update the previously store time 
     now = millis(); 
     } 
    } 

,並與您的代碼集成:

int ballsAdded = 0; 
int ballsTotal = 10; 
Ball [] ball; 

int now,delay = 1500; 

void setup() 
{ 
    size(600,600,P3D);sphereDetail(6);noStroke(); 
    ball = new Ball[ballsTotal]; 
    now = millis(); 
} 

void draw() 
{ 
    //update based on time 
    if(millis() >= (now+delay)){//if the current time is greater than the previous time+the delay, the delay has passed, therefore update at that interval 
    if(ballsAdded < ballsTotal) { 
     ball[ballsAdded] = new Ball(); 
     ballsAdded++; 
     println("added new ball: " + ballsAdded +"/"+ballsTotal); 
    } 
    now = millis(); 
    } 
    //render 
    background(255); 
    lights(); 
    //quick'n'dirty scene rotation 
    translate(width * .5, height * .5, -1000); 
    rotateX(map(mouseY,0,height,-PI,PI)); 
    rotateY(map(mouseX,0,width,PI,-PI)); 
    //finally draw the spheres 
    for (int i = 0; i < ballsAdded; i++) { 
     fill(map(i,0,ballsAdded,0,255));//visual cue to sphere's 'age' 
     ball[i].drawBall(); 
    } 
} 

class Ball 
{ 
    float sphereSize = random(30, 90); 
    float sphereX = random(-2200, 2800); 
    float sphereY = 0; 
    float sphereZ = random(-2200, 2800); 

    void drawBall() 
    { 
    pushMatrix(); 
    translate(sphereX, sphereY, sphereZ); 
    sphere(sphereSize); 
    sphereY +=1; 
    popMatrix(); 
    } 
} 
+0

感謝您抽出寶貴的時間來做到這一點。這正是我需要的。 – 2013-02-17 00:06:36

+0

不用擔心你的項目和善良! :) – 2013-02-17 00:16:05