xxxxxxxxxx
100
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let potValue = 0; // potentiometer value
let serialConnected = false;
let onGround = false; // whether ball is on the ground
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 (!serialConnected) {
textAlign(CENTER, CENTER);
fill(0);
text("Press 'Space' key on the keyboard", width / 2, height / 2);
return;
}
applyForce(wind);
applyForce(gravity);
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
// check for bounce on the x axis
if (position.x > width - mass / 2) {
if(!onGround){
position.x = width - mass / 2;
velocity.x *= -0.9;
}
}
else if (position.x < mass / 2) {
position.x = mass / 2;
velocity.x *= -0.9;
}
// check for bounce on the y axis
if (position.y > height - mass / 2) {
velocity.y *= -0.9;
position.y = height - mass / 2;
if (!onGround) {
sendBounceSignal();
onGround = true;
}
} else {
onGround = false;
}
wind.x = map(potValue, 0, 1023, -1, 1);
ellipse(position.x, position.y, mass, mass);
// boundaries on x axis
if (position.x > width - mass / 2 || position.x < mass / 2) {
velocity.x *= -0.9;
}
}
function applyForce(force) {
let f = p5.Vector.div(force, mass);
acceleration.add(f);
}
// bouncing signal to Arduino
function sendBounceSignal() {
if (serialActive) {
let sendToArduino = "1\n";
writeSerial(sendToArduino);
}
}
// receive data from Arduino
function readSerial(data) {
potValue = int(trim(data));
}
// initialize serial connection
function keyPressed() {
if (key == ' ') {
mass = random(10,100);
setUpSerial();
serialConnected = true;
}
}
function serialOpened() {
serialActive = true;
}