在draw()方法中只运行一段代码

时间:2013-11-08 16:04:07

标签: while-loop processing

我有这段代码:

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循环中的代码不会运行。有关为什么会这样的建议吗?

2 个答案:

答案 0 :(得分:3)

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

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

侧面注释...如果您想按一次按钮并触发效果一旦您可能会更好地使用void keyPressed()

答案 1 :(得分: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);
  }      
}