处理中的 Draw() 不更新屏幕

Draw() in Processing not updating screen

我是 Processing 的新手,我正在尝试 运行 一个程序,如果变量的值小于 20 则绘制圆,如果值大于 20 则绘制椭圆。问题如果我尝试使用数组的值,屏幕不会更新。它只取一个值并且不会改变。如果我只是创建一个随机数,那么它就可以工作。我还看到,当屏幕不更新时,终端中的值确实显示了正确的数字,因此程序 运行s 没有明显的错误。 (所有这些 println 仅用于调试目的...)

void draw () {

  delay(500);
  for (int i = 0; i < totalData.size(); i++) {
    record2 = totalData.getJSONObject(i);
    distance2 = int(record2.getString("field1"));
    //float distance2 = random(15, 25);
    
    println("distance2 is " + distance2);
    
    if (distance2 <= 20) { 
      println("triangle");
      background(500);
      triangle(30, 75, 58, 20, 86, 75);
      println("distance2 at if " + distance2);
       
    } else{
      background(1700);
      println("ellipse");
      ellipse(56, 46, 55, 55);
    
      println("distance at else is " + distance2);
        }
        
      println("distance2 at end " + distance2);
  
   }
}

@John Coleman 的评论很到位,但我会尽量提供更多细节,以便您正确理解问题:

首先查看draw()函数文档。它说:

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called. draw() is called automatically and should never be called explicitly. All Processing programs update the screen at the end of draw(), never earlier.

所以你的 draw() 函数已经是一个循环,你要做的是在函数外部创建 i 变量并在每次调用 draw() 时递增它:

int i = 0;
void draw () {
    record2 = totalData.getJSONObject(i);
    i++;
    distance2 = int(record2.getString("field1"));
    println("distance2 is " + distance2);

    if (distance2 <= 20) { 
        println("triangle");
        background(500);
        triangle(30, 75, 58, 20, 86, 75);
        println("distance2 at if " + distance2);
    } else{
        background(1700);
        println("ellipse");
        ellipse(56, 46, 55, 55);

        println("distance at else is " + distance2);
    }
    println("distance2 at end " + distance2);
}

这应该会给你预期的行为。

文档还说:

The number of times draw() executes in each second may be controlled with the frameRate() function.

您很可能想使用它而不是 delay() 来控制帧速率。

如果您想开始处理,阅读文档始终是一个好的开始,我还建议您查看 Daniel Shiffman youtube channel 这可能是您可以在网上找到的关于处理的最完整和最具指导意义的资源。