Moving multiple components left to right

Hello, I’ve written some code that moves a rectangle and triangle (an arrow) to move left to right but I’m positive that there is a cleaner and more efficient way to do this. My code for this was a bit unorganised and I was wondering if there was a better way to do this. Any help would be greatly appreciated :smiley:

Here is my code:

float speedRect = 3;
float speedTri = 3;
float rectx = 50;

float trix1 = 25;
float trix2 = 65;
float trix3 = 105;

void setup(){
size(500, 500);
}

void draw(){
background(100);
rectMode(CORNER);
fill(50);
stroke(50);

ellipse(400, 100, 25, 25);
rect(rectx, 350, 30, 100);
triangle(trix1, 350, trix2, 300, trix3, 350);

rectx = rectx + speedRect;

trix1 = trix1 + speedTri;
trix2 = trix2 + speedTri;
trix3 = trix3 + speedTri;

if(rectx + 28 > width || rectx < 0) {
speedRect = speedRect * -1.0;
}

if(trix1 + 25 < 0) {
speedTri = speedTri * -1.0;
}

if(trix2 > width || trix2 < 0) {
speedTri = speedTri * -1.1;
}

if(trix3 - 25 > width || trix3 < 0) {
speedTri = speedTri * -1.0;
}

}

You can actually make it a lot easier:
Just use a single variable for position and speed. After all, the objects do not move relative to each other.
I’ve done the whole thing here and “mid” indicates the X coordinate of the center of the arrow.

float mid=65;
float speed=3;
void setup() {
  size(500, 500);
}

void draw() {
  background(100);
  rectMode(CORNER);
  fill(50);
  stroke(50);

  ellipse(400, 100, 25, 25);
  rect(mid-15, 350, 30, 100);
  triangle(mid-40, 350, mid, 300, mid+40, 350);

  mid+=speed;
  if (mid + 15 > width ||mid < 15) {
    speed *= -1.0;
  }
}