How would I make the line in the code bounce between the walls of the canvas?

Viewed 39

I am using processing and I am trying to get the rectangle to reverse its direction when it hits the side of the screen. Specifically, when the edge of the rectangle reaches the side of the window, the rectangle should change direction and start moving towards the other side instead of still going right. The direction should reverse again when it hits the other side of the window.

ArrayList<Ball> balls;
int rectWidth = 20;
int rectHeight = 20;

long lastTime = 0;
long lastTimeEllipse = 0;
float tx = 0; //x value TimeLine
float tx1 = 0; //x value Ellipse
float value = 0;

void setup() {
  size(400, 200);
  frameRate(60);
  balls = new ArrayList();
  lastTime = millis();
  lastTimeEllipse = millis();
}

void draw() {
  background(0);
  if ( millis() - lastTime > 500) {
    lastTime = millis();
    //after 0.5 sec. tx moves 40px to the right
    tx += 40;
    value = 2;
  } else if (millis()-lastTime < 500) {
    value = 1;
  }
  stroke(255, 0, 0);
  line(tx, 0, tx, height);
  if (tx>=width) {
    tx=0;
    tx1 = tx1 + width;
  }
2 Answers

You need to values. The current x coordinate of the line and the movement:

float tx = 0;
float dx = 40;

Every time when the line line reaches the left or right of the window, then change the direction:

tx += dx;
if (tx < 0 || tx >= width) {
    dx *= -1;
}

Example code:

long lastTime = 0;
long lastTimeEllipse = 0;
float tx = 0;
float dx = 40;

void setup() {
    size(400, 200);
    frameRate(60);
    lastTime = millis();
    lastTimeEllipse = millis();
}

void draw() {
    background(0);
    if ( millis() - lastTime > 500) {
        lastTime = millis();
        tx += dx;
        if (tx < 0 || tx >= width) {
            dx *= -1;
        }
    }
    stroke(255, 0, 0);
    line(tx, 0, tx, height);
}

You'll need to create a float speed (or something like that) and change that everytime x of the rectangle (which I'm guessing is tx?) is smaller than 0 or greater than width - rectWidth.

So declare the variable:

float speed = 40;

And after moving the rectangle in your draw method, do:

if(tx <= 0 || tx >= width - rectWidth)
    speed = -speed;
Related