Hi I’m looking to change some Processing code into p5.js code. I’m super new to both Processing and p5.js so I’m wondering if anyone can help transfer the bottom Processing code into p5.js compatible code. Please help! Thanks!!
int num = 5;
Spring[] springs = new Spring[num];
void setup() {
size(640, 360);
noFill();
springs[0] = new Spring(35, 10, 15, 0.98, 8.0, 0.1, springs, 0);
springs[1] = new Spring(27, 32, 15, 0.95, 9.0, 0.1, springs, 1);
springs[2] = new Spring(63, 20, 7, 0.90, 9.9, 0.1, springs, 2);
springs[3] = new Spring(55, 45, 15, 0.90, 9.9, 0.1, springs, 3);
springs[4] = new Spring(14, 70, 7, 0.90, 9.9, 0.1, springs, 4);
}
void draw() {
background(255);
line(42, 11, 59, 18);
line(62, 23, 58, 37);
line(22, 44, 17, 60);
for (Spring spring : springs) {
spring.update();
spring.display();
}
}
void mouseMoved() {
for (Spring spring : springs) {
spring.pressed();
}
}
void mouseReleased() {
for (Spring spring : springs) {
spring.released();
}
}
class Spring {
// Screen values
float xpos, ypos;
float tempxpos, tempypos;
int size = 20;
boolean over = true;
boolean move = false;
// Spring simulation constants
float mass; // Mass
float k = 0.2; // Spring constant
float damp; // Damping
float rest_posx; // Rest position X
float rest_posy; // Rest position Y
// Spring simulation variables
//float pos = 20.0; // Position
float velx = 0.0; // X Velocity
float vely = 0.0; // Y Velocity
float accel = 0; // Acceleration
float force = 0; // Force
Spring[] friends;
int me;
// Constructor
Spring(float x, float y, int s, float d, float m,
float k_in, Spring[] others, int id) {
xpos = tempxpos = x;
ypos = tempypos = y;
rest_posx = x;
rest_posy = y;
size = s;
damp = d;
mass = m;
k = k_in;
friends = others;
me = id;
}
void update() {
if (move) {
rest_posy = mouseY;
rest_posx = mouseX;
}
force = -k * (tempypos - rest_posy); // f=-ky
accel = force / mass; // Set the acceleration, f=ma == a=f/m
vely = damp * (vely + accel); // Set the velocity
tempypos = tempypos + vely; // Updated position
force = -k * (tempxpos - rest_posx); // f=-ky
accel = force / mass; // Set the acceleration, f=ma == a=f/m
velx = damp * (velx + accel); // Set the velocity
tempxpos = tempxpos + velx; // Updated position
if ((overEvent() || move) && !otherOver() ) {
over = true;
} else {
over = false;
}
}
// Test to see if mouse is over this spring
boolean overEvent() {
float disX = tempxpos - mouseX;
float disY = tempypos - mouseY;
if (sqrt(sq(disX) + sq(disY)) < size/2 ) {
return true;
} else {
return false;
}
}
// Make sure no other springs are active
boolean otherOver() {
for (int i=0; i<num; i++) {
if (i != me) {
if (friends[i].over == false) {
return false;
}
}
}
return false;
}
void display() {
if (over) {
stroke(000);
} else {
stroke(000);
}
ellipse(tempxpos, tempypos, size, size);
}
void pressed() {
if (over) {
move = true;
} else {
move = false;
}
}
void released() {
move = false;
rest_posx = xpos;
rest_posy = ypos;
}
}