1

我是处理新手,想知道如何在指示的行上创建一个 for 循环以再创建 2 个椭圆?我想在不干扰椭圆轨迹的情况下创建这些椭圆。

     int xv = 200;
     int yv = 20;
     int xsp = 2;
     int ysp = 2;

     void setup() {
     size(700, 500);

     }

     void draw() {
     background(250);

     int xcoord = xv; { // x position. 
      **how do i create 2 more ellipses with a for     
      loop?
     int ycoord = yv;

   if (xcoord > width || xcoord < 0) { // left, right 
   walls
   xsp = -xsp; // move other direction
   }
   if (yv > height || yv < 0) { // top, bottom walls
   ysp = -ysp; // move in other direction
   }
   ellipse(xcoord, yv, 20, 20);

   xv= xv + xsp; // moves the ellipses
   yv = yv + ysp;
   }
4

1 回答 1

2

在这里,我为您制作了一个数组样式示例 :)

int howMany = 100;// 100?
//here you make empty arrays
float[] xv  = new float[howMany];
float[] yv  = new float[howMany];
float[] xsp = new float[howMany];
float[] ysp = new float[howMany];


     void setup() {
     size(700, 500);
      for (int i = 0; i < xv.length; i++){
      //they all have same length so... all at once
      // here you populate them...
      xv [i] = random(width);
      yv [i] = random(height);
      xsp[i] = random(-4,4);
      ysp[i] = random(-4,4);
      }
       fill(0,40);
     }

     void draw() {
     background(250);

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

       if(xv[i] > width || xv[i] < 0){
         xsp[i] = -xsp[i];
       }

       if(yv[i] > height || yv[i] < 0){
         ysp[i] = -ysp[i];
       }


       ellipse(xv[i], yv[i], 20, 20);
       xv[i] = xv[i] + xsp[i]; 
       yv[i] = yv[i] + ysp[i];
     }

   }

还有一个类(对象)示例:

int howMany = 100;// 100?
//here you make a empty array of type Sample
//One array to rule them all :)
Sample[] samples  = new Sample[howMany];



void setup() {
  size(700, 500);
  for (int i = 0; i < samples.length; i++) {
    // call the constructor to create each sample with random parameters
    samples[i] = new Sample(random(width), random(height), random(-4, 4), random(-4, 4));
  }
  fill(0,40);
}

void draw() {
  background(250);
  for (int i = 0; i < samples.length; i++) {
    //call methods...
    samples[i].display();
    samples[i].update();
  }
}



class Sample {

  //class vars
  float xv, yv, xsp, ysp;

  // a constructor
  Sample(float _xv, float _yv, float _xsp, float _ysp) {
    xv  = _xv;
    yv  = _yv;
    xsp = _xsp;
    ysp = _ysp;
  }


  void update() {

    if (xv > width || xv < 0) {
      xsp = -xsp;
    }

    if (yv > height || yv < 0) {
      ysp = -ysp;
    }

    xv+=xsp; 
    yv+=ysp;
  }

  void display() {
    ellipse(xv, yv, 20, 20);
  }
}
于 2013-09-18T17:05:23.833 回答