xxxxxxxxxx
83
let video;
let bodyPose;
let poses = [];
let targetXs = [];
let targetYs = [];
let dingSound;
function preload() {
// In this example we're "flipping" the camera so that
// the displayed image appears like a mirror image of
// our body.
bodyPose = ml5.bodyPose("BlazePose", { flipped: true });
dingSound = loadSound("ding.mp3");
}
function setup() {
createCanvas(640, 480);
// In current versions of p5.js you can mirror the camera
// image by setting the optional "flipped" property to true.
video = createCapture(VIDEO, { flipped: true });
video.size(width, height);
video.hide();
bodyPose.detectStart(video, gotPoses);
// pick initital target coordinates
for (let i = 0; i < 2; i++) {
targetXs[i] = random(20, width - 20);
targetYs[i] = random(20, height - 20);
}
}
function gotPoses(results) {
poses = results;
console.log(results);
}
function draw() {
// Draw the webcam video
image(video, 0, 0, width, height);
// Draw the targets
for (let i = 0; i < 2; i++) {
ellipse(targetXs[i], targetYs[i], 10, 10);
}
if (poses.length > 0) {
let leftX = poses[0].left_wrist.x;
let leftY = poses[0].left_wrist.y;
let rightX = poses[0].right_wrist.x;
let rightY = poses[0].right_wrist.y;
// Draw the detected points
ellipse(leftX, leftY, 10, 10);
ellipse(rightX, rightY, 10, 10);
// Calculate the distance from the detected points to the targets
let distance = 0;
for (let i = 0; i < 2; i++) {
let leftDistance = dist(leftX, leftY, targetXs[i], targetYs[i]);
let rightDistance = dist(rightX, rightY, targetXs[i], targetYs[i]);
// We take the "better" distance between left and right wrist
if (leftDistance < rightDistance) {
distance = distance + leftDistance;
} else {
distance = distance + rightDistance;
}
}
// If the distance is below a threshold, play a sound and pick
// new coordinates
if (distance < 50) {
dingSound.play();
for (let i = 0; i < 2; i++) {
targetXs[i] = random(20, width - 20);
targetYs[i] = random(20, height - 20);
}
}
}
}