xxxxxxxxxx
91
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let potentiometerValue = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
noFill();
position = createVector(width / 2, 0);
velocity = createVector(0, 0);
acceleration = createVector(0, 0);
gravity = createVector(0, 0.5 * mass);
wind = createVector(0, 0);
}
function draw() {
background(255);
if (!serialActive) {
textSize(20);
fill(255, 0, 0);
textAlign(CENTER);
text("Press 'SPACE' key to select serial port", width / 2, height / 2);
} else {
// Update wind force based on potentiometer value
wind.x = map(potentiometerValue, 0, 1023, -2, 2); // Map potentiometer value to wind force
applyForce(wind);
applyForce(gravity);
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
ellipse(position.x, position.y, mass, mass);
// Constraints for canvas boundaries
if (position.y > height - mass / 2) {
velocity.y *= -0.9; // Dampening on ground impact
position.y = height - mass / 2;
writeSerial(1 + '\n'); // Notify Arduino when ball bounces
}
if (position.y < mass / 2) {
velocity.y *= -0.9;
position.y = mass / 2;
}
if (position.x > width - mass / 2) {
velocity.x *= -0.9;
position.x = width - mass / 2;
}
if (position.x < mass / 2) {
velocity.x *= -0.9;
position.x = mass / 2;
}
writeSerial(0 + '\n'); // Ensure Arduino knows LED is off otherwise
}
}
function applyForce(force) {
let f = p5.Vector.div(force, mass); // Newton's 2nd law: F = M * A
acceleration.add(f);
}
function readSerial(data) {
let values = data.trim().split(","); // Expecting potentiometer value from Arduino
if (values.length > 0) {
potentiometerValue = int(values[0]); // Read and update wind based on potentiometer
}
}
function keyPressed() {
if (keyCode === 32) {
setUpSerial();
}
if (key == ' ') {
mass = random(15, 80);
position.y = -mass;
velocity.mult(0);
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}