xxxxxxxxxx
128
let handsfree;
let showPoints = true;
let bob;
let anchor;
let velocity;
let restLength = 200;
let k = 0.02;
let gravity;
//------------------------------------------
function setup() {
createCanvas(640, 480);
bob = createVector(350, 350);
anchor = createVector(300, 0);
velocity = createVector(0, 0);
gravity = createVector(0, 0.6);
//you can change the maxNumHands if you want more than 1
handsfree = new Handsfree({
showDebug: true,
hands: true,
maxNumHands: 1
})
handsfree.start();
}
//------------------------------------------
function draw() {
background(200);
drawHand();
}
//------------------------------------------
function drawHand() {
//if the hands exist in the video
if (handsfree.data.hands) {
if (handsfree.data.hands.multiHandLandmarks) {
//get the associated data points
var landmarks = handsfree.data.hands.multiHandLandmarks;
var nHands = landmarks.length;
//draw the first hand
if (nHands > 0) {
var hand = landmarks[0];
var rescaledHand = rescaleHand(hand);
drawSpring(rescaledHand);
}
if (showPoints) {
drawDebugPoints(landmarks);
}
}
}
}
function drawSpring(hand){
strokeWeight(4);
stroke(255);
line(anchor.x, anchor.y, bob.x, bob.y);
fill(0);
circle(anchor.x, anchor.y, 32);
circle(bob.x, bob.y, 64);
anchor.x = hand[8].x;
anchor.y = hand[8].y;
//velocity.set(0, 0);
let force = p5.Vector.sub(bob, anchor);
let x = force.mag() - restLength;
force.normalize();
force.mult(-1 * k * x);
// F = A
velocity.add(force);
velocity.add(gravity);
bob.add(velocity);
velocity.mult(0.99);
}
//----------------------------------------------------------------
function drawDebugPoints(landmarks) {
var nHands = landmarks.length;
fill("black");
noStroke();
for (var h = 0; h < nHands; h++) {
for (var i = 0; i <= 20; i++) {
var px = landmarks[h][i].x;
var py = landmarks[h][i].y;
px = map(px, 0, 1, width, 0);
py = map(py, 0, 1, 0, height);
text(i, px + 5, py);
circle(px, py, 10);
}
}
}
//YOU DONT NEED TO KNOW HOW THIS WORKS
function rescaleHand(hand) {
//here we change the values of each
//of the objects in the array
//to be from 0 to width or height instead of 0 to 1
//you can mostly ignore how this works, but know
//that it remaps the values of the hand points to
//fit better within the p5 canvas
//the Array.map function IS NOT THE SAME AS THE p5 map function
return hand.map(
function(point) {
return {
x: map(point.x, 0, 1, width, 0),
y: map(point.y, 0, 1, 0, height)
}
});
}