xxxxxxxxxx
59
let distance = 0; // Initialize distance variable
let drones = [];
function setup() {
createCanvas(400, 400);
// Create drones
for (let i = 0; i < 3; i++) {
drones.push({ x: random(width), y: random(height), speed: 0 });
}
}
function draw() {
background(255);
stroke(0);
fill(0);
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
}
// Calculate speed based on distance (custom mapping)
let speed = map(distance, 0, 100, 10, 1); // Adjust mapping based on desired speed ranges
// Draw drones with changing speed based on distance
for (let i = 0; i < drones.length; i++) {
ellipse(drones[i].x, drones[i].y, 20, 20); // Draw drone
moveDrone(i, speed); // Move drone based on speed
}
}
function keyPressed() {
if (key == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
}
}
function moveDrone(index, speed) {
// Update drone's position using Perlin noise
let xincrement = 0.01;
let yincrement = 0.01;
drones[index].x += map(noise(drones[index].x * xincrement), 0, 1, -speed, speed);
drones[index].y += map(noise(drones[index].y * yincrement), 0, 1, -speed, speed);
// Wrap drones around the canvas edges
drones[index].x = (drones[index].x + width) % width;
drones[index].y = (drones[index].y + height) % height;
}
function readSerial(data) {
if (data != null) {
// Map distance received from the ultrasonic sensor to a range of 0 to 100
distance = map(Number(data), 5, 50, 0, 100); // Adjust mapping based on the actual sensor range
print(distance);
}
}