Follow 3 / 追跡 3

セグメント化された線がマウスに追従します。各セグメントから次のセグメントへの相対角度はatan2()で計算され、次の位置はsin()とcos()で計算されます。Keith Petersのコードに基づいています。

atan2 follow chain
Interaction Math

View Source Code

/*
 * @name Follow 3
 * @arialabel Long segmented snake shape follows the user’s mouse as it moves 
 * @frame 710,400
 * @description A segmented line follows the mouse. The relative angle from
 * each segment to the next is calculated with atan2() and the position of
 * the next is calculated with sin() and cos(). Based on code from Keith Peters.
 */
let x = [],
  y = [],
  segNum = 20,
  segLength = 18;

for (let i = 0; i < segNum; i++) {
  x[i] = 0;
  y[i] = 0;
}

function setup() {
  // createCanvas(710, 400);
  createCanvas(windowWidth, windowHeight);
  strokeWeight(9);
  stroke(255, 100);
}

function draw() {
  background(0);
  dragSegment(0, mouseX, mouseY);
  for (let i = 0; i < x.length - 1; i++) {
    dragSegment(i + 1, x[i], y[i]);
  }
}

function dragSegment(i, xin, yin) {
  const dx = xin - x[i];
  const dy = yin - y[i];
  const angle = atan2(dy, dx);
  x[i] = xin - cos(angle) * segLength;
  y[i] = yin - sin(angle) * segLength;
  segment(x[i], y[i], angle);
}

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

License

Source code is available on GitHub p5.js website legacy.

All examples are licensed under CC BY-NC-SA 4.0.