Hi
I’m trying to enable bouncing balls effect with spring dynamics.
I’ve tweaked the chain example a bit a here’s the code I’m working on:
Spring2D s1, s2;
float gravity = 9.0;
float mass = 5;
void setup() {
size(800, 600);
fill(255, 126);
// Inputs: x, y, mass, gravity
s1 = new Spring2D(0.0, width/2, mass, gravity);
s2 = new Spring2D(0.0, width/2, mass, gravity);
}
void draw() {
background(0);
s1.update(mouseX, mouseY);
s1.display(mouseX, mouseY);
s2.update(s1.x, s1.y);
s2.display(s1.x, s1.y);
// the collider rectangle
stroke(255);
strokeWeight(2);
rect(50, 50, 700, 500);
}
class Spring2D {
float vx, vy; // The x- and y-axis velocities
float x, y; // The x- and y-coordinates
float gravity;
float mass;
float radius = 30;
float stiffness = 0.2;
float damping = 0.9;
Spring2D(float xpos, float ypos, float m, float g) {
x = xpos;
y = ypos;
mass = m;
gravity = g;
}
void update(float targetX, float targetY) {
float forceX = (targetX - x) * stiffness;
float ax = forceX / mass;
vx = damping * (vx + ax);
x += vx;
float forceY = (targetY - y) * stiffness;
forceY += gravity;
float ay = forceY / mass;
vy = damping * (vy + ay);
y += vy;
if (x <= 50) {
mouseX = 50 + int(radius);
}
}
void display(float nx, float ny) {
noStroke();
ellipse(x, y, radius*2, radius*2);
stroke(255);
line(x, y, nx, ny);
}
}
The rectangle line is the border and I don’t want the balls to cross hat but it does even if I tell it not to. See:
if (x <= 50) {
mouseX = 50 + int(radius);
I think it’s because dynamics still apply.
Then I tried:
if (x <= 50) {
s1.x = 50 + int(radius);
s2.x = 50 + int(radius);
}
With that, I’m getting a weird flashing balls.
How can I achieve bounce-back effect relative to damping, stiffness, mass?