1

我想知道如何更改以下代码,以便将形成花瓣的圆圈存储在数​​组中。所以我可以在另一个功能中使用它。

   void setup() {
     size(400, 400);
     smooth();
     noStroke();
  // frameRate(15);
  }

  void draw() {
    String[] circles = new String[5];
    int c1 = 0;
    int c2 = -40;
    int c3 = 50;
    int c4 = 50;
   // set centre point
    translate(width/2, height/2);
    fill(#c6ff89); // green
    for (int i = 0; i < circles.length; i++) {
      ellipse(c1, c2, c3, c4);
       rotate(radians(72));

    }
   // centre circle
   fill(#fff9bb); // light yellow
   ellipse(0, 0, 50, 50);
  }

谁能向我解释如何将其更改为更加面向对象的形式?这是在处理中。

4

2 回答 2

2

假设您ellipse正在返回EclipseObject 并且您想要创建5 circles,请创建一个数组作为类变量private Eclipse[] myCircles = new Eclipse[5];然后改变你的for循环如下:

for (int i = 0; i < circles.length; i++) {
   Eclipse cicrle = ellipse(c1, c2, c3, c4);
   rotate(radians(72));
   myCircles[i] = cicrle;
}

请注意:根据您的程序更改对象类名称和数组大小。

于 2012-11-19T04:23:20.973 回答
2

注意:正如代码所示,String[] 圈子没有用...

在这里,我以处理方式写了一个示例......希望它有所帮助:

//an array of your class type
Flower[] flowers = new Flower [3];
// one alone..
Flower atMouse = new Flower(0, 0);

void setup() {
  size(400, 400);

  // initialize objects
  for (int i=0; i < flowers.length;i++)
  {
    int pos = i+1;
    flowers[i] = new Flower (pos*100, pos*100);
  }
  smooth();
  background(255);
}

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

  atMouse.display(mouseX, mouseY);
}

class Flower {

  //class member variables
  float posX;
  float posY;
  int c1 = 0;
  int c2 = -40;
  int c3 = 50;
  int c4 = 50;

  // a constructor
  Flower(float _posX, float _posY)
  {
    //just pass vars
    posX = _posX;
    posY = _posY;
  }

  void display()
  {
    noStroke();
    pushMatrix();
    translate(posX, posY);
    fill(#c6ff89); // green
    for (int i = 0; i < 5; i++) {
      ellipse(c1, c2, c3, c4);
      rotate(radians(72));
    }
    popMatrix();
    // centre circle
    fill(#fff9bb); // light yellow
    ellipse(posX, posY, 50, 50);
  }

  //an overloaded version to keep pos updating...
  void display(float px, float py)
  {
    noStroke();
    pushMatrix();
    translate(px, py); // here use px instead...
    fill(#c6ff89); // green
    for (int i = 0; i < 5; i++) {
      ellipse(c1, c2, c3, c4);
      rotate(radians(72));
    }
    popMatrix();
    // centre circle
    fill(#fff9bb); // light yellow
    ellipse(px, py, 50, 50);//also here
  }
}//eofcl
于 2012-11-19T14:02:36.853 回答