xxxxxxxxxx
67
// Watch me live-code this https://www.youtube.com/watch?v=ZAge9pUM6do&t=254s
let shoulder = {
x: 100,
y: 300
}
let elbow = {
x: 200,
y: 200
}
let hand = {
x: 300,
y: 250
}
function setup() {
createCanvas(400, 400);
upperArm = dist(shoulder.x, shoulder.y, elbow.x, elbow.y)
forearm = dist(elbow.x, elbow.y, hand.x, hand.y)
}
function draw() {
background(220);
strokeWeight(2)
fill(255)
line(shoulder.x, shoulder.y, elbow.x, elbow.y)
line(elbow.x, elbow.y, hand.x, hand.y)
circle(shoulder.x, shoulder.y, 20)
circle(elbow.x, elbow.y, 20)
fill(100, 255, 100)
circle(hand.x, hand.y, 20)
if(mouseIsPressed){
if(dist(mouseX, mouseY, hand.x, hand.y) < 20){
hand.x = mouseX;
hand.y = mouseY
elbow = ik(shoulder, hand, forearm, upperArm)
}
}
strokeWeight(0.5)
line(shoulder.x, shoulder.y, hand.x, hand.y)
line(shoulder.x, shoulder.y, 400, shoulder.y)
}
function ik(a, b, A, B) {
let C = dist(a.x, a.y, b.x, b.y)
let th = acos( (B**2 + C**2 - A**2) / (2*B*C) )
let phi = atan2(-(b.y - a.y), b.x - a.x)
return {
x: a.x + B*cos(th + phi),
y: a.y - B*sin(th + phi)
}
}