xxxxxxxxxx
76
let particle;
let video;
let trackingColor = [0, 255, 0]; // Red color to track
let threshold = 40; // Threshold for color matching
let lastPosition;
let currentPosition;
function setup() {
createCanvas(800, 600);
frameRate(30);
video = createCapture(VIDEO);
video.size(800, 600);
video.hide();
particle = new Projectile(createVector(random(0, width / 2), random(height / 2, height)), createVector(3, -12));
background(210);
}
function draw() {
background(210, 210, 210, 5);
// Update and draw the particle
particle.update();
particle.draw();
// Create new particle on DOWN_ARROW key press
if (keyIsDown(DOWN_ARROW)) {
background(210);
particle = new Projectile(createVector(random(0, width / 2), random(height / 2, height)), createVector(random(1, 8), random(-1, -15)));
}
// Display the video feed
image(video, 0, 0);
// Track the color and draw the marker
trackColor();
if (currentPosition) {
fill(255, 0, 0);
noStroke();
ellipse(currentPosition.x, currentPosition.y, 10, 10);
}
// Predict the next position based on velocity
if (lastPosition && currentPosition) {
let velocity = p5.Vector.sub(currentPosition, lastPosition);
let predictedPosition = p5.Vector.add(currentPosition, velocity);
fill(0, 255, 0);
ellipse(predictedPosition.x, predictedPosition.y, 10, 10);
}
lastPosition = currentPosition ? currentPosition.copy() : null;
}
function trackColor() {
video.loadPixels();
let closestDistance = Infinity;
currentPosition = null;
for (let y = 0; y < video.height; y++) {
for (let x = 0; x < video.width; x++) {
let index = (x + y * video.width) * 4;
let r = video.pixels[index];
let g = video.pixels[index + 1];
let b = video.pixels[index + 2];
let d = dist(r, g, b, trackingColor[0], trackingColor[1], trackingColor[2]);
if (d < threshold && d < closestDistance) {
closestDistance = d;
currentPosition = createVector(x, y);
}
}
}
}