Processing: How do i create an object every “x” ti

2019-01-20 18:42发布

问题:

What I want to do is to create a new planet in my system for example every 10 seconds and that it starts to move and also prints a "hello" . At the end I want that the 8 planets (ellipses) will be moving together.

I try to use delay(); but I failed .

Can someone help me please?

Planet [] planetCollection = new Planet [8];
float [] wid2 = {100,200,300,400,500,600,700,800};
float [] hig2 = {50,75,100,125,150,175,200,225};
int [] colorR = {100,800,300,400,500,600,700,800};
int [] colorG = {50,225,100,125,150,175,200,225};
int [] colorB = {50,225,100,125,150,175,200,225};
int [] size =   {10,12,14,16,18,20,22,24};
int lastTime =0;
int contador =0;

void setup (){
      size (1600,1600);
      smooth();

      //INITIALIZE

      for (int i=0 ; i<planetCollection.length; i++){

         planetCollection [i] = new Planet(wid2[i], hig2[i], colorR[i], 
            colorG[i], colorB[i], size[i]);
         }

}

void draw (){
      background (0);

      //CALL FUNCIONALITY

      for (int i=0 ; i<planetCollection.length; i++){
        planetCollection [i].run();
      }
}



    class Planet {
    //GLOBAL VARIABLES
    float val;
    float x = 0;
    float y = 0;
    float wid2;
    float hig2;
    float speed;
    int colorR;
    int colorG;
    int colorB;
    int size;
    int centerx = width/2;
    int centery = height/4;


    //CONTRUCTOR
    Planet(float _w, float _h,int _colorR,int _colorG,int _colorB, int _size){

    wid2=_w;
    hig2=_h;
    colorR= _colorR;
    colorG= _colorG;
    colorB= _colorB;
    size = _size;



    speed=10/(2*PI * sqrt ((pow(wid2,2)+pow (hig2,2)/2))); ;

    }


    //FUNCTIONS

    void run (){
    move();
    display();
    }
    void move (){
      x= sin (val);
      y= cos(val);
      x *=wid2;
      y *=hig2;
      //SUN/CENTER
      noStroke();
      fill (255,238,41);
      ellipse (centerx,centery,40,40);
      if (dist (mouseX,mouseY,centerx,centery)<20){
      if(mousePressed){
      speed =0;
      }
      }
      //
      x+= centerx;
      y+= centery;
      val += speed;

      }



      void display (){
        //PLanets
      fill(colorR, colorG, colorB);
      ellipse(x, y, size, size);
      ///Orbits
      noFill();
      stroke(255);
     ellipse(centerx, centery, wid2*2, hig2*2);
      println ("posicionx "+x); 
      println ("posiciony "+y);
      println ("width "+wid2);
      println ("high "+hig2);
      println ("val "+val);
      println ("speed "+speed);


      }


    }

回答1:

You can use the modulo % operator along with the frameCount variable inside the draw() function to do something every X frames.

Here is an example program that draws little circles most frames, but draws a big circle every 60 frames:

void setup() {
  size(500, 500);
  background(0);
}

void draw() {

  ellipse(mouseX, mouseY, 10, 10);

  if (frameCount % 60 == 0) {
    ellipse(mouseX, mouseY, 50, 50);
  }
}