How to rotate this arm upwards?

Viewed 80

I am learning Java with the program named Processing. However, I cannot understand why my code do not work appropriately. I made a arm with this problem which should be rotated to upside or downside when I hold the mouse button, but it just works when I hold the left button on my mouse, and it does not work when I hold the right button. The problem is I do not know the problem of my code as follows.

float angle=0;
float angleDirection=1;
float speed=0.005;

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

void draw(){
  background(255,255,255);
  stroke(20,20,255);
  
  translate(400,300);
  rotate(angle);
  strokeWeight(18);
  line(0,0,140,0);
  pushMatrix();
  
  translate(140,0);
  rotate(angle*2.0);
  strokeWeight(14);
  line(0,0,100,0);
  
  translate(100,0);
  rotate(angle*2.5);
  strokeWeight(10);
  line(0,0,60,0);
  
  popMatrix();
  rotate(-angle*2.0);
  strokeWeight(18);
  line(0,0,-140,0);
  
  translate(-140,0);
  rotate(-angle*2.0);
  strokeWeight(14);
  line(0,0,-100,0);
  
  translate(-100,0);
  rotate(-angle*2.5);
  strokeWeight(10);
  line(0,0,-60,0);
  
if(mousePressed){
  if(mouseButton==LEFT){
     angle=angle+speed*angleDirection;
     if((angle>QUARTER_PI)||(angle<0)){
      angle=QUARTER_PI;
      }
      
   if(mouseButton==RIGHT){ 
       angle=angle+speed*angleDirection;
     if((angle>QUARTER_PI)||(angle<0)){
       angleDirection=-angleDirection;
       angle=QUARTER_PI;
       }
      }
     }
    }
}
1 Answers

You're almost there, but accidentally made a logical error: the right button condition is nested inside the left button condition. Since the mouseButton can only be either left or right (but not both), the right button condition will never trigger. Simply move it outside of the left button condition:

if (mousePressed) {
    if (mouseButton==LEFT) {
      angle=angle+speed*angleDirection;
      if ((angle>QUARTER_PI)||(angle<0)) {
        angle=QUARTER_PI;
      }
    }
    if (mouseButton==RIGHT) {
      angle=angle+speed*angleDirection;
      if ((angle>QUARTER_PI)||(angle<0)) {
        angleDirection=-angleDirection;
        angle=QUARTER_PI;
      }
    }
  }

(Edit > Auto Format (Ctrl+T / CMD + T) will make it easier to spot {} issues)

Have fun learning!

Related