# Moving multiple components left to right

**URL:** <https://discourse.processing.org/t/moving-multiple-components-left-to-right/28825>\
**Category:** Coding Questions\
**Tags:** homework\
**Created:** [March 25, 2021, 8:52am UTC](https://discourse.processing.org/t/moving-multiple-components-left-to-right/28825 "2021-03-25T08:52:46Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hwahwa](https://avatars.discourse-cdn.com/v4/letter/h/e99b99/32.png) [@hwahwa](https://discourse.processing.org/u/hwahwa)\
**Post date:** [March 25, 2021, 8:52am UTC](https://discourse.processing.org/t/moving-multiple-components-left-to-right/28825/1 "2021-03-25T08:52:46Z")

</div>

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 😃

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;  
}

}

---

<div class="post-metadata">

**Author:** ![SamTech](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/samtech/32/12897_2.png) [@SamTech](https://discourse.processing.org/u/SamTech)\
**Post date:** [March 25, 2021, 9:44am UTC](https://discourse.processing.org/t/moving-multiple-components-left-to-right/28825/2 "2021-03-25T09:44:57Z")

</div>

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.

```auto
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;
  }
}

```
