xxxxxxxxxx
74
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.1*mass);
wind = createVector(0,0);
}
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) {
velocity.y *= -0.9; // A little dampening when hitting the bottom
position.y = height-mass/2;
}
}
function readSerial(data) {
if (data != null) {let fromArduino = trim(data); let sensorVal = int(fromArduino);
if (sensorVal < 600){
wind.x=1;
}
else if(sensorVal >= 600 && sensorVal < 800){
wind.x = 0;
}
else {
wind.x = -1;
}
}
let sendToArduino = position.y + 0.5 * mass + "\n";
writeSerial(sendToArduino);
}
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 === ' ') {
// serial communication
if (!serialActive) {
setUpSerial();
}
mass=random(15,80);
position.y=-mass;
velocity.mult(0);
}
}