xxxxxxxxxx
79
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let potValue = 512;
let running = true;
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);
//created this flag variable to get the ball to drop again
if (!running) {
textSize(24);
fill(0);
text("Press 's' to run again", width / 2 - 100, height / 2);
return;
}
//mapping the value of the potentiometer to which direction the ball falls
wind.x = map(potValue, 0, 1023, -2.5, 2.5);
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;
position.y = height - mass / 2;
//standard s
if (serialActive) {
writeSerial("Ball bounced\n");
//sending this to arduino each time ball hits ground
}
}
if (position.x < -mass || position.x > width + mass) {
//preventing the ball from being registered when it rolls off the screen
running = false;
}
}
function applyForce(force) {
let f = p5.Vector.div(force, mass);
acceleration.add(f);
}
function keyPressed() {
if (key == ' ') {
//opening setup pop up window
setUpSerial();
}
if (key == 's') {
//preparing a new ball to drop resetting the values
fill('white');
position = createVector(width / 2, 0);
velocity = createVector(0, 0);
acceleration = createVector(0, 0);
running = true;
}
}
function readSerial(data) {
//just to avoid no readSerial error saving data
if (data != null) {
potValue = int(data);
}
}