# Triangle is Moving but is getting Bigger as it moves

I’m having trouble getting my triangle to stop getting bigger as it moves, any suggestions?

``````float xa=30;
float ya=75;
float xb=58;
float yb=20;
float xc=86;
float yc=75;
float xSpeed=10;
float ySpeed=10;

void setup(){
size(800,600);
}

void draw (){
background (0);
fill (225,225,225);
text("Cliking the mouse on the background might slow down the ball",200,20);
Ball();
}

void Ball(){
fill(255,0,0);
triangle (xa,ya,xb,yb,xc,yc);
xa=xa+xSpeed;
if (xa>width || xa<0){
xSpeed=xSpeed*-1;
}
ya=ya+ySpeed;
if (ya>height || ya<0){
ySpeed=ySpeed*-1;
}
xb=xb+xSpeed;
if (xb>width || xb<0){
xSpeed=xSpeed*-1;
}
yb=yb+ySpeed;
if (yb>height || yb<0){
ySpeed=ySpeed*-1;
}
xc=xc+xSpeed;
if (xc>width || xc<0){
xSpeed=xSpeed*-1;
}
yc=yc+ySpeed;
if (yc>height || yc<0){
ySpeed=ySpeed*-1;
}
}

void mouseReleased() {
if (.5<random(1)){
xSpeed=1;
ySpeed=1;
}
else{
xSpeed=10;
ySpeed=10;
}}
``````

In essence, this is what you want to do:

``````void Ball(){
fill(255,0,0);
triangle (xa,ya,xb,yb,xc,yc);
//have ALL of your points moving
xa=xa+xSpeed;
xb=xb+xSpeed;
xc=xc+xSpeed;
ya=ya+ySpeed;
yb=yb+ySpeed;
yc=yc+ySpeed;

if (xa>width || xa<0 || xb>width || xb<0 || xc>width || xc<0){ //if ANY of the X values s goes out of bounds, reverse everyone's speed
xSpeed=xSpeed*-1;
}

if (ya>height || ya<0 || yb>height || yb<0 || yc>height || yc<0 ){  //if ANY of the Y values s goes out of bounds, reverse everyone's speed
ySpeed=ySpeed*-1;
}

}
``````

You have all the right code, just the problem is you’re a little too specific. What you want, is that as soon as ANY point of the triangle goes out, to change xSpeed or ySpeed to the opposite direction. And then the triangle won’t grow or stretch. It used to grow, because sometimes some points would be going at an opposite xSpeed, while the rest would keep on going normally.

Hopefully this helps!

EnhancedLoop7

Thank you very much I see what you mean.

1 Like

Glad to hear that EnhancedLoop7

In general – with a triangle, rectangle, or anything else – don’t apply bounce rules to each point individually. This is asking for trouble.

Instead, track the center point of the object, and only move that – then draw the perimeter relative to that center. You can still do bounce checking logic on those perimeter points, but calculate them on the fly from the center – that way you only have one center, and the shape can never distort. (Unless you want it to distort!)

2 Likes