public VerletConstraint(ref VerletParticle particle1, ref VerletParticle particle2, float restingDistance) { this.particle1 = particle1; this.particle2 = particle2; this.restingDistance = restingDistance; }
void SatisfyConstraints() { for (int iter = 0; iter < numOfIter; ++iter) { //constrain in a box for (int i = 0; i < particles.Count; ++i) { particles [i].position = Vector3.Min(Vector3.Max(particles [i].position, new Vector3(0, 0, 0)), new Vector3(1000, 1000, 1000)); } //rest length constraints //就是限制两个粒子间距是restlength:|p2-p1| = restlength //求出位置差,两头分别移动一半距离 for (int i = 1; i < particles.Count; ++i) { VerletParticle prevParticle = particles [i - 1]; VerletParticle particle = particles [i]; Vector3 delta = particle.position - prevParticle.position; //正常的计算 float deltaLength = delta.magnitude; //Mathf.Sqrt (delta * delta); float diff = (deltaLength - restLength) / deltaLength; prevParticle.position += delta * 0.5f * diff; particle.position -= delta * 0.5f * diff; //优化平方根(泰勒展开) // delta = delta * restLength * restLength / ((Vector3.Dot (delta, delta) + restLength * restLength) - 0.5f); // prevParticle.position += delta; // particle.position -= delta; } } }
public VerletConstraint(ref VerletParticle particle1, ref VerletParticle particle2) { this.particle1 = particle1; this.particle2 = particle2; // Assume resting distance as the current distance between the particles restingDistance = (particle1.Position - particle2.Position).magnitude; }
// Use this for initialization void Start() { particles = new List <VerletParticle> (); for (int i = 0; i < num; ++i) { VerletParticle newParticle = new VerletParticle(); newParticle.position = newParticle.prevPosition = transform.position + new Vector3(10 * i, 0, 0); particles.Add(newParticle); } }