Why this line drawing animation shows up only when I put my variables on top of my coding?

edited September 2017 in Questions about Code

Hello yall, I 'd like to draw lines with 20 pixels increments like below.

However, when I put "int x=0" after void draw(), I couldn't see anything.

Why it doesn't show anythiing?

Case one

int x = 0;

void setup() {
  size(400,300);
}

void draw() {
  background(0);
  strokeWeight(2);
  stroke(255);
  line (x,0,x,height);
  x = x+20;
}

case two

void setup() {
  size(400,300);
}

void draw() {
  int x = 0;
  background(0);
  strokeWeight(2);
  stroke(255);
  line (x,0,x,height);
  x = x+20;
}
Tagged:

Answers

  • edited September 2017 Answer ✓

    I made this for you:

    int x = 0; ArrayList<Integer> xHistory = new ArrayList<Integer>();
    void setup() {
     size(400,300);
    }
    void draw() {
     background(0);
     strokeWeight(2);
     stroke(255);
     for (int next : xHistory) {
      line (next, 0, next, height);
     }
     if (x <= width) {
      xHistory.add(x);
      x += 20;
     } else {
      xHistory.clear();
      x = 0;
     }
    } 
    

    I apologize for the weird formatting, I'm new to the forums.

  • Answer ✓

    Draw is a loop, it is called repeatedly.

    In case 1 it is called repeatedly and X increments because X is global, so you see lots of lines.

    In case 2 it is called repeatedly but X is local so it's always 0. You see 1 line at x = 0, lots of times.

  • Answer ✓

    Read the FAQ about setup and draw.

    And the one about formatting code.

  • Answer ✓

    And all the others whilst you are there.

Sign In or Register to comment.