xxxxxxxxxx
129
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let wmap;
let drag = 0.99;
let mass = 50;
let bounce = 0;
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);
// setUpSerial();
}
function draw() {
background(255);
wind = createVector(wmap, 0);
// if (!serialActive) {
// fill(0);
// text("Click the mouse to select Serial Port", 20, 30);
// } else {
// text("Connected", 20, 30);
// }
if (!serialActive) {
text("Press p to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
}
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.x > width) {
position.x = 0;
}
if (position.y > height - mass / 2) {
if (bounce == 0) {
bounce = 1;
} else {
bounce = 0;
}
}
if (position.y > height - mass / 2) {
velocity.y *= -1.25; // A little dampening when hitting the bottom
position.y = height - mass / 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 (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);
}
}
function keyPressed() {
if (key == "p") {
// important to have in order to start the serial connection!!
setUpSerial();
}
}
function readSerial(data) {
if (data != null) {
wmap = int(data);
console.log(wmap);
}
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
let sendToArduino = bounce;
console.log("bounce " + bounce);
writeSerial(sendToArduino);
}
// arduino code
// void setup() {
// Serial.begin(9600);
// pinMode(2, OUTPUT);
// while (Serial.available() <= 0) {
// Serial.println("0"); // send a starting message
// delay(300); // wait 1/3 second
// }
// }
// void loop() {
// while (Serial.available() > 0) {
// // read the incoming byte:
// int inByte = Serial.read();
// analogWrite(2, inByte);
// int WindPower = analogRead(A0);
// Serial.println(WindPower);
// }
// }