xxxxxxxxxx
88
let rVal = 0;
let alpha = 255;
let left = 0;
let right = 0;
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
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);
textSize(18);
}
function draw() {
background(255);
applyForce(wind);
applyForce(gravity);
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
ellipse(position.x, position.y, mass, mass);
if (position.y > height - mass / 2) {
console.log("hit bottom");
left = 1;
velocity.y *= -0.9; // A little dampening when hitting the bottom
position.y = height - mass / 2;
} else {
left = 0;
}
if (!serialActive) {
fill(0);
text(
"Press Space Bar to select Serial Port and 'n' to add new ball",
20,
30
);
fill(255);
} else {
text("Connected", 20, 30);
text("rVal = " + str(rVal), 20, 50);
text("alpha = " + str(alpha), 20, 70);
wind.x = map(alpha, 0, 1023, -1, 1);
}
}
function readSerial(data) {
if (data != null) {
let fromArduino = split(trim(data), ",");
if (fromArduino.length == 2) {
rVal = int(fromArduino[0]);
alpha = int(fromArduino[1]);
}
let sendToArduino = left + "," + right + "\n";
writeSerial(sendToArduino);
}
}
function applyForce(force) {
let f = p5.Vector.div(force, mass);
acceleration.add(f);
}
function keyPressed() {
if (key == " ") {
setUpSerial();
}
if (key == "n") {
mass = random(15, 80);
position.y = -mass;
velocity.mult(0);
}
}