0

我有这个代码:

boolean run;

void setup() {
  size(1440, 900, P3D);
  background(0);
}

void draw() {

  if (keyPressed && key == 'K') {
    run = true;
  } 

  while (run) {
    stroke(100, 200);
    fill(255, 200);
    float xstart = random(10);
    float ynoise = random(10);

    translate(width/2, height/2, 0);

    for (float y=-(height/8);y<=(height/8);y+=3) {
      ynoise += 0.02;
      float xnoise = xstart;

      for (float x=-(height/8);x<=(height/8);x+=3) {
        xnoise += 0.02;
        drawPoint(x, y, noise(xnoise, ynoise));
      }
    }
    run = false;
  }

  if (keyPressed && key == ENTER) {
    background(0);
  }
}

void drawPoint(float x, float y, float noiseFactor) {
  pushMatrix();
  translate(x*noiseFactor*4, y*noiseFactor*4, -y);
  float edgeSize = noiseFactor*26;
  ellipse(0, 0, edgeSize, edgeSize);
  popMatrix();
}

但是,如果我按“k”,while 循环中的代码不会运行。关于为什么会这样的任何建议?

4

2 回答 2

3

尝试按 shift + k.... 或将代码更改为:

(keyPressed && (key == 'K' || key == 'k'))

附带说明...如果您想按一次按钮并触发一次效果,则使用void keyPressed()可能会更好

于 2013-11-08T16:36:02.577 回答
1

按键时可以使用noLoop()功能和整个场景。redraw()

void setup() {
  size(1440, 900, P3D);
  background(0);
  noLoop();
}

void draw() {
  stroke(100, 200);
  fill(255, 200);
  float xstart = random(10);
  float ynoise = random(10);

  translate(width/2, height/2, 0);

  for (float y=-(height/8);y<=(height/8);y+=3) {
    ynoise += 0.02;
    float xnoise = xstart;

    for (float x=-(height/8);x<=(height/8);x+=3) {
      xnoise += 0.02;
      drawPoint(x, y, noise(xnoise, ynoise));
    }
  }
}

void drawPoint(float x, float y, float noiseFactor) {
  pushMatrix();
  translate(x*noiseFactor*4, y*noiseFactor*4, -y);
  float edgeSize = noiseFactor*26;
  ellipse(0, 0, edgeSize, edgeSize);
  popMatrix();
}

void keyPressed(){
  if(key == 'K' || key == 'k')
    redraw();

  if(key == ENTER){
    redraw();
    background(0);
  }      
}
于 2013-11-09T19:19:15.120 回答