Gravity for 'mouse follow' function


#1

How might gravity be implemented for this drum beater so that it can swing and droop?:

https://editor.p5js.org/munr/full/rkhA74j0Q

var x = 100,
  	y = 100,
  	angle1 = 0.0,
 	 	segLength = 45;

function setup() {
  createCanvas(820, 420);

  strokeWeight(7.0);
  stroke(255, 255, 255);
}

function draw() {
  background(186, 177, 167);

  //kick
  if (x > 370 && x < 370 + 172 &&
    y > 342 && y < 342 + 100)
    fill(242, 192, 0);
  else
    fill(150, 140, 127);
  ellipse(455, 435, 180, 180);

  //snare
  if (x > 235 && x < 235 + 151 &&
    y > 311 && y < 311 + 76)
    fill(242, 192, 0);
  else
    fill(150, 140, 127);
  ellipse(310, 350, 140, 63);

  //tom1
  if (x > 317 && x < 317 + 133 &&
    y > 203 && y < 203 + 73)
    fill(242, 192, 0);
  else
    fill(150, 140, 127);
  ellipse(385, 240, 125, 60);

  //tom2
  if (x > 455 && x < 455 + 130 &&
    y > 215 && y < 215 + 69)
    fill(242, 192, 0);
  else
    fill(150, 140, 127);
  ellipse(518, 250, 129, 64);

  //hihat
  if (x > 80 && x < 80 + 155 &&
    y > 285 && y < 285 + 65)
    fill(242, 192, 0);
  else
    fill(150, 140, 127);
  ellipse(155, 320, 175, 65);

  //ride
  if (x > 605 && x < 605 + 190 &&
    y > 195 && y < 195 + 67)
    fill(242, 192, 0);
  else
    fill(150, 140, 127);
  ellipse(695, 230, 190, 60);

  //floortom
  if (x > 540 && x < 540 + 195 &&
    y > 320 && y < 320 + 80)
    fill(242, 192, 0);
  else
    fill(150, 140, 127);
  ellipse(635, 360, 200, 80);
  
  //crash
  if (x > 52 && x < 65 + 140 &&
    y > 146 && y < 146 + 71)
    fill(242, 192, 0);
  else
    fill(150, 140, 127);
  ellipse(124, 180, 190, 68);
  
   //stands
  //hihat stand
  line(149, 700, 153, 355);
   //crash stand
  line(121, 215, 115, 289);
  //ride stand
  line(700, 260, 705, 330);

	//drum beater colour
  fill(255, 255, 255)

  
  //mouse follow function *based on code by Keith Peters*
  dx = mouseX - x;
  dy = mouseY - y;
  angle1 = atan2(dy, dx);
  x = mouseX - (cos(angle1) * segLength);
  y = mouseY - (sin(angle1) * segLength);

  segment(x, y, angle1);
  ellipse(x, y, 15, 15);
  fill(150, 140, 127);
}

function segment(x, y, a) {
  push();
  translate(x, y);
  rotate(a);
  line(0, 0, segLength, 0);
  pop();
}

#2

here is a great resource for physics … Nature of Code


#3

I’m short on time so I wonder if you could you break down how to implement a force or gravity system that would affect the segment/drum beater.


#4

Unless you know how to solve differential equations numerically, it is pretty hard to explain. You can see the formulas here: https://en.wikipedia.org/wiki/Pendulum_(mathematics).

Nature of Code (as @slow_izzm mentioned) is really well written, and has a chapter on Forces that can explain what you are looking for very nicely.

If you are looking for a quick and dirty solution, you should google for it, but you won’t learn anything from that.

P. S. Use markdown for your code with: ```
You can edit your OP.

void exampleCode() {
}