处理 - 使对象消失并出现在某些时间范围内

时间:2018-04-04 05:57:12

标签: java random time processing

这是我目前的代码:

int doorCounter = 0;

void setup()
{
 size(512, 348); //width and height of screen
 doorCounter = (int)random(180,300);
}

void draw()
{
 display();
 doorCounter = doorCounter - 1; // Decrease count by 1
 if (doorCounter <= 0) 
  {
   fill(255);
   rect(420, 190, 55, 100); //house door outline
   rect(435, 210, 25, 25, 7); // house door window
   ellipse(435, 255, 8, 8); // house door handle 
   doorCounter = (int)random(180,480); 
  }
}

void display()
{
  fill(255);
  rect(420, 190, 55, 100); //house door outline
  fill(0,0,0); // fill the following polygons in black
  rect(435, 210, 25, 25, 7); // house door window
  ellipse(435, 255, 8, 8); // house door handle
}

然而,这段代码所做的只是使对象在几分之一秒内消失,只是让它立即重新出现。如何使对象在随机间隔内保持消失3-8秒,就像对象在3-8秒内消失一样,因为它仍在屏幕上?

P.s我不知道我想要实现的目标是否有意义所以请随意提问。

1 个答案:

答案 0 :(得分:1)

一个想法是使用时间戳并检查从中经过的时间,如下所示:

int min_time = 3000; // in ms
int max_time = 8000; // in ms

int time_frame = (int)random(min_time, max_time);

int time_stamp = 0;

boolean show_door = true;

void setup()
{
  size(512, 348); //width and height of screen
}

void draw()
{
  background(200);

  int time_passed = millis() - time_stamp;

  if (time_passed < time_frame && show_door) {
    display();
  } else if (time_passed >= time_frame) {
    time_stamp = millis();
    time_frame = (int)random(min_time, max_time);
    show_door = !show_door;
  }
}

void display()
{
  fill(255);
  rect(420, 190, 55, 100); //house door outline
  fill(0, 0, 0); // fill the following polygons in black
  rect(435, 210, 25, 25, 7); // house door window
  ellipse(435, 255, 8, 8); // house door handle
}