Kresten
Kresten

Reputation: 838

Moving a rect with translate and a time delay?

I have this code. It was ment to print a rect 10 times moving it 60 pics to the right every time with a delay of 1000 ms before each print. It doesn't, and I don't understand why. Could someone please explain it to me?

int time;
int wait =1000;

void setup()
{
  time = millis();
  size(800, 200);
  background(255);
}

void draw() {
int i=0;
  while (i<10){
    if(millis() - time >= wait){
      time = millis();
    }

  translate(60, 0);
  rect(0, 0, 10, 10);
  }
}

Upvotes: 0

Views: 220

Answers (2)

Majlik
Majlik

Reputation: 1082

As @Petros mentioned you got yourself into infinite loop but it is easier to use delay() function and condition only how much times was rec printed.

int wait = 1000;
int translate = 0;
int count = 0;

void setup()
{  
  size(800, 200);
  background(255);
}

void draw() {
  if(count < 10)
  {
    delay(wait);
    translate += 60;
    translate(translate, 0);
    rect(0, 0, 10, 10);
    count++;
  }  
}

EDIT

Upgraded version so you can change MAXof printed rec. And it will also change size of canvas according to number of rec. Also added data stream to right and shifting down as wanted in comment.

int wait = 100;
int translate = 0;
int count = 0;
static final int MAX = 10;

void setup()
{  
  size(60*MAX, 12*MAX);
  background(255);
}

void draw() {
  if(count < MAX)
  {
    delay(wait);
    translate(translate, count*11);
    translate += 60;
    rect(0, 0, 10, 10);
    fill(50);
    text("Data", 15, 10);
    noFill();
    count++;
  }  
}

Upvotes: 0

Petros Koutsolampros
Petros Koutsolampros

Reputation: 2800

This is happening because you are preventing the draw() function from finishing. You do this by setting an integer i = 0 and then you say while (i<10) {}. Meanwhile you never change i thus the code is doing an infinite loop inside the while(), and never reaches the end of the draw() function which will refresh the canvas with the rectangles you want. You can't set your own rendering loop because Processing requires its own to finish in order to display. Thus you have to "go with its flow" and define everything along its loop, the draw() function.. Sort of like this:

int time;
int wait =1000;
int translateX;
void setup()
{
  time = millis();
  size(800, 200);
  background(255);
}

void draw() {
  if (millis() - time >= wait) {
    time = millis();
    translateX +=60;
    translate(translateX, 0);
    rect(0, 0, 10, 10);
  }
}

Upvotes: 1

Related Questions