How to partially rotate a line around a point of origin? (Making a stick figure wave)

Viewed 69

I've drawn a stick figure in p5.js and I'm trying to make it wave. Essentially I have to rotate the line making up its arm around the origin (coord (40,290)) partially.

I want it to bounce between the red line and blue line given in the code below in order to make it look like it's waving. I'm not really sure how to do this though. I've been trying to use the rotate() function but haven't found much success.

Any help would be much appreciated.

function setup() {
  createCanvas(400, 400);
  background(220);
}

/*
MY SKETCH OVERVIEW:

Person 1 is waving using animation
*/

function draw() {
  //person1
  stroke('black');
  line(20, 395, 40, 355); //left leg
  line(40, 355, 60, 395); //right leg
  line(40, 355, 40, 250); //body
  line(40, 290, 20, 320); //left arm
  ellipse(40, 220, 60); //head

  //person1 waving (animation)
  stroke('red');
  line(40, 290, 60, 250); //p1 right arm

  stroke('blue');
  line(40, 290, 80, 285);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

1 Answers

In order to use rotate to make the image wave you can first translate the hinge point of the image's arm to the center of rotation, rotate and then translate back to where the arm joins the body.

function setup() {
  createCanvas(400, 400);
  background(220);
}

// Person 1 is waving using animation

var theta=0;
var increaseAngle=true;
function draw() {
  // set background so we get animation
  background(220);
  //person1
  stroke('black');
  line(20, 395, 40, 355); //left leg
  line(40, 355, 60, 395); //right leg
  line(40, 355, 40, 250); //body
  line(40, 290, 20, 320); //left arm
  ellipse(40, 220, 60); //head

  // translate so that the hinge point of the right arm is centered
  translate(40, 290);
  rotate(theta);
  translate(-40, -290);

  //person1 waving (animation)
  stroke('red');
  line(40, 290, 60, 250); //p1 right arm
  if (increaseAngle){
    theta += 0.01;
  } else {
    theta -= 0.01;
  }
  // reverse motion when theta reaches an extreem
  if (theta > PI/2){
   increaseAngle = false;  
  } 
  if (theta < 0){
    increaseAngle = true;  
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>

Related