Harsha Satya Vardhan
Harsha Satya Vardhan

Reputation: 57

Moving the circle in the directing of another circle revolving around it in canvas

I have a problem of moving the big circle in the direction of small circle when a button is pressed. can anyone help?

Goals:

  1. Make a circle on canvas [Done]
  2. Draw a small circle that rotates around the big circle [Done]
  3. Move the big circle for 5 pixels when a button is pressed in the direction of small circle pointing at that time [pending]
  4. add a drawing effect while moving [pending]

can we can use the coordinates of x and y in below at the point of button press and move the main circle in the direction? correct me if i am wrong

let x = r *2* cos(angle);


let y = r *2* sin(angle);

let angle = 0;


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



function draw() {
  background(0);
  stroke(255);
  strokeWeight(4);
  let cir = createVector(200,200);
  let velocity = createVector();
  
  
  
  
  let r = 10;
  k = circle(cir.x, cir.y, r * 2);

  strokeWeight(4);
  stroke(255);
  let x = r *2* cos(angle);
  let y = r *2* sin(angle);
  translate(200,200);
  point(x, y);
  angle += 0.01;
  
  if(mouseIsPressed){
    k.x += x;
    k.y += y;
  }
}
<html>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.js"></script>
</html>

Upvotes: 1

Views: 309

Answers (1)

Charlie Wallace
Charlie Wallace

Reputation: 1830

You can move the big circle in the direction of the small circle while keeping the small circle orbiting around the big circle by keeping track of the big circle's center.

Move the variable cir outside of draw so we hang on to any changes made to it.

We also need to calculate a move that is 5px along the line segment from the big circle's center and the small circle. To do this we can use the formula in this solution to find a point on a line segment

To prevent the small circle from rotating during the move we can increment the rotation angle only when the mouse is not down.

let angle = 0;
let cir;

function setup() {
  createCanvas(400, 400);
  cir = createVector(200,200);
}

function draw() {
  background(0);
  stroke(255);
  strokeWeight(4);
  let r = 10;
  circle(cir.x, cir.y, r * 2);
  strokeWeight(4);
  stroke(255);
  let x = r *2* cos(angle);
  let y = r *2* sin(angle);
  point(x +cir.x, y+cir.y);
 
  
  if(mouseIsPressed){ 
    cir.x = (1-0.025)*cir.x+0.025*(x+cir.x);
    cir.y = (1-0.025)*cir.y+0.025*(y+cir.y);
  } else {
   angle += 0.01;
  }
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>

Upvotes: 2

Related Questions