xxxxxxxxxx
65
let position, velocity, acceleration, gravity, wind; // vectors
let drag = 0.99, mass = 50, hasBounced = false;
function setup() {
createCanvas(640, 360);
noFill();
position = createVector(width/2, 0);
velocity = createVector(0,0);
acceleration = createVector(0,0);
gravity = createVector(0, 0.5*mass);
wind = createVector(0,0);
textAlign(CENTER);
textSize(18);
}
function draw() {
background(255);
applyForce(wind);
applyForce(gravity);
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
fill(hasBounced ? 'green' : 'white')
ellipse(position.x,position.y,mass,mass);
if (position.y > height-mass/2) {
velocity.y *= -0.9; // A little dampening when hitting the bottom
position.y = height-mass/2;
if (!hasBounced && abs(velocity.y) > 1) {
hasBounced = true;
setTimeout(() => hasBounced = false, 100); // Set hasBounced to false after 0.1 s
}
}
if (!serialActive) {
background(8);
fill('white');
text("Press c to connect to the Arduino", width/2, height/2)
}
}
function applyForce(force){
// Newton's 2nd law: F = M * A
// or A = F / M
let f = p5.Vector.div(force, mass);
acceleration.add(f);
}
function keyPressed(){
if (key == ' '){
mass = random(15,80);
position.set(width/2, -mass);
velocity.mult(0);
gravity.y = 0.5*mass;
wind.mult(0);
} else if (key == 'c') {
setUpSerial(); // Start the serial connection
}
}
function readSerial(data) {
if (data != null) { // Ensure there's actually data
wind.x = map(int(data), 0, 1023, -2, 2);
writeSerial((hasBounced ? 1 : 0) + '\n');
}
}