Changing moving direction when reaching an specific point?

Captura de Tela 2017-09-20 às 18.58.15](https://forum.processing.org/two/uploads/imageupload/959/YE1MDX5NDXBD.png "Captura de Tela 2017-09-20 às 18.58.15")

Hello everyone! I'm new to processing and I've got this program in which the line moves from the left edge to the right edge. When it reaches the right edge it appears back in the left and restart the loop. I wanna know how can I make it changes direction when hitting right edge and move back to the left. I tried conditions like if (pos > width ) {pos--} but it wouldn't work because when the line goes back to the start, the position becomes < width.

Hope you guys can help me. Thanks!

Here goes the original program:

void setup() { size(400, 400); frameRate(12); }

int pos=0;

void draw() { background(204); pos++; line(pos,20,pos,80); if (pos > width ) { pos=0; } }

Tagged:

Answers

  • _vk_vk
    edited September 2017

    That's a way to do it. You should format your code using at least 4 spaces before each line. Or selecting it and pressing the big C button above the editor.

    int dir = 1;
    int step = 1;
    
    void setup() { 
      size(400, 400); 
      frameRate(12);
    }
    
    int pos=0;
    
    void draw() { 
      background(204); 
      pos = pos + (step*dir); 
      line(pos, 20, pos, 80); 
      if (pos >= width || pos <= 0 ) { 
        dir = dir * -1;
      }
    }
    
  • The trick, as _vk has shown, is to make the direction a variable as well as the position. Then you can change the direction when it hits the edge, and that change is remembered because it is stored in the variable.

  • A recent question also addressed a similar issue (how to bounce a direction of change) only for a simple counter rather than a screen position:

Sign In or Register to comment.