xxxxxxxxxx
79
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let ard_wind = 1; //initializing the wind speed
let bit;
function setup() {
createCanvas(640, 360);
position = createVector(width / 2, 0);
velocity = createVector(0, 0);
acceleration = createVector(0, 0);
gravity = createVector(0, 0.5 * mass);
wind = createVector(0, 0);
bit = 0; //initializing the value for the LED
}
function draw() {
background(255);
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
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;
bit = 1; //lighting up the LED upon collision with "the ground"
} else {
bit = 0; //turning off the LED when the ball is not touching "ground"
}
}
}
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 = ard_wind * -1; //when left arrow is pressed, the velocity of the wind attains a negative value and the ball moves to the left
}
if (keyCode == RIGHT_ARROW) {
wind.x = ard_wind; //when the right arrow is pressed, the velocity of the wind attains a positive value and the ball moves to the right
}
if (keyCode == DOWN_ARROW) {
mass = random(15, 80);
position.y = -mass;
velocity.mult(0);
}
if (key == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
}
}
function readSerial(data) {
if (data != null) {
let sen = bit + "\n";
writeSerial(sen); //sending the values to light up or turn off the LED
ard_wind = map(data, 0, 300, 0, 10); // mapping the data received from arduino to a sensible range for the wind velocity
console.log(ard_wind);
}
}