17-02-2020, 05:21 PM
(This post was last modified: 17-02-2020, 05:23 PM by josemendez.)
(17-02-2020, 01:35 PM)GrimCaplan Wrote: Could you actually provide some code snippets on how to accomplish what you're describing? I'd appreciate it.
For instance:
Hi,
Spring forces are calculated like this, using Hooke's law:
Code:
F = -kx
where F is the force, k the spring stiffness, and x the displacement. If you also want to throw some damping in, simply remove some of the velocity:
Code:
F = -kx - vel * damp
Optionally, multiply by mass (that is, divide by inverse mass) if you want to make the spring stiffness mass-independent.
In your case, say we want a force that tries to keep the y coordinate at zero:
Code:
Vector4 targetPosition = solver.positions[particleIndex];
targetPosition.y = 0;
solver.externalForces[particleIndex] = ((targetPosition - solver.positions[particleIndex]) * springStiffness - velocity * springDamping) / solver.invMasses[particleIndex];
(Here, targetPosition - solver.positions[particleIndex] is the spring displacement, "x". springStiffness is k.)
That's it. When you detect a touch, add another force that fights this one, trying to make the particle rise to a given height:
Code:
Vector4 targetPosition = solver.positions[particleIndex];
targetPosition.y = <your height>;
solver.externalForces[particleIndex] += ((targetPosition - solver.positions[particleIndex]) * springStiffness - velocity * springDamping) / solver.invMasses[particleIndex];