xxxxxxxxxx
65
// VARIABLES
let segments = []
const numberOfSegments = 3
const segmentLength = 50
const initialX = 0
const initialY = 0
const initialAngle = 0
let base // Vector with the position of the base
let vertical // Vector at the top, pointing it makes the segments vertical
let target // Vector at which the end of the segments is pointing
// SETUP
function setup() {
createCanvas(600, 400);
base = createVector(width/2, height)
vertical = createVector(width/2, 0)
target = createVector(width/2, 0)
for (let i = 0; i < numberOfSegments; i++) {
const segment = new Segment(
initialX,
initialY,
segmentLength,
initialAngle
)
segments.push(segment)
}
}
// DRAW
function draw() {
background(51);
drawLimits()
calculateTargetXY()
// Make segments follow their target
for (let i = 0; i < segments.length; i++) {
const x = i === 0 ? target.x : segments[i-1].a.x
const y = i === 0 ? target.y : segments[i-1].a.y
segments[i].follow(x, y)
segments[i].update()
}
// Fix the segments to the base and display them
for (let i = segments.length - 1; i >= 0; i--) {
const pos = i === segments.length - 1 ? base : segments[i + 1].b
segments[i].setA(pos.x, pos.y)
segments[i].show(i / segments.length)
}
}
const drawLimits = () => {
stroke(70)
strokeWeight(1)
noFill()
circle(width/2, height, numberOfSegments * segmentLength * 2)
}
const calculateTargetXY = () => {
const ratio = 0.97
target.x = ratio * target.x + (1 - ratio) * mouseX
target.y = ratio * target.y + (1 - ratio) * mouseY
}