F = m * a // here F is force, m is the mass of object, a is acceleration of object
So we can get a = k * dl / m, we can set strength = k / m, then get this:
a = strength * dl
Then we get delta x and delta y like this:
// if we alread computed delta x as x, delta y as y
l = Math.sqrt(x * x + y * y);
dl = (l - distance);
acceleration = strength dl; // => strength (l - distance)
dv = acceleration dt; // => strength (l - distance) dt
// next (x / l) means get delta in x axis
dvx = dv dt x / l; // => x (l - distance) strength dt dt / l
// next (y / l) means get delta in y axis
dvy = dv dt y / l; // => y (l - distance) strength dt * dt / l
Here we do some change to the variable.
l = Math.sqrt(x * x + y * y);
l = (l - distances[i]) / l * strengths[i] * (dt * dt);
x *= l, y *= l;
You can see the only difference with here forceLink code is dt * dt and alpha.
My problem with compute delta x and delta y
My problem is here:
x = target.x - source.x; // instead of target.x + target.vx - source.x - source.vx
y = target.y - source.y; // insrtead of target.y + target.vy - source.y - source.vy
If we add target.vx - source.vx (call this dvx) or target.vy - source.vy (call this dvy), image that,
spring distance is geting larger and larger, so dlx = target.x - source.x is getting lagger
the velocity is geting smaller and smaller, so dvx = target.vx - source.vx is getting smaller
al last, dlx + dvx will become smaller, it will make the force become smaller, then the dx and dy will change less.
Here is the thing, I think
forceLink
is mean to implement aspring force
, if so, now code of the force has a issue.Prove the implementation is spring force
I just give some reason to prove this is a implementation of spring force, you can skip this part if you alredy believe this.
According to Hooke's law:
And according to Newton's laws:
So we can get
a = k * dl / m
, we can setstrength = k / m
, then get this:Then we get delta x and delta y like this:
dl = (l - distance); acceleration = strength dl; // => strength (l - distance) dv = acceleration dt; // => strength (l - distance) dt // next (x / l) means get delta in x axis dvx = dv dt x / l; // => x (l - distance) strength dt dt / l // next (y / l) means get delta in y axis dvy = dv dt y / l; // => y (l - distance) strength dt * dt / l
Here we do some change to the variable.
You can see the only difference with here forceLink code is
dt * dt
andalpha
.My problem with compute delta x and delta y
My problem is here:
If we add
target.vx - source.vx
(call thisdvx
) ortarget.vy - source.vy
(call thisdvy
), image that,spring distance is geting larger and larger, so
dlx = target.x - source.x
is getting laggerthe
velocity
is geting smaller and smaller, sodvx = target.vx - source.vx
is getting smalleral last,
dlx + dvx
will become smaller, it will make the force become smaller, then thedx
anddy
will change less.