Driving Effect / Moving Dividing Line

Hi, I want to create a “car avoiding game”. To make it look like the cars are driving I want to make the dividing line move constantly from top to bottom in a loop. How is that possible? Hopefully, someone is able to help me out with this problem!

This is my code:

void settings () {
  size(700, 700);
}

void draw() {
  background(0);
  fill(#07D339);
  rect (0, 0, 700, 700);
  fill(#9A9A9A);
  rect (100, 0, 500, 700);

  for (int i=0; i<700; i=i+44) {
    fill(#FFFFFF);
    rect(347, i, 6, 30);
  }

  for (int i=0; i<700; i=i+44) {
    fill(#FFFFFF);
    rect(222, i, 6, 30);
  }

  for (int i=0; i<700; i=i+44) {
    fill(#FFFFFF);
    rect(472, i, 6, 30);
  }
}
1 Like

The way I would go about doing this is to use a variable to keep track of an offset. Start by declaring a variable like:

// above settings
int offset = 0;

Then you can add the offset to where you are drawing the rectangle in the y position. Like:

// in for loops
rect(472, i + offset, 6, 30);

Then you need to increase or decrease the offset each frame. Like:

// at the end of the draw method
offset++; // the same as offset = offset + 1;
// or offset--; for -1

At this point, you can run to see what this variable is doing. But you’ll notice that it offset just keeps increasing and the lines go off the screen. So we can add an if statement to check if the offset is larger than the line and the space to the next line. If this is the case reset the offset to 0. Like:

// right after offset++;
if (offset >= 44) {
  offset = 0;
}

Then it should be running smoothly but because the lines are moving we have to add on more line so it doesn’t look like they just pop out of thin air. I would just change the start or end of the for loops. Like:

for (int i = -44; i < 700; i = i + 44) // if using offset++;
for (int i = 0; i < 744; i = i + 44) // if using offset--;

Here’s what I got if I put it all together:

int offset = 0;

void settings () {
  size(700, 700);
}

void draw() {
  background(0);
  fill(#07D339);
  rect (0, 0, 700, 700);
  fill(#9A9A9A);
  rect (100, 0, 500, 700);

  for (int i=-44; i<700; i=i+44) {
    fill(#FFFFFF);
    rect(347, i + offset, 6, 30);
  }

  for (int i=-44; i<700; i=i+44) {
    fill(#FFFFFF);
    rect(222, i + offset, 6, 30);
  }

  for (int i=-44; i<700; i=i+44) {
    fill(#FFFFFF);
    rect(472, i + offset, 6, 30);
  }

  offset++;
  if (offset >= 44) {
    offset = 0;
  }
}
2 Likes

Thank you, your answer was really helpful!

But do you have an idea why it is not running fluently? All moves seem to be “stucking”, also the driving cars etc? I tried to work with frameRate() but this didn’t help me.