xxxxxxxxxx
79
let velocity;
let gravity;
let position;
let led;
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);
}
function draw() {
background(255);
if (!serialActive) {
textAlign(CENTER);
text("Press Space Bar to select Serial Port", width / 2, height / 3);
} else {
text("Connected", width / 2, height / 3);
}
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) {
velocity.y *= -0.9; // A little dampening when hitting the bottom
position.y = height - mass / 2;
}
console.log(position.y);
if (position.y >= 360) {
led = 1;
} else if (position.y <= 330) {
led = 0;
}
wind.x = map(alpha, 0, 1023, -1, 1);
}
function keyPressed() {
if (key == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
}
}
function readSerial(data) {
console.log(data);
}
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 (keyCode == LEFT_ARROW) {
wind.x = -1;
}
if (keyCode == RIGHT_ARROW) {
wind.x = 1;
}
if (key == " ") {
mass = random(15, 80);
position.y = -mass;
velocity.mult(0);
}
}