xxxxxxxxxx
118
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let rVal = 0;
let alpha = 255;
let left = 0; // True (1) if mouse is being clicked on left side of screen
let right = 0; // True (1) if mouse is being clicked on right side of screen
let serialSetup = false;
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);
// Set up serial connection
setUpSerial();
textSize(20);
}
function draw() {
background(255);
if (serialSetup) {
let windtext = "";
if (alpha < 300) {
wind.x = -1;
windtext = "Wind : Right";
} else if (alpha > 800) {
wind.x = 1;
windtext = "Wind : Left";
} else {
wind.x = 0;
windtext = "No wind.";
}
push();
fill(0);
text(windtext, 20, 50);
pop();
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(
"Bounce! Position Y: " + position.y + ", Velocity Y: " + velocity.y
);
left = 1;
} else {
left = 0;
}
}
}
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);
}
}
// This function will be called by the web-serial library
// with each new *line* of data. The serial library reads
// the data until the newline and then gives it to us through
// this callback function
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 to set up the serial connection
function setUpSerial() {
// Use serial.js or any other appropriate method to set up serial connection
// Example: serial = new p5.SerialPort();
}
// Function to write data to Arduino
function writeSerial(data) {
// Use serial.js or any other appropriate method to write data to Arduino
}