How to make this rotating square reverse direction

please format code with </> button * homework policy * asking questions

Hello! I’m quite new to this so this is probably really easy but I’ve made this rotating square that I want to, after having completed a certain percentage of the rotation, reverse direction and “swing back”. Then I want it to reverse direction again so it moves in the same direction again. Kind of like a pendulum (that’s not affected by gravity!).

I’ve tried to use if loops but I think I’m getting my maths confused because I told it to if <5, move forward and if>5 move backward, but of course, this means that it just freezes in place.

This is the code I have right now.

Thank you!

//moiree

int a = 0;


void setup(){
  size(800, 800, P2D);
  background(50);
}

void draw(){
  background(50);


pushMatrix();

rotate(radians(a));

// if (a>5){
// 	a=5;
//   a=a-0.05;
// };
	
	if (a<5){
a=a+0.05;
	}

  
for(float q=30; q<width -30; q=q+7){
  stroke(255);
  strokeWeight(2);
  line(50,q, width-50, q);
};
popMatrix();

pushMatrix();
for(float c=30; c<width -30; c=c+7){
  stroke(255);
  strokeWeight(2);
  line(50,c, width-50, c);
};
popMatrix();

print(a);


  

}

hi,
at each frame you evaluate a
and a is the current rotation, this information alone can’t tell if you need to rotate clockwise or anti-clockwise (it depends from wich direction you come from)
it means you need another information , aka another variable
many ways to do that , for eg:
you can use a boolean, eg boolean clockwise=true;
in pseudo code it will be:
if clockwise a=a+0.5 else a=a-0.5
then you need to define the rules when rotation is clockwise or reverse
if a>5 clockwise= false;
if a <-5 clockwise= true;

tell me if i 'm not clear

1 Like